text:
Q: I need multiple PDF files to download for each loop using dompdf With the below code I am getting all the loop data in one pdf file. But my requirement is I need a separate pdf file for each loop. So for each loop, I need user data in a separate pdf file that has to be download. I am working on it but getting all data in a single pdf only. So any suggestions to this code are very helpful thank you
<?php
include 'dbconfig.php';
require_once 'dompdf/autoload.inc.php';

use Dompdf\Dompdf;

if(isset($_POST['submit'])){
    $html = "";
    foreach ($_POST['check'] as $key => $val) {
        $qry = mysql_query("SELECT * FROM jain_college where id=".$val);
        $row=mysql_fetch_array($qry);

        $status=$row['status'];
        $name=$row['name'];

        $html.='

                e-Receipt for Payment
               Date:'.$row['date'].'

                Receipt Number
                '. $row['number'].'

                Year
                '.$row['sem'].'

                Program Name
                '. $row['program'].'

                Course Name
                '. $row['course'].'

                Application Number/Reg Number
                '. $row['USN'].'

                Student Name
                '. $row['name'].'

                Student Mobile Number
                '.$row['mobile'].'

';

        if($status=='1') {
            $html.= '

                    Tuition Fees
                    '. $row['tuition'].'

                    A&A Fees
                    '.$row['A_Fees'].'

                    Total Amount:
                    '. $row['total'].'

';
        }
        if($status=='2') {
            $html.='

                    DD Number
                    '.$row['ddnumber'].'

                    Bank Name
                    '.$row['bank'].'

                    DD Date
                    '. $row['cashdate'].'

                    Amount:
                    '.$row['amount'].'

                    Drawn in Favour of:
                    '. $row['favour'].'

';
            }

            if($status=='3') {
                $html.='

                        UTR Number
                        '. $row['rtgs_number'].'

                        Bank Name
                        '. $row['rtgs_bank'].'

                        NEFT/RTGS Date
                        '. $row['rtgs_date'].'

                        Amount:
                        '. $row['rtgs_amount'].'

';

            }
            if($status=='4') {
                $html.='

                        Cheque Number
                        '.$row['cheque_number'].'

                        Bank Name
                        '.$row['cheque_bank'].'

                        Cheque Date
                        '.$row['cheque_date'].'

                        Amount:
                        '. $row['cheque_amount'].'

                        Drawn in Favour of:
                        '. $row['Cheque_favour'].'

';
                }

                $html.='

                   PAN Number:
                        '.$row['pan'].'

                   Remarks:
                        '.$row['remark'].'

                    ';
            }

            $dompdf= new Dompdf();
            $dompdf->loadHtml($html);

            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();

            $dompdf->stream($name);
        }

A: you can do this by modifying your code a little bit. just move the pdf creation process inside the loop and give it a try.
if(isset($_POST['submit'])){

foreach ($_POST['check'] as $key => $val) {
    $html = "";
    $qry = mysql_query("SELECT * FROM jain_college where id=".$val);
    $row=mysql_fetch_array($qry);

    $status=$row['status'];
    $name=$row['name'];

    $html.='

            e-Receipt for Payment
           Date:'.$row['date'].'

            Receipt Number
            '. $row['number'].'

            Year
            '.$row['sem'].'

            Program Name
            '. $row['program'].'

            Course Name
            '. $row['course'].'

            Application Number/Reg Number
            '. $row['USN'].'

            Student Name
            '. $row['name'].'

            Student Mobile Number
            '.$row['mobile'].'

';

    if($status=='1') {
        $html.= '

                Tuition Fees
                '. $row['tuition'].'

                A&A Fees
                '.$row['A_Fees'].'

                Total Amount:
                '. $row['total'].'

';
    }
    if($status=='2') {
        $html.='

                DD Number
                '.$row['ddnumber'].'

                Bank Name
                '.$row['bank'].'

                DD Date
                '. $row['cashdate'].'

                Amount:
                '.$row['amount'].'

                Drawn in Favour of:
                '. $row['favour'].'

';
        }

        if($status=='3') {
            $html.='

                    UTR Number
                    '. $row['rtgs_number'].'

                    Bank Name
                    '. $row['rtgs_bank'].'

                    NEFT/RTGS Date
                    '. $row['rtgs_date'].'

                    Amount:
                    '. $row['rtgs_amount'].'

';

        }
        if($status=='4') {
            $html.='

                    Cheque Number
                    '.$row['cheque_number'].'

                    Bank Name
                    '.$row['cheque_bank'].'

                    Cheque Date
                    '.$row['cheque_date'].'

                    Amount:
                    '. $row['cheque_amount'].'

                    Drawn in Favour of:
                    '. $row['Cheque_favour'].'

';
            }

            $html.='

               PAN Number:
                    '.$row['pan'].'

               Remarks:
                    '.$row['remark'].'

                ';

            $dompdf= new Dompdf();
            $dompdf->loadHtml($html);
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            $dompdf->stream($name);
        }

    }


text:
Q: React Native Text Trailing Space I have a simple Text element that loads data from json file,and every thing works fine,
but when i apply styling "justify",i found a big trailing space at the end of the Text and cannot remove it.
i tried trimming {mydata.trim()},
It did not work,or may be the trim worked but applying the Styling justify Add the trailing space again.
any Suggestions

redpajama_set_name: RedPajamaStackExchange


text:
Q: Strip space from all column values in Pandas I was working on a problem set where we have a lot of columns in a Pandas dataframe and many of these columns have trailing spaces. My question is, is there a better way to remove these spaces rather than creating a dynamic string (where we pass in column name as variable and append a strip() to it) and then executing it for every column.

A: Without an example it is not fully clear what you want to accomplish, but maybe the following will help:
import pandas as pd

df = pd.DataFrame({'A  ': [1, 2], 'B ': [4, 5], 'C': [8,9]})

The column headers do have trailing white spaces:
df.columns
Index([u'A  ', u'B ', u'C'], dtype='object')

Now you can use map and strip to get rid of them:
df.columns = df.columns.map(lambda x: x.strip())

or alternatively
df.columns = df.columns.map(str.strip)

or simply (which should be the preferred option)
df.columns = df.columns.str.strip()

If you now call
df.columns

it yields
Index([u'A', u'B', u'C'], dtype='object')

If it is about the values and not the headers, you can also use applymap:
df = pd.DataFrame({'A': ['1', '2  '], 'B': ['4 ', '5 '], 'C': ['8 ','9']})

     A   B   C
0    1  4   8
1  2    5    9

Then the following gets rid of the trailing white spaces:
df.applymap(lambda x: x.strip())

or alternatively (which is the better option):
df.applymap(str.strip)

   A  B  C
0  1  4  8
1  2  5  9

Note: This assumes, that you have only strings in your columns. You can also check this link.


text:
Q: Validate soap xml using validator against xsd I want to validate a soap request xml against a given xsd, The request can be huge so I can't just extract the content of soap body and do the validation, instead I do streaming based validation. I have already made xsd for the soap body (request part) and it does not contain any information about soap headers thus the validation gets failed, What I did was importing the soap schema to my xsd so that validator can identify the soap headers. It worked, but the validation gets successfull even if the soap body doesn't contain anything. How can we specify in the xsd that soap body should contain at least of particular element? My modified xsd is pasted below. thanks.
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema attributeFormDefault="qualified" targetNamespace="urn:sample"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tns="sample">
    <xsd:import namespace="http://schemas.xmlsoap.org/soap/envelope/"
                schemaLocation="http://schemas.xmlsoap.org/soap/envelope/"/>
    <xsd:complexType name="type1">
        <xsd:sequence>
            <xsd:element name="item" type="tns:type2" minOccurs="0" maxOccurs="unbounded"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="type3">
        <xsd:sequence>
            <xsd:element name="item" type="tns:type4" minOccurs="0" maxOccurs="unbounded"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:element name="element1">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="RETURN" type="tns:type3" minOccurs="0"/>
                <xsd:element name="HEADER" type="tns:type1"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="element2">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="RETURN" type="tns:type3" minOccurs="0"/>
                <xsd:element name="ERRORS" type="xsd:int"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

A: Try something similar to:
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
FileInputStream fileInputStream = new FileInputStream(new File("Simple.xsd"));
Schema schema = factory.newSchema(new StreamSource(fileInputStream));
Validator val = schema.newValidator();
FileInputStream fileInputStream2 = new FileInputStream(new File("Input.xml"));
val.validate(new StreamSource(fileInputStream2));


text:
Q: Add all the items for an attribute in DynamoDb to ElasticCache or Aws memory db for fast lookup I would appreciate some insights if this is a good/bad design choice.
I have a Dynamodb with an attribute of which all of which have to be fetched for an access pattern.
Instead of doing a parallel scan, would it be OK to write through in elastic cache(Redis set) so that it can looked up instantly?


text:
Q: Chrome issuing GET requests for images already loaded? I'm working on a JS game for Facebook and preloading all images. With chrome, but not yet seen on other browsers, once I open a new tab and surf a few sites chrome will issue fresh GET requests for images already in cache and on screen.
For the sake of testing I put ALL the images, at a 20x20 pixels size, on the side of the game. But if I open a new tab, then surf the web for 5 or so minutes, images that were not in the main game div will get reloaded when they get added to the page again (even though they are sitting on screen in a 'preloaded' div).
Rails 3.2 backend on Heroku.
I have tried disabling all Chrome plugins, clearing the cache, and a few different preloader strategies.
resolved
The page was caching fine, the images weren't. I added the following line to my rails production.rb, and the problem appears fixed.

A: The page was caching fine, the images weren't. I added the following line to my rails production.rb, and the problem appears fixed.
config.static_cache_control = "public, max-age=7200"

Thanks @chris for getting me on the right track!


text:
Q: Serve specific "template" page at any URL that ends in its slug Still new to WordPress, so please go easy on me.
Goal:
Prevent users of a specific role from viewing other custom post types made by users of same role.
Intended solution:
Modify the URL and redirect to a custom 403 page when the user ID doesn't match the post author. As such, if the person attempting to view example.com/%taxonomy%/%private-post-slug% would instead be redirected to example.com/%taxonomy%/403
Current redirect code:
<?php

add_action( 'template_redirect', 'private_posts_redirect');

function private_posts_redirect() {
    $user = wp_get_current_user();
    $post = get_post();
    $author = $post->post_author;
    if( get_post_type() == 'custom-post-type'){
        if(!$user->ID == $author || !$user->ID == 1){
           $intendedtarget = $_SERVER['REQUEST_URI'];
           $intendedtargetpath = parse_url( $intendedtarget, PHP_URL_PATH );
           $intendedtargetslug = pathinfo( $intendedtargetpath, PATHINFO_BASENAME );
           $redirectslug = '403';
           $redirecturl = str_replace( $intendedtargetslug, $redirectslug, $intendedtarget);
           wp_redirect($redirect_url);
           exit;
        }
    }
}

Current issue:
I've created a 403 page with '403' as the slug, I'm just not sure how to serve the content of that template page on any page that ends with that slug.
Tentative solution:
add_action('init' '403_page')

function 403_page(){
    if(stristr($_SERVER['REQUEST_URI'],'403')){
        DO_SOMETHING
    }
}

Edit: I know this only addresses the post author, I've already got the redirects for users that aren't of the role I'm looking to compartmentalize posts for. Additionally, I am using the  Advanced Post Queries plugin to only serve authors their posts, however that doesn't prevent them from viewing others posts by typing random numbers into the URL and getting to view sensitive RFQ, quote, and pricing info that's unique to that user.


text:
Q: How in Elasticsearch correctly to filter data between 2 date? I am confused with strange behavior of Elasticsearch (version 6.4). I am tring to filter data between 2 date.
When I use such URL:
http://localhost:9200/index/_search?q=date_time:[2018-10-27T00:00:00+TO+2018-10-27T23:00:00]

The result is empty. However, when I use URL with epoch_millis format of that date, it works and return correct result.
http://localhost:9200/index/_search?q=date_field:[1540576800000+TO+1540638000000]

In Kibana I see this information about data_field:

How in Elasticsearch correctly to filter data between 2 date?


text:
Q: How can I do calculations using Jquery and output them in html? I want to calculate percentage using javascript.
If the selected value in place1 & place2 is not equal then the calculation should be displayed in both flvalue & flvalues.
Ex: If value is 1000 and selected percent is 10 and selected place1 & place2 value is equal then flvalue should be 1100.
If value is 1000 and selected percent is 10 and selected place1 & place2 value is notequal then flvalue should be 1100 and flvalues should be 1100.

Value
<input type="text" name="gvalue" id="input" class="input" required/>Percentage
    <select name="percent" id="percent" class="input">
      <option value="Country" selected>Select Percentage</option>
      <option value="5">5</option>
      <option value="10">10</option>
      <option value="15">15</option>
    </select>

Place_1
<select name="place_1" id="place_1" class="input">
  <option value="Place" selected>Place</option>
  <option value="Place 1">Place 1</option>
  <option value="Place 2">Place 2</option>
  <option value="Place 3">Place 3</option>
</select>

Place_2
<select name="place_2" id="place_2" class="input">
  <option value="Place" selected>Place</option>
  <option value="Place 1">Place 1</option>
  <option value="Place 2">Place 2</option>
  <option value="Place 3">Place 3</option>
</select>

    Final Value
    <input type="text" name="flvalue" class="input" id="total" required/>
    <input type="text" name="flvalues" class="input" id="totals" required/>

A: You've just to add condition on places selected value :
if($('#place').val()=="10"){
   $('#totals').val(val + val * per / 100);
}else{
   $('#totals').val('');
}

And to add attach the change event also to the #place select :
$('#percent,#input,#place').on('change input', function() {

Hope this helps.

$('#percent,#input,#place').on('change input', function() {
  var val = Number($('#input').val()) || 0,
      per = Number($('#percent').val()) || 0;

  $('#total').val(val + val * per / 100);

  if($('#place').val()=="10"){
    $('#totals').val(val + val * per / 100);
  }else{
    $('#totals').val('');
  }
})

Value
<input type="text" name="gvalue" id="input" class="input" required/>

Percentage
<select name="percent" id="percent" class="input">
  <option value="Country" selected>Select Percentage</option>
  <option value="5">5</option>
  <option value="10">10</option>
  <option value="15">15</option>
</select>

Place
<select name="place" id="place" class="input">
  <option value="Country" selected>Place</option>
  <option value="5">Place 1</option>
  <option value="10">Place 2</option>
  <option value="15">Place 3</option>
</select>

Final Value
<input type="text" name="flvalue" class="input" id="total" required/>
<input type="text" name="flvalues" class="input" id="totals" required/>

A: Give it a try to this,

$('#percent,#input,#place_2,#place_1').on('change input', function() {
     var val = Number($('#input').val()) || 0,
     per = Number($('#percent').val()) || 0;
     var tot_am = val + val * per / 100;
     if ($('#place_1').val() != $('#place_2').val()) {
      $('#total').val(tot_am);
      $('#totals').val(tot_am);
     } else if ($('#place_1').val() == $('#place_2').val()) {
      $('#total').val()
      $('#totals').val('');
  }
});

    Value
<input type="text" name="gvalue" id="input" class="input" required/>Percentage
    <select name="percent" id="percent" class="input">
      <option value="Country" selected>Select Percentage</option>
      <option value="5">5</option>
      <option value="10">10</option>
      <option value="15">15</option>
    </select>

Place_1
<select name="place_1" id="place_1" class="input">
  <option value="Place" selected>Place</option>
  <option value="Place 1">Place 1</option>
  <option value="Place 2">Place 2</option>
  <option value="Place 3">Place 3</option>
</select>

Place_2
<select name="place_2" id="place_2" class="input">
  <option value="Place" selected>Place</option>
  <option value="Place 1">Place 1</option>
  <option value="Place 2">Place 2</option>
  <option value="Place 3">Place 3</option>
</select>

    Final Value
    <input type="text" name="flvalue" class="input" id="total" required/>
    <input type="text" name="flvalues" class="input" id="totals" required/>

Hope this will solve your problem.


text:
Q: How to find the chart version of subcharts from a released helm chart? I have installed a helm chart with subcharts and I want to find out which version of the subchart is installed. Is there any possible way in helm 3?

A: Following official Helm documentation:

*

*Helm.sh: Subcharts and globals

*Helm.sh: Charts

*Helm.sh: Helm dependency
You can get the version of a subchart used by a chart by following below example:

*

*Download the chart with $ helm pull repo/name --untar

*Go inside the chart directory

*Invoke command: $ helm dependency list
You can get a message that there are no dependencies:
WARNING: no dependencies at gce-ingress/charts
You can also get a message with dependencies and their versions:
NAME                VERSION REPOSITORY                                        STATUS
kube-state-metrics  2.7.*  https://kubernetes-charts.storage.googleapis.com/  unpacked

Additionally you can check the content of the prometheus/charts/kube-state-metrics/Chart.yaml for additional information.
Please let me know if that helped you.


text:
Q: C or C++ websocket client working example I am new to C and C++. I am trying to find small working example for any websocket library in C or C++ that can connect to websocket server. So, far I have explored, uWebsockets, libwebsockets, websocketpp, and boost::beast. None of them seem to have detailed documentation. I found some examples on boost::beast website at https://www.boost.org/doc/libs/develop/libs/beast/doc/html/beast/examples.html, however they are not working either. If I can find make a single working example I can work on it to learn more.
I tried this command, and it is connecting to yahoo endpoint:
wscat -c "wss://streamer.finance.yahoo.com/" -H 'Origin: https://finance.yahoo.com'
and print a random string.
wscat -c "wss://streamer.finance.yahoo.com/" -H 'Origin: https://finance.yahoo.com'
Connected (press CTRL+C to quit)
> {"subscribe":["ES=F","YM=F","NQ=F","RTY=F","CL=F","GC=F","SI=F","EURUSD=X","^TNX","^VIX","GBPUSD=X","JPY=X","BTC-USD","^CMC200","^FTSE","^N225","INTC"]}
< CgdCVEMtVVNEFduJQ0cYoP2/2/VeIgNVU0QqA0NDQzApOAFFlmEuP0iAgL/AwQJVlwxHR139ST1HZYBWqUNqC0JpdGNvaW4gVVNEsAGAgL/AwQLYAQTgAYCAv8DBAugBgIC/wMEC8gEDQlRD+gENQ29pbk1hcmtldENhcIECAAAAADbvcUGJAgAAhAG9ZWtC
< CgdCVEMtVVNEFQTtQkcY4KbH2/VeIgNVU0QqA0NDQzApOAFFUznHPkiAgMzPwQJVlwxHR139ST1HZQBrQUNqC0JpdGNvaW4gVVNEsAGAgMzPwQLYAQTgAYCAzM/BAugBgIDMz8EC8gEDQlRD+gENQ29pbk1hcmtldENhcIECAAAAADbvcUGJAgAAND7DT2tC

I tried simple python code like this
from websocket import create_connection
import json
import pprint
import re
import time
import datetime

def subscribe_yahoo ():
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0',
        'Accept': '*/*',
        'Accept-Language': 'en-US,en;q=0.5',
        'Sec-WebSocket-Version': '13',
        'Origin': 'https://finance.yahoo.com',
        'Sec-WebSocket-Key': 'nNtGm/0ZJcrR+goawlJz9w==',
        'DNT': '1',
        'Connection': 'keep-alive, Upgrade',
        'Sec-Fetch-Dest': 'websocket',
        'Sec-Fetch-Mode': 'websocket' ,
        'Sec-Fetch-Site': 'same-site' ,
        'Pragma': 'no-cache',
        'Cache-Control': 'no-cache',
        'Upgrade': 'websocket',
    }

    messages='{"subscribe":["INTC"]}'

    # Initialize the headers needed for the websocket connection
    initMessages = [
       messages,

    ]

    websocketUri = """wss://streamer.finance.yahoo.com/"""
    print (websocketUri)

    ws = create_connection(websocketUri,header=headers)
    for m in initMessages:
        print ("sending ", m)
        ws.send(m)

    message_stream = True
    i=0
    while message_stream:
        result = ws.recv()
        i=i+1
        print (str(i),' -- ', result)

subscribe_yahoo()

and it is working too.
I would really appreciate if someone can help me with a code that works similarly in c or c++.
Can someone explain if it is possible to use firefox source code https://searchfox.org/mozilla-central/source/netwerk/protocol/websocket  to implement a websocket client in C++ or not, or if someone has used firefox code successfully for websocket client.
I haven't asked for any recommended library, any library will do for my learning purpose.
Thanks in advance :)
Following example is copied as is from https://www.boost.org/doc/libs/develop/libs/beast/example/websocket/client/sync-ssl/websocket_client_sync_ssl.cpp
#include "example/common/root_certificates.hpp"

#include <boost/beast/core.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/beast/websocket/ssl.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <cstdlib>
#include <iostream>
#include <string>

namespace beast = boost::beast;         // from <boost/beast.hpp>
namespace http = beast::http;           // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio;            // from <boost/asio.hpp>
namespace ssl = boost::asio::ssl;       // from <boost/asio/ssl.hpp>
using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>

// Sends a WebSocket message and prints the response
int main(int argc, char** argv)
{
    try
    {
        // Check command line arguments.
        if(argc != 4)
        {
            std::cerr <<
                "Usage: websocket-client-sync-ssl <host> <port> <text>\n" <<
                "Example:\n" <<
                "    websocket-client-sync-ssl echo.websocket.org 443 \"Hello, world!\"\n";
            return EXIT_FAILURE;
        }
        std::string host = argv[1];
        auto const  port = argv[2];
        auto const  text = argv[3];

        // The io_context is required for all I/O
        net::io_context ioc;

        // The SSL context is required, and holds certificates
        ssl::context ctx{ssl::context::tlsv12_client};

        // This holds the root certificate used for verification
        load_root_certificates(ctx);

        // These objects perform our I/O
        tcp::resolver resolver{ioc};
        websocket::stream<beast::ssl_stream<tcp::socket>> ws{ioc, ctx};

        // Look up the domain name
        auto const results = resolver.resolve(host, port);

        // Make the connection on the IP address we get from a lookup
        auto ep = net::connect(get_lowest_layer(ws), results);

        // Set SNI Hostname (many hosts need this to handshake successfully)
        if(! SSL_set_tlsext_host_name(ws.next_layer().native_handle(), host.c_str()))
            throw beast::system_error(
                beast::error_code(
                    static_cast<int>(::ERR_get_error()),
                    net::error::get_ssl_category()),
                "Failed to set SNI Hostname");

        // Update the host_ string. This will provide the value of the
        // Host HTTP header during the WebSocket handshake.
        // See https://tools.ietf.org/html/rfc7230#section-5.4
        host += ':' + std::to_string(ep.port());

        // Perform the SSL handshake
        ws.next_layer().handshake(ssl::stream_base::client);

        // Set a decorator to change the User-Agent of the handshake
        ws.set_option(websocket::stream_base::decorator(
            [](websocket::request_type& req)
            {
                req.set(http::field::user_agent,
                    std::string(BOOST_BEAST_VERSION_STRING) +
                        " websocket-client-coro");
            }));

        // Perform the websocket handshake
        ws.handshake(host, "/");

        // Send the message
        ws.write(net::buffer(std::string(text)));

        // This buffer will hold the incoming message
        beast::flat_buffer buffer;

        // Read a message into our buffer
        ws.read(buffer);

        // Close the WebSocket connection
        ws.close(websocket::close_code::normal);

        // If we get here then the connection is closed gracefully

        // The make_printable() function helps print a ConstBufferSequence
        std::cout << beast::make_printable(buffer.data()) << std::endl;
    }
    catch(std::exception const& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Compiled using :
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0

g++ boost_test.cpp -o websocket-client-sync-ssl -lboost_system -pthread -lssl -lcrypto

./websocket-client-sync-ssl
Usage: websocket-client-sync-ssl <host> <port> <text>
Example:
    websocket-client-sync-ssl echo.websocket.org 443 "Hello, world!"

then as suggested:
./websocket-client-sync-ssl echo.websocket.org 443 "Hello, world!"

doesn't work
/websocket-client-sync-ssl streamer.finance.yahoo.com 443 "Hello, world!"
Error: The WebSocket stream was gracefully closed at both endpoints

A: Here's a quick demo using easywsclient:
#include "easywsclient.hpp"
#include <iostream>
#include <string>
#include <memory>
#include <mutex>
#include <deque>
#include <thread>
#include <chrono>
#include <atomic>

// a simple, thread-safe queue with (mostly) non-blocking reads and writes
namespace non_blocking {
template <class T>
class Queue {
    mutable std::mutex m;
    std::deque<T> data;
public:
    void push(T const &input) {
        std::lock_guard<std::mutex> L(m);
        data.push_back(input);
    }

    bool pop(T &output) {
        std::lock_guard<std::mutex> L(m);
        if (data.empty())
            return false;
        output = data.front();
        data.pop_front();
        return true;
    }
};
}

// eastwsclient isn't thread safe, so this is a really simple
// thread-safe wrapper for it.
class Ws {
    std::thread runner;
    non_blocking::Queue<std::string> outgoing;
    non_blocking::Queue<std::string> incoming;
    std::atomic<bool> running { true };

public:
    void send(std::string const &s) { outgoing.push(s); }
    bool recv(std::string &s) { return incoming.pop(s); }

    Ws(std::string url) {
        using easywsclient::WebSocket;

        runner = std::thread([=] {
            std::unique_ptr<WebSocket> ws(WebSocket::from_url(url));
            while (running) {
                if (ws->getReadyState() == WebSocket::CLOSED)
                    break;
                std::string data;
                if (outgoing.pop(data))
                    ws->send(data);
                ws->poll();
                ws->dispatch([&](const std::string & message) {
                    incoming.push(message);
                });
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
            ws->close();
            ws->poll();
        });
    }
    void close() { running = false; }
    ~Ws() { if (runner.joinable()) runner.join(); }
};

int main() {
    Ws socket("ws://localhost:40800");

    std::atomic<bool> run{true};
    auto receiver = std::thread([&] {
        std::string s;
        while (run) {
            if (socket.recv(s))
                std::cout << s << '\n';
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    });

    std::string line;
    while (std::getline(std::cin, line))
        socket.send(line);
    run = false;
    receiver.join();
    socket.close();
}

I tested it with a server using Crow:
// A simple websocket-based echo server
#include "crow_all.h"

int main() {
    crow::SimpleApp app;

    CROW_ROUTE(app, "/")
        .websocket()
        .onopen([&](crow::websocket::connection& conn){
                CROW_LOG_INFO << "new websocket connection";
                })
        .onclose([&](crow::websocket::connection& conn, const std::string& reason){
                CROW_LOG_INFO << "websocket connection closed: " << reason;
                })
        .onmessage([&](crow::websocket::connection& conn, const std::string& data, bool is_binary){
                    std::cout << "Received message: " << data << "\n";
                    if (is_binary)
                        conn.send_binary(data);
                    else
                        conn.send_text(data);
                });

    app.port(40800)
        .multithreaded()
        .run();
}

I built using this Makefile:
both: client server

INC = -Iexternal/easywsclient/ -Iexternal/crow/build/amalgamate/

LIBS = -leasywsclient -Lexternal/easywsclient -lboost_system -pthread

CXXFLAGS += ${INC}

client: client.o
    ${CXX} -o client client.o ${LIBS}

server: server.o
    ${CXX} -o server server.o ${LIBS}

To test, start the server, then the client. Then you can type random stuff into the client. It'll be sent to the server, printed out there, echoed back to the client, and printed back out there. Pretty much your typical, useless (but enough to prove they're communicating) network demo kind of thing.


text:
Q: If router is off for a few days, do you have an ip address as far as ISP is concerned? I have an ISP which assigns IP addresses dynamically. If I go out and turn my router off I am always assigned a new one once I turn it back on.
Does that mean that...
1) my previous IP goes elsewhere when my router is turned off?
2) i dont actually have an IP address if my router is off for a day or more?

A: This depends on your ISP's DHCP Server.
Each time you are leased a new IP address - it will be leased for a set perios of time (with my ISP, this is 8 days).
Half way through that period of time (4 days in my case), the router will re-apply for its IP and be leased it for a further 8 days - this is known as the DHCP Half-life.
If your router is off long enough that the full length of the DHCP lease is reached and your router makes no attempt to re-lease the IP - this IP address is freed up to go to another client and you lose the IP.
You may find after a long period of time that you power on your router and still get the same IP.
Some DHCP servers will exhaust their list of "never used" IPs before moving onto ones that have been leased and released.. meaning it may not have been reassigned.  When your router fires back up, it will ask if it is still allowed to use the same IP (which it thinks it still owns) and be told yes (because nothing else has needed it yet).
Another possibility is that you have a reserved IP.  Some ISPs offer static IPs, but still insist that you keep your router set to DHCP.  In this case, they set a reservation up - which means that the IP they assign you is reserved exclusively for the MAC address of your router - and it will be "assigned" to you every time your router asks for an IP, no matter how long it has been off for.


text:
Q: Is there a color picker plugin for Eclipse? I'm using Eclipse Galileo PDT for my work. I also use it to edit my CSS files.
Is there a plugin that lets me pick a color (from a palette or even anywhere from the screen) and which returns the HEX value of that color into my CSS file?

A: Jspresso Colors 'n Fonts

Just select any java string literal and right click on it to open the contextual popup menu... then select Jspresso>Choose Color... or select Jspresso>Choose Font...
Supports also tooltip : fly over your string literal to display the current color or font... and activate hyperlink to open the editor popup !

A: Aptana Studio has really great support for CSS.  CSS color picking is easy, you can grab a color from anywhere on the screen.
You can install Aptana as a plug into an existing Eclipse installation.
http://docs.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration

A: There are a few plugins at the Eclipse plugins site that might meet your needs.
CSS Designer looks promising:

JointLogic CSS Designer is an Eclipse plugin that provides CSS authoring facilities like - CSS Styles view, CSS declaration designer with preview and web-oriented color picker. It integrates with Eclipse Web Tools Platform (WTP) to allow CSS authoring while editing CSS and HTML files.

Here's a screesnhot from the homepage:

A: I would recommend to use external software: http://www.colorschemer.com/online.html
You can integrate it into Eclipse.

A: I have used this plugin called colors in both Galymeade and I just dropped into Galileo.
http://www.eclipseplugincentral.com/Web_Links-index-req-viewlink-cid-1281.html  you can copy the color code to/from clipboard or editor. Slider bar for coloring, color picker etc. I used it to edit css files on a recent project.  Good Luck.

A: You might want to check out the second example at http://eclipsescript.org/#example-scripts.

A: I created a Groovy Monkey script that opens Eclipse's color picker. It was inspired by what fornwall pointed at (second example of Eclipse Script plugin). It's also able to recognize if current selection is a color so it can be selected it in the picker.
The script is on gist.github, instructions included.
Having a shortcut key for a script is not (yet?) possible in Groovy Monkey, but Crtl+Alt+M runs the last executed script.

A: A good plugin to consider is the Designerator Color Plugin from the Designerator project. It contributes a Colors view as explained in this blog post. No need to install the whole software, the color view is in a separate feature that can be installed by itself.
The Sampler plugin could also be of interest. However it does not show a color picker dialog where one can select a color, it only has the color picker tool for selecting a color from the screen.


text:
Q: The packages to be newly installed are the same as the packages that should be autoremoved! I am noticing a very peculiar thing just after shifting to Debian-based distros.
root@Am-I-Helpful:~# uname -a
Linux Am-I-Helpful 4.3.0-kali1-amd64 #1 SMP Debian 4.3.3-5kali4
(2016-01-13) x86_64 GNU/Linux

The output of apt-get update && apt-get dist-upgrade is :
root@Am-I-Helpful:~# apt-get update && apt-get dist-upgrade
Hit:1 http://heanet.dl.sourceforge.net/project/ubuntuzilla/mozilla/apt all InRelease
Hit:2 http://kali.mirror.garr.it/mirrors/kali sana InRelease
Hit:3 http://kali.mirror.garr.it/mirrors/kali-security sana/updates InRelease
Reading package lists... Done
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages were automatically installed and are no longer required:
  libavcodec56 libavformat56 libavresample2 libavutil54 libdvbpsi9
  libfreerdp-rail1.1 libpostproc52 libswscale3 libvncclient0 libvpx1
  libx264-142
Use 'apt autoremove' to remove them.
The following NEW packages will be installed:
  libavcodec56 libavformat56 libavresample2 libavutil54 libdvbpsi9
  libfreerdp-rail1.1 libpostproc52 libswscale3 libvncclient0 libvpx1
  libx264-142
The following packages have been kept back:
  libarchive13 vlc vlc-nox vlc-plugin-notify vlc-plugin-samba
0 upgraded, 11 newly installed, 0 to remove and 5 not upgraded.
Need to get 0 B/5,605 kB of archives.
After this operation, 14.8 MB of additional disk space will be used.
Do you want to continue? [Y/n] n
Abort.

The surprising thing is :
It says
The following packages were automatically installed and are no longer required:
  libavcodec56 libavformat56 libavresample2 libavutil54 libdvbpsi9
  libfreerdp-rail1.1 libpostproc52 libswscale3 libvncclient0 libvpx1
  libx264-142
Use 'apt autoremove' to remove them.

On the other end, at the very next line it also states
The following NEW packages will be installed:
  libavcodec56 libavformat56 libavresample2 libavutil54 libdvbpsi9
  libfreerdp-rail1.1 libpostproc52 libswscale3 libvncclient0 libvpx1
  libx264-142

These are the same list of packages which are asked to be removed! I am not getting this as to how it is coming into picture.
The content of my /etc/apt/sources.list is :
# deb cdrom:[Debian GNU/Linux 2016.1 _Kali-rolling_ - Official Snapshot amd64 LIVE/INSTALL Binary 20160120-18:14]/ kali-rolling contrib main non-free
#deb cdrom:[Debian GNU/Linux 2016.1 _Kali-rolling_ - Official Snapshot amd64 LIVE/INSTALL Binary 20160120-18:14]/ kali-rolling contrib main non-free
#deb http://downloads.sourceforge.net/project/ubuntuzilla/mozilla/apt all main
#deb http://downloads.sourceforge.net/project/ubuntuzilla/mozilla/apt all main
deb http://http.kali.org/kali sana main non-free contrib
deb http://security.kali.org/kali-security/ sana/updates main contrib non-free
deb http://downloads.sourceforge.net/project/ubuntuzilla/mozilla/apt all main

Could someone please clarify as to what is happening here? How to solve this ambiguous case?

A: There is no ambiguity.
Apt is warning you that you could remove those packages if you want. If you use apt autoremove, they will be removed.
On the other side, until you do not remove them, they will be updated regularly.


text:
Q: Can we use parameters in case statement in snowflake sql stored procedure I am working on a stored procedure in snowflake using sql language which expects three parameters. I need to execute different sql queries based on the parameter value of the third parameter. For eg, if the 3rd parameter is A, then execute sql_query1. If 3rd parameter is B, then execute sql_query2 and so on. Is there a way to do this in snowflake stored procedure using sql language and not javascript.
Also, the parameters of the stored procedure will be used in the where clause to filter the data. Below is what I've done till now, however I'm getting syntax error:
create or replace procedure CASE_DEMO_CMS(CONTRACT_ID VARCHAR, VALID_FROM_TSTP TIMESTAMP_NTZ(9),product_System_code varchar)
RETURNS TABLE ()
LANGUAGE SQL
AS
declare
   res resultset;

    query varchar;

begin

    case

        when :product_system_code :='U2' then

                    query := 'SELECT

                        .......

                    WHERE ctrt.contract_id = ?

                    AND ctrt.valid_from_tstp = ?

                    AND ctrt.product_system_code= ?';

    res := (execute immediate :query using(contract_id,valid_from_tstp,product_system_code));

    return table(res);

else return 'Unspecified value'

end case;

end;
Error: Syntax error: unexpected when

A: The stored procedure should return the same output for each return part and  the comparision operator is =(not the :=):
CREATE OR REPLACE procedure CASE_DEMO_CMS(
                CONTRACT_ID VARCHAR,
                VALID_FROM_TSTP TIMESTAMP_NTZ(9),
                product_System_code varchar)
RETURNS TABLE (col TEXT, col2 INT)
LANGUAGE SQL
AS
declare
   res resultset;
   query varchar;
begin
    case when :product_system_code ='U2'
    then
         query := 'SELECT ctrt.some_col, ctrt.col2
                   FROM ctrt
                   WHERE ctrt.contract_id = ?
                   AND ctrt.valid_from_tstp = ?
                   AND ctrt.product_system_code= ?';
         res := (execute immediate :query
                using(contract_id,valid_from_tstp,product_system_code));
         return table(res);
    else
         query := 'SELECT ''Unspecified value'', NULL::INT';
         res := (execute immediate :query);
         return table(res);
    end case;
end;

Sample data:
CREATE OR REPLACE TABLE ctrt
AS
SELECT 1 AS contract_id, CURRENT_DATE() AS valid_from_tstp,
       'U2' AS product_system_code, 'text' AS some_col, 10 AS col2;

Call:
CALL CASE_DEMO_CMS(1, CURRENT_DATE(), 'U2');

Output:

Call:
CALL CASE_DEMO_CMS(1, CURRENT_DATE(), 'Some other value');

Output:


text: Q: Functionality of libflang `sect` calls I was looking at the perf profile for one of the spec2017 benchmark compiled with llvm. I saw hotness in few of the libflang routines. But I am not able to figure out what is the functionality of f90_sect_i8 function. I searched for sect calls but could not find anything substantial.


text:
Q: Determining all the processes started with a given executable in Linux I have this need to collect\log all the command lines that were used to start a process on my machine during the execution of a Perl script which happens to be a test automation script. This Perl script starts the executable in question (MySQL) multiple times with various command lines and I would like to inspect all of the command lines of those invocations. What would be the right way to do this? One possibility i see is run something like "ps -aux | grep mysqld | grep -v grep" in a loop in a shell script and capture the results in a file but then I would have to do some post processing on this and remove duplicates etc and I could possibly miss some process command lines because of timing issues. Is there a better way to achieve this.

A: Processing the ps output can always miss some processes. It will only capture the ones currently existing. The best way would be to modify the Perl script to log each command before or after it executes it.
If that's not an option, you can get the child pids of the perl script by running:
pgrep -P $pid -a

-a gives the full process command. $pid is the pid of the perl script. Then process just those.

A: You could use strace to log calls to execve.
$ strace -f -o strace.out -e execve perl -e 'system("echo hello")'
hello

$ egrep ' = 0$' strace.out
11232 execve("/usr/bin/perl", ["perl", "-e", "system(\"echo hello\")"], 0x7ffc6d8e3478 /* 55 vars */) = 0
11233 execve("/bin/echo", ["echo", "hello"], 0x55f388200cf0 /* 55 vars */) = 0

Note that strace.out will also show the failed execs (where execve returned -1), hence the egrep command to find the successful ones. A successful execve call does not return, but strace records it as if it returned 0.
Be aware that this is a relatively expensive solution because it is necessary to include the -f option (follow forks), as perl will be doing the exec call from forked subprocesses.  This is applied recursively, so it means that your MySQL executable will itself run through strace.  But for a one-off diagnostic test it might be acceptable.
Because of the need to use recursion, any exec calls done from your MySQL executable will also appear in the strace.out, and you will have to filter those out.  But the PID is shown for all calls, and if you were to log also any fork or clone calls (i.e. strace -e execve,fork,clone), you would see both the parent and child PIDs, in the form <parent_pid> clone(......) = <child_pid> so then you should hopefully then have enough information to reconstruct the process tree and decide which processes you are interested in.


text:
Q: Print only on recto (one paper side) with Word.interop I'm trying to print a document, only on recto, and not recto-verso.
So, I print my document with Word.Interop and before open document, set default printer parameters like this :
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
wordApp.Visible = false;

PrinterSettings settings = new PrinterSettings();
foreach (string printer in PrinterSettings.InstalledPrinters)
{
    settings.PrinterName = printer;
    if (settings.IsDefaultPrinter)
    {
        settings.Duplex = Duplex.Simplex;
    }
}
wordApp.Documents.Open(fullPath);

wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
wordApp.ActiveDocument.PrintOut(false);

wordApp.Quit(WdSaveOptions.wdDoNotSaveChanges);

This print well, but always in recto-verso. How can I change default printer parameters. Why settings.Duplex = Duplex.Simplex; doesn't work?
I checked, and Duplex value is simplex when the document open.


text:
Q: Handle reply messages properly after some operations in php I am developing an application on corePHP, whenever I am handling add, edit & delete operations I am redirecting with "header" method along with query strings appending in the URL like "http://mywebsite.com/my_file.php?added=1" and I am checking if that "added" is there or not in the URL with global variables like "isset($_GET['added'])", messages are showing fine but what is my problem here is "whenever I just refresh the page the same page the message is showing again & again as the parameter 'added' is present in the URL. I know there must be a proper way of handling this. So, Can anyone please suggest a proper way of handling this. Thanks.
My code is below:
Browser URL
http://mywebsite.com/my_website_page.php?added=1

my_website_page.php:
if(isset($_POST)){
  $is_success = my_method_todo_some_task($_POST);
  if($is_success ){
      header('Location: my_website_page.php?id='.$my_var.'&added=1');
      exit;
  }else{
      header('Location: my_website_page.php?id='.$my_var.'&added=0');
      exit;
  }
}

my_website_page.php :
if(isset($_GET['added'])) {
 if($_GET['added'] == 1){
    echo '
1 Record added successfully
';
 }else{
    echo '
Some problem occurred, please try again.
';
 }
}

I know this can be posible with sessions but if we use session then again the same problem will come. So any idea apart from using sessions. Thanks.

A: As a quick fix , i would reccomend to set a success or failure message in session
See:
       if($is_success ){
    $_SESSION['msg']="Record added successfully";
$_SESSION['successful']=1;
          header('Location: my_website_page.php?id='.$my_var);
          exit;
      }else{
$_SESSION['successful']=0;
    $_SESSION['msg']="Some problem occurred, please try again.";
          header('Location: my_website_page.php?id='.$my_var);
          exit;
      }

and in website.php:
   if(isset($_SESSION['successful']) && $_SESSION['successful'] ) {

    echo '
'. $_SESSION["msg"].'
';
 }
if(isset($_SESSION['successful']) && !$_SESSION['successful'] ) {
    echo '
'. $_SESSION["msg"].'
';
 }
unset($_SESSION['successfull']);
unset($_SESSION['msg']);
}

Dont forget add session_start() at top of each page.
Note:  There are several other methods to do it like ajax submission.

A: There's when session comes in handy
session_start();
if(isset($_POST)){
  $is_success = my_method_todo_some_task($_POST);
  if($is_success ){
      $_SESSION['added'] = 1;
      header('Location: my_website_page.php?id='.$my_var.'&added=1');
      exit;
  }else{
      $_SESSION['added'] = 0;
      header('Location: my_website_page.php?id='.$my_var.'&added=0');
      exit;
  }
}

if(!empty($_SESSION['added'])) {
  echo 'Your message here';
  unset($_SESSION['added']);
}


text:
Q: Proper alignment of three boxes I want two text boxes to appear next to a photo which is 5cm wide. The combined height of the boxes may be greater than or less than the height of the photo.
If the combined height is less than the photo, I want the text boxes aligned vertically with the top and the bottom of the photo thus:
+---------------------------------------+  +------------+
| Text1 text1 text1 text1 text1 text1   |  |            |
| text1 text1 text1 text1 text1.        |  |            |
+---------------------------------------+  |            |
                                           |   Photo    |
                                           |            |
+---------------------------------------+  |            |
| Text2 text2 text2 text2 text2 text2   |  |            |
| text2 text2 text2 text2 text2.        |  |            |
+---------------------------------------+  +------------+

If the combined height is greater than the photo, I want the two boxes below each other thus:
+---------------------------------------+  +------------+
| Text1 text1 text1 text1 text1 text1   |  |            |
| text1 text1 text1 text1 text1 text1   |  |            |
| text1 text1 text1 text1 text1 text1   |  |            |
| text1 text1 text1 text1 text1 text1   |  |   Photo    |
+---------------------------------------+  |            |
+---------------------------------------+  |            |
| Text2 text2 text2 text2 text2 text2   |  |            |
| text2 text2 text2 text2 text2 text2   |  |            |
| text2 text2 text2 text2 text2 text2   |  +------------+
| text2 text2 text2 text2 text2.        |
+---------------------------------------+

Is there any way to achieve this automatically? And if not, how can I best achieve what is shown in the first illustration? (I've experimented with both tabular/multirow setups and with floats, but I just can't get it right.)
Edit:
This is one of the things I've tried to no avail (replace 1988.jpg with an appropriate filename):
\documentclass{report}
\usepackage{graphicx}
\usepackage{multirow}

\begin{document}

\begin{tabular}{l r}
\fbox{\parbox[t]{8cm}{Text1 text1 text1 text1 text1 text1 text1 text1 text1 text1
text1 text1 text1 text1 text1.}}
 & \multirow{3}{*}{\parbox[t]{5cm}{\includegraphics[width=5cm,height=10cm]{1988.jpg}
}} \\
\parbox{8cm}{\vfill} & \\
\fbox{\parbox[b]{8cm}{Text2 text2 text2 text2 text2 text2 text2 text2 text2 text2
text2 text2 text2 text2 text2.}} & \\
\end{tabular}

\end{document}

A: You can box the text and the image, measure their heights and then act accordingly:
\documentclass{article}
\usepackage{graphicx}
\usepackage{adjustbox}

\newlength\PhotoWd
\setlength\PhotoWd{5cm}
\newlength\PhotoGap
\setlength\PhotoGap{20pt}
\newlength\TextWd
\setlength\TextWd{\dimexpr\textwidth-\PhotoWd-\PhotoGap\relax}

\newlength\TextHt
\newlength\ImageHt
\newlength\MaxHt

\newsavebox\TextBox
\newsavebox\ImageBox

\newcommand\PlaceTextImage[4][]{%
  \begin{lrbox}{\TextBox}
    \begin{minipage}{\linewidth}
    \fbox{\parbox{\dimexpr\TextWd-2\fboxsep-2\fboxrule\relax}{#2}}\par\medskip
    \fbox{\parbox{\dimexpr\TextWd-2\fboxsep-2\fboxrule\relax}{#3}}
    \end{minipage}
  \end{lrbox}%
  \savebox\ImageBox{\includegraphics[#1]{#4}}%
  \setlength\TextHt{\dimexpr\ht\TextBox+\dp\TextBox\relax}%
  \setlength\ImageHt{\dimexpr\ht\ImageBox+\dp\ImageBox\relax}%
  \setlength\MaxHt{\TextHt}
  \ifdim\ImageHt>\TextHt\relax
    \setlength\MaxHt{\ImageHt}
  \fi%
  \par\medskip\noindent
  \begin{minipage}[t][\MaxHt][t]{\TextWd}
  \fbox{\parbox[t]{\dimexpr\TextWd-2\fboxsep-2\fboxrule\relax}{#2}}%
  \ifdim\ImageHt>\TextHt\relax
    \par\vfill
  \else
    \par\medskip
  \fi%
  \fbox{\parbox[t]{\dimexpr\TextWd-2\fboxsep-2\fboxrule\relax}{#3}}
  \end{minipage}\hspace*{\PhotoGap}%
  \begin{minipage}[t][\MaxHt][t]{\PhotoWd}
  \adjustbox{valign=t}{\usebox\ImageBox}
  \end{minipage}\par\medskip%
}

\begin{document}

Text before

\PlaceTextImage[width=\PhotoWd,height=200pt]{some test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text}{some other text  test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text}{example-image-b}

Text after and before

\PlaceTextImage[width=\PhotoWd,height=40pt]{some test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text}{some other text  test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text test text}{example-image-b}

Text after

\end{document}

\PlaceTextImage has three mandatory arguments:
\PlaceTextImage{<upper text>}{<lower text>}{<image file>}

and an optional argument allowing you to specify options for \includegraphics.
Using the lengths \PhotoWd and \PhotoGap you can change the width for the photo and the gap between text and photo; the width for the text boxes is calculated automatically.

A: This can be done using a number of minipages to wrap and align the text appropriately.
\documentclass{report}
\usepackage[demo]{graphicx} % Remove [demo] for final version
\usepackage[export]{adjustbox}
\usepackage{calc,etoolbox}
\usepackage{fullpage} % Increase margins for these specific widths

\begin{document}

\newcommand{\imagebox}{\includegraphics[width=5cm,height=10cm,valign=t]{1988.jpg}}

\newcommand{\textboxes}{
     \noindent\begin{minipage}[t]{\linewidth}
     \fbox{\parbox[t]{8cm}{
     Text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
    text1 text1 text1 text1 text1.}}
    \par\vspace{1ex}\vfill
    \fbox{\parbox[b]{8cm}{
    Text2 text2 text2 text2 text2 text2 text2 text2 text2
    text2 text2 text2 text2 text2 text2 text2 text2 text2
    text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
    text2 text2 text2 text2 text2 text2 text2 text2 text2
    text2 text2 text2 text2 text2.}}
    \end{minipage}
}

% Calculate height of image and text boxes
\newlength{\imageboxheight}
\settototalheight{\imageboxheight}{\imagebox}
\newlength{\textboxesheight}
\settototalheight{\textboxesheight}{\textboxes}
\newlength{\maxTextBoxes}
\setlength{\maxTextBoxes}{\ifdimgreater{\textboxesheight}{\imageboxheight}{\textboxesheight}{\imageboxheight}}

% Typeset content
\noindent\begin{minipage}[t][\maxTextBoxes]{\textwidth}
    \noindent\begin{minipage}[t][\imageboxheight]{9cm}
    \textboxes\end{minipage}\begin{minipage}[t]{6cm}
    \imagebox
    \end{minipage}
\end{minipage}\vspace{\baselineskip} % A bit of extra space

% Following text starts after both image and text
Next paragraph starts here.

\end{document}

A: Here's an interface for such a construction.
\documentclass{article}
\usepackage{graphicx}
\usepackage[export]{adjustbox}
\usepackage{environ}
\usepackage{calc}

\newsavebox{\photobox}
\newsavebox{\upperbox}
\newsavebox{\lowerbox}
\newsavebox{\tempbox}
\newlength{\photodepth}
\newlength{\boxesdepth}
\newlength{\photowidth}

\newenvironment{boxesandphoto}[2][]
 {\vfuzz=2pt
  \par\addvspace{\topsep}
  \sbox{\photobox}{\includegraphics[#1,valign=t]{#2}}%
  \setlength{\photowidth}{\wd\photobox}%
  \setlength{\photodepth}{\dp\photobox}%
 }
 {%
  \maketextboxes\centering
  \ifdim\photodepth<\boxesdepth \photodepth=\boxesdepth \fi
  \addtolength\photodepth{\ht\photobox}%
  \addtolength\photodepth{\fboxrule+\fboxsep}
  \leavevmode
  \vtop to\photodepth{
    \vspace*{0pt}
    \unvbox\tempbox
  }\hfill
  \vtop to\photodepth{
    \vspace*{0pt}
    \box\photobox
    \vss
  }
  \par\addvspace{\dimexpr\topsep+\medskipamount}
 }

\newcommand{\maketextbox}[2]{%
  \sbox{\tempbox}{%
    \fbox{%
      \begin{minipage}[#1]{\textwidth-\photowidth-2\fboxsep-2\fboxrule-1em}
      \BODY\par
      \vspace{0pt}
      \end{minipage}%
    }%
  }
  \global\setbox#2=\box\tempbox
}

\NewEnviron{toptext}{\maketextbox{t}{\upperbox}}
\NewEnviron{bottomtext}{\maketextbox{b}{\lowerbox}}

\newcommand{\maketextboxes}{%
  \setbox\tempbox=\vtop{
    \box\upperbox
    \vspace{2ex plus 1fill}
    \box\lowerbox
    \kern\fboxrule\kern\fboxsep
  }%
  \setlength{\boxesdepth}{\dp\tempbox}%
  \addtolength{\boxesdepth}{-\fboxsep-\fboxrule}
}

\begin{document}

something above

\begin{boxesandphoto}[height=3cm,width=3cm]{example-image-b}
\begin{toptext}
some test text test text test text test text test text test text
test text test text test text test text test text test text test
text test text test text
\end{toptext}
\begin{bottomtext}
some other text test text test text test text test text test text
test text test text test text test text test text test text test text
test text test text test text test text test text test text test text
test text test text test text test text test text
\end{bottomtext}
\end{boxesandphoto}

something in the middle

\begin{boxesandphoto}[height=5cm,width=3cm]{example-image-b}
\begin{toptext}
some test text test text test text test text test text test text
test text test text test text test text test text test text test
text test text test text
\end{toptext}
\begin{bottomtext}
some other text test text test text test text test text test text
test text test text test text test text test text test text test text
test text test text test text test text test text test text test text
test text test text test text test text test text
\end{bottomtext}
\end{boxesandphoto}

something at the bottom

\end{document}

A: Here's a slight modification of cslstr's solution. Here I avoid the minipage environment in the \textboxes command. This works for me.
\documentclass{report}
\usepackage[demo]{graphicx} % Remove [demo] for final version
\usepackage[export]{adjustbox}
\usepackage{calc,etoolbox}
\usepackage{fullpage} % Increase margins for these specific widths

\begin{document}

\newcommand{\imagebox}{\includegraphics[width=5cm,height=10cm,valign=t]{1988.jpg}}

\newcommand{\textboxes}{
     \fbox{\parbox[t]{8cm}{
     Text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
     text1 text1 text1 text1 text1 text1 text1 text1 text1
    text1 text1 text1 text1 text1.}}
    \par\vspace{1ex}\vfill
    \fbox{\parbox[b]{8cm}{
    Text2 text2 text2 text2 text2 text2 text2 text2 text2
    text2 text2 text2 text2 text2 text2 text2 text2 text2
    text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
%   text2 text2 text2 text2 text2 text2 text2 text2 text2
    text2 text2 text2 text2 text2 text2 text2 text2 text2
    text2 text2 text2 text2 text2.}}
}

\newcommand{\textboxespaged}{
     \noindent\begin{minipage}[t]{\linewidth}
     \textboxes%
     \end{minipage}
}

% Calculate height of image and text boxes
\newlength{\imageboxheight}
\settototalheight{\imageboxheight}{\imagebox}
\newlength{\textboxesheight}
\settototalheight{\textboxesheight}{\textboxespaged}
\newlength{\maxTextBoxes}
\setlength{\maxTextBoxes}{\ifdimgreater{\textboxesheight}{\imageboxheight}{\textboxesheight}{\imageboxheight}}

% Typeset content
\noindent\begin{minipage}[t][\maxTextBoxes]{\textwidth}
    \noindent\begin{minipage}[t][\imageboxheight]{9cm}
    \textboxes\end{minipage}\begin{minipage}[t]{6cm}
    \imagebox
    \end{minipage}
\end{minipage}\vspace{\baselineskip} % A bit of extra space

% Following text starts after both image and text
Next paragraph starts here.

\end{document}


text:
Q: Pagination system in asp.net core 2.0 mvc I want to create for my project a common pagination component for all my pages which contains a listing.
I used to work with old-school webforms and i am not sure to work with best practice in asp.net mvc core.
I have read this documentation which is great from Microsoft: https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page#add-paging-functionality-to-the-students-index-page
I have put PaginatedList class in my project.
Everything works great.
But i want to put html stuff for pagination in a partial view (in order to factorize html code):
@model PaginatedList<T>

@{
    var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
    var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}

    Previous

    Next

Then, i want to put this line at the bottom of each listing page:
@Html.Partial("~/Views/Shared/_pagination.cshtml", Model)

I have 2 problems:

*

*On the first line of my partial view, i do not know which datatype i should put. It might be PaginatedList, PaginatedList, or anything else.
I do not know the good syntax to say "Model is PaginatedList where T can be any entity of my project". I tried to put object instead of T, but it does not work.

*As you can see, the prev/next links contains other parameters (param1). This parameters can be filters. But this filters are not the same. Is there a way to say to the  tag: "Copy each GET parameter you can see with its current value" ?
Thanks

A: Sort of an old question but... I use this to render the partial at the top and bottom:
 @await Html.PartialAsync("_pagination.cshtml")

Then just use the same model as the main page in your _pagination.cshtml page:
 @model youproject.Pages.yourpageModel;

....
@{
    var prevDisabled = !Model.PaginatedInventory.HasPreviousPage ? "disabled" : "";
    var nextDisabled = !Model.PaginatedInventory.HasNextPage ? "disabled" : "";
    var SortOrderDir = Model.CurrentSortDir;
    var numberOfPages = Model.PaginatedInventory.TotalPages;
    var CurrentPageIndex = Model.PaginatedInventory.PageIndex;

    int CurrentLimit = Model.IntegerCurrentLimit;
    int start = ((CurrentPageIndex - 7) > 0) ? CurrentPageIndex - 7 : 0;
    int end = ((CurrentPageIndex + 7) < numberOfPages) ? CurrentPageIndex + 7 : numberOfPages;

}

etc... the pagemodel (yourpagemodel.cs file) creates "PaginatedInventory":
public PaginatedList<InventoryItem> PaginatedInventory { get; set; }

...
  PaginatedInventory = await PaginatedList<InventoryItem>.CreateAsync(
                Items,CurrentPageIndex, IntegerCurrentLimit);

The type is already defined in the model.


text:
Q: When trying to logout/unwind back to the home screen, why would you get a found nil error if there isn't even an optional? Line where error is:
self.passwordField.delegate = self

Code from the button:
 @IBAction func unwindToRed(_ sender: Any) {

    do {
                   try Auth.auth().signOut()
                   let ViewController1 = ViewController()
                   let ViewNavigationController = UINavigationController(rootViewController: ViewController1)
                   self.present(ViewNavigationController, animated: true, completion: nil)
               } catch let err {
                   print(err)
               }

}

This is the relevant homepage code:
class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var emailField: UITextField!

@IBOutlet weak var passwordField: UITextField!

var userUID: String!
var databaseRef: DatabaseReference!

override func viewDidLoad() {

    super.viewDidLoad()

    databaseRef = Database.database().reference()

    self.passwordField.delegate = self
    self.emailField.delegate = self

    emailField.attributedPlaceholder = NSAttributedString(string: "Email",
    attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])

    passwordField.attributedPlaceholder = NSAttributedString(string: "Password",
    attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])

}
 override func viewDidAppear(_ animated: Bool) {
    if let _ = KeychainWrapper.standard.string(forKey: "uid") {
        self.performSegue(withIdentifier: "tohome", sender: nil)
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
     @IBAction func signInPressed(_ sender: Any) {

   Auth.auth().createUser(withEmail: (emailField.text ?? ""), password: (passwordField.text ?? ""))  { (user, error) in
       if let _eror = error {
           //something bad happning
           print(_eror.localizedDescription )
        let alert = UIAlertController(title: "Error", message: "Invalid Entry or Duplicate.", preferredStyle: UIAlertController.Style.alert)
                             let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
                             alert.addAction(action)
                             self.present(alert, animated: true, completion: nil)

       }else{
           //user registered successfully
           print(user as Any)
                 if let userID = user?.uid {
                                           KeychainWrapper.standard.set((userID), forKey: "uid")

                                           let databaseRef = Database.database().reference()

databaseRef.child("people").child(userID).child("users").setValue(self.emailField.text!)

databaseRef.child("people").child(userID).child("postID").setValue(userID)

                                           self.performSegue(withIdentifier: "tohome", sender: nil)
                                       }

       }
    }
}

 @IBAction func loginInPressed(_ sender: Any) {
 Auth.auth().signIn(withEmail: (emailField.text ?? ""), password: (passwordField.text ?? ""))  { (user, error) in
 if let _eror = error {
               //something bad happning
               print(_eror.localizedDescription )
            let alert = UIAlertController(title: "Error", message: "Incorrect Email or Password.", preferredStyle: UIAlertController.Style.alert)
                                 let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
                                 alert.addAction(action)
                                 self.present(alert, animated: true, completion: nil)

           }else{
               //user registered successfully
               print(user as Any)
                    if let userID = user?.uid {
                        KeychainWrapper.standard.set((userID), forKey: "uid")
                        self.performSegue(withIdentifier: "tohome", sender: nil) }

           }
        }
}

A: Problem is hiding in this line:
@IBAction func unwindToRed(_ sender: Any) {
    do {
          try Auth.auth().signOut()
          let ViewController1 = ViewController() // <-- This is the problem
          let ViewNavigationController = UINavigationController(rootViewController: ViewController1)
          self.present(ViewNavigationController, animated: true, completion: nil)
     } catch let err {
          print(err)
     }

}

Because you are using storyboards to create your views, you should instantiate your view controller from storyboard. To do this right please refer to Creating View Controllers from Storyboard.
If you're new to iOS development or you don't know why this is required please refer to this post which will explain instantiating view controller from storyboard vs. creating new instance.


text:
Q: What does "pypi" in the "Channel" column of `conda list` output imply? $ conda list -v torch-glow
# packages in environment at /anaconda3/envs/pytorch:
#
# Name                    Version                   Build  Channel
torch-glow                0.0.0                    pypi_0    pypi

Does it mean that I pip install'd the torch-glow package?

A: It means you used pip install as described in the docs:
https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-pkgs.html#installing-non-conda-packages

The command conda list shows packages installed this way, with a label showing that they were installed with pip.

Please note that:

Issues may arise when using pip and conda together. When combining conda and pip, it is best to use an isolated conda environment. Only after conda has been used to install as many packages as possible should pip be used to install any remaining software. If modifications are needed to the environment, it is best to create a new environment rather than running conda after pip. When appropriate, conda and pip requirements should be stored in text files.

https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#pip-in-env


text:
Q: Send HTML form attachment in email I know there are many questions/answers to this on here as well as all over Google, and I've looked through many but can't seem to find a solution that works for me, tried all but failed. Feel free to rate negative if you think I haven't searched hard enough.
I'm new to PHP, and this is the first time I've needed to use file attachments so it's foreign to me.
Can someone help?
Here is the PHP:
<?php
if ($_POST["application-submit"]) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $age = $_POST['age'];
    $height = $_POST['height'];
    $weight = $_POST['weight'];
    $picture = $_POST['picture'];
    $to = 'models@swoleinc.com';
    $subject = 'Swole Inc Application';

    $ip = getenv('HTTP_CLIENT_IP')?:
    getenv('HTTP_X_FORWARDED_FOR')?:
    getenv('HTTP_X_FORWARDED')?:
    getenv('HTTP_FORWARDED_FOR')?:
    getenv('HTTP_FORWARDED')?:
    getenv('REMOTE_ADDR');

    $body ="Name: $name\n\n
    E-Mail: $email\n\n
    Age: $age\n\n
    Height: $height\n\n
    Weight: $weight\n\n
    Picture: $picture\n\n
    IP Address: $ip";

    if (!$_POST['name']) {
        $errName = '^ You forgot your name!';
    }

    if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errEmail = '^ We need a valid email.';
    }

    if (!$_POST['age']) {
        $errAge = '^ How old are you?';
    }

    if (!$_POST['height']) {
        $errHeight = '^ Tell us how tall you are.';
    }

    if (!$_POST['weight']) {
        $errWeight = '^ We promise we won\'t laugh!';
    }

    if (!$_POST['picture']) {
        $errPicture = '^ Show us your physique!';
    }

    if (!$errName && !$errAge && !$errHeight && !$errWeight && !$errEmail && !$errPicture) {
        if (mail ($to, $subject, $body)) {
            $result='
Thanks for applying! If you fit our current needs, we\'ll be in touch soon!
';
        } else {
            $result='
Sorry, something\'s broken. If the problem persists, email models@swoleinc.com instead.
';
        }
    }
}
?>

Here is the HTML:
<?php include('apply.php'); ?>
              <form action="#apply" method="post" id="apply" enctype="multipart/form-data">

                    All fields are required.

                  <input type="text" name="name" id="name" value="<?php echo htmlspecialchars($_POST['name']); ?>">

                  <?php echo "
$errName
";?>
                  Name

                  <input type="text" name="email" id="email" value="<?php echo htmlspecialchars($_POST['email']); ?>">

                  <?php echo "
$errEmail
";?>
                  Email

                  <input type="text" class="extra" name="age" id="age" value="<?php echo htmlspecialchars($_POST['age']); ?>">

                  <?php echo "
$errAge
";?>
                  Age

                  <input type="text" class="extra" name="height" id="height" value="<?php echo htmlspecialchars($_POST['height']); ?>">

                  <?php echo "
$errHeight
";?>
                  Height

                  <input type="text" class="extra" name="weight" id="weight" value="<?php echo htmlspecialchars($_POST['weight']); ?>">

                  <?php echo "
$errWeight
";?>
                  Weight

                    <input type="file" name="picture" allow="images/*" style="border-bottom: 0; padding: 0" value="<?php echo htmlspecialchars($_POST['picture']); ?>">
                    <?php echo "
$errPicture
";?>

                    <?php echo $result; ?>

                    <input id="application-submit" type="submit" name="application-submit" class="btn-apply text-center" value="I have what it takes!" style="display: block; padding: 20px 30px">

              </form>

Feel free to view the live version: Swole Inc
As you will see, the image won't send right now which obviously won't let the form submit because it'll give the error message.
EDIT:
This was one of the variations I tried:
<?php
if ($_POST["application-submit"]) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $age = $_POST['age'];
    $height = $_POST['height'];
    $weight = $_POST['weight'];
    $picture = $_POST['picture'];
    $to = 'models@swoleinc.com';
    $subject = 'Swole Inc Application';

    $file = $path . "/" . $filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));

    $separator = md5(time());

    $eol = PHP_EOL;

    $headers = "From: name <models@swoleinc.com>" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol . $eol;

    $headers .= "--" . $separator . $eol;
    $headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
    $headers .= $message . $eol . $eol;

    $headers .= "--" . $separator . $eol;
    $headers .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: base64" . $eol;
    $headers .= "Content-Disposition: attachment" . $eol . $eol;
    $headers .= $content . $eol . $eol;
    $headers .= "--" . $separator . "--";

    $ip = getenv('HTTP_CLIENT_IP')?:
    getenv('HTTP_X_FORWARDED_FOR')?:
    getenv('HTTP_X_FORWARDED')?:
    getenv('HTTP_FORWARDED_FOR')?:
    getenv('HTTP_FORWARDED')?:
    getenv('REMOTE_ADDR');

    $body ="Name: $name\n\n
    E-Mail: $email\n\n
    Age: $age\n\n
    Height: $height\n\n
    Weight: $weight\n\n
    Picture: $picture\n\n
    IP Address: $ip";

    if (!$_POST['name']) {
        $errName = '^ You forgot your name!';
    }

    if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errEmail = '^ We need a valid email.';
    }

    if (!$_POST['age']) {
        $errAge = '^ How old are you?';
    }

    if (!$_POST['height']) {
        $errHeight = '^ Tell us how tall you are.';
    }

    if (!$_POST['weight']) {
        $errWeight = '^ We promise we won\'t laugh!';
    }

    if (!$_POST['picture']) {
        $errPicture = '^ Show us your physique!';
    }

    if (!$errName && !$errAge && !$errHeight && !$errWeight && !$errEmail && !$errPicture) {
        if (mail ($to, $subject, $body, $headers)) {
            $result='
Thanks for applying! If you fit our current needs, we\'ll be in touch soon!
';
        } else {
            $result='
Sorry, something\'s broken. If the problem persists, email models@swoleinc.com instead.
';
        }
    }
}
?>


text:
Q: How does the C++ compiler know which implementation of a virtual function to call? Here is an example of polymorphism from http://www.cplusplus.com/doc/tutorial/polymorphism.html (edited for readability):
// abstract base class
#include <iostream>
using namespace std;

class Polygon {
    protected:
        int width;
        int height;
    public:
        void set_values(int a, int b) { width = a; height = b; }
        virtual int area(void) =0;
};

class Rectangle: public Polygon {
    public:
        int area(void) { return width * height; }
};

class Triangle: public Polygon {
    public:
        int area(void) { return width * height / 2; }
};

int main () {
    Rectangle rect;
    Triangle trgl;
    Polygon * ppoly1 = ▭
    Polygon * ppoly2 = &trgl;
    ppoly1->set_values (4,5);
    ppoly2->set_values (4,5);
    cout << ppoly1->area() << endl; // outputs 20
    cout << ppoly2->area() << endl; // outputs 10
    return 0;
}

My question is how does the compiler know that ppoly1 is a Rectangle and that ppoly2 is a Triangle, so that it can call the correct area() function? It could find that out by looking at the "Polygon * ppoly1 = ▭" line and knowing that rect is a Rectangle, but that wouldn't work in all cases, would it? What if you did something like this?
cout << ((Polygon *)0x12345678)->area() << endl;

Assuming that you're allowed to access that random area of memory.
I would test this out but I can't on the computer I'm on at the moment.
(I hope I'm not missing something obvious...)

A: Chris Jester-Young gives the basic answer to this question.
Wikipedia has a more in depth treatment.
If you want to know the full details for how this type of thing works (and for all type of inheritance, including multiple and virtual inheritance), one of the best resources is Stan Lippman's "Inside the C++ Object Model".

A: Disregarding aspects of binding, it's not actually the compiler that determines this.
It is the C++ runtime that evaluates, via vtables and vpointers, what the derived object actually is at runtime.
I highly recommend Scott Meyer's book Effective C++ for good descriptions on how this is done.
Even covers how default parameters in a method in a derived class are ignored and any default parameters in a base class are still taken! That's binding.

A: Each object (that belongs to a class with at least one virtual function) has a pointer, called a vptr. It points to the vtbl of its actual class (which each class with virtual functions has at least one of; possibly more than one for some multiple-inheritance scenarios).
The vtbl contains a bunch of pointers, one for each virtual function. So at runtime, the code just uses the object's vptr to locate the vtbl, and from there the address of the actual overridden function.
In your specific case, Polygon, Rectangle, and Triangle each has a vtbl, each with one entry pointing to its relevant area method. Your ppoly1 will have a vptr pointing to Rectangle's vtbl, and ppoly2 similarly with Triangle's vtbl. Hope this helps!

A: To answer the second part of your question: that address probably won't have a v-table in the right place, and madness will ensue.  Also, it's undefined according to the standard.

A: cout << ((Polygon *)0x12345678)->area() << endl;

This code is a disaster waiting to happen. The compiler will compile it all right but when it comes to run time, you will not be pointing to a valid v-table and if you are lucky the program will just crash.
In C++, you shouldn't use old C-style casts like this, you should use dynamic_cast like so:
Polygon *obj = dynamic_cast<Polygon *>(0x12345678)->area();
ASSERT(obj != NULL);

cout << obj->area() << endl;

dynamic_cast will return NULL if the given pointer is not a valid Polygon object so it will be trapped by the ASSERT.

A: Virtual function tables.  To wit, both of your Polygon-derived objects have a virtual function table that contains function pointers to the implementations of all their (non-static) functions; and when you instantiate a Triangle, the virtual function pointer for the area() function points to the Triangle::area() function; when you instantiate a Rectangle, the area() function points to the Rectangle::area() function.  Because virtual function pointers are stored along with the data for an object in memory, every time you reference that object as a Polygon, the appropriate area() for that object will be used.


text:
Q: Can't browse Core Data table I am trying to learn core data. after following few online tutorials I have created a sample iPhone app. the app is working fine. i can save data and search in the database.
The problem I am having is I can't browse the database in my mac. I am using 'SQLite Database Browser'. in the app folder there are three SQLite files (with extension .sqlite, .sqlite-shm and .sqlite-wal)
I can open the .sqlite file, but I don't see any table in the file. (I think the table is still in the temporary files. or is it?)
couldn't post the screenshot of the database folder, as i don't have enough reputation :-(
Here is the code I am using to save data:
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];

NSManagedObject *newPerson = [[NSManagedObject alloc]initWithEntity:entitydesc insertIntoManagedObjectContext:context];

[context hasChanges];

[newPerson setValue: self.firstName.text forKey:@"firstname"];
[newPerson setValue: self.lastName.text forKey:@"lastname"];

NSError *error;
[context hasChanges];
[context save:&error];

_displayLabel.text = [NSString stringWithFormat:@"person added"];

I have developed app with SQLite database before and I didn't have any issue browsing database.
Before I start implementing core data to my app, I wanted to know if this problem is going to cause me headeche down the track. or is it something i can ignore.

A: Your SQLite file is using WAL mode as Martin mentioned.  You can vacuum the database to see the data or just let it perform as it is working as intended.
Further discussion on this topic can be found at CoreData database not showing in sqlite since moving to Xcode 5


text:
Q: About the definition of functional derivative and the $L^2$ inner product There is something I do not understand well about the definition of the functional derivative. In the wikipedia page http://en.wikipedia.org/wiki/Functional_derivative it says:

1) This definition readily accepts that the functional derivative can be written using the inner product for $L^2$ Hilbert space. But according to the Riesz representation theorem, this should be valid only for a bounded linear functional on the $L^2$ Hilbert space. So as long as $[\dfrac{d}{d\epsilon} F[\rho + \epsilon \phi]]_{\epsilon=0}$ is a bounded linear functional for $\phi \in L^2$, then this definition is true. Is this correct?
2)The inner product definition is used with the dirac delta function in the same Wikipedia page like that:

But according to another resources the evaluation functional $F[\rho] = \rho (r)$ is linear but not bounded in $L^2$ and such the Riesz representation theory should not work in this case. But we can derive $[\dfrac{d}{d\epsilon} F[\rho + \epsilon \phi]]_{\epsilon=0}=\int \delta (r-r') \phi(r')dr'$ where we have obtained an inner product form from which we can read $\delta(r-r')$ as the functional derivative. So the representation theorem seems to "work". How is this justified, am I missing something?

A: The definition you mentioned of the functional derivative is valid, whenever $[\frac{\mathbb{d}}{\mathbb{d}\epsilon}F[\rho+\epsilon\phi]]_{\epsilon=0}$ is linear in $\rho$ and can be represented as an integral with some function, which is not necessarily in $L^2$. Hence this linear functional may not be bounded as a functional $L^2 \rightarrow \mathbb{R}$. I remind you that the inner product on $L^2$ is defined only for function in $L^2$ and not for general functions, so in the case where $\frac{\delta F}{\delta \rho}\notin L^2$ you can not use the notion of inner product when referring to the functional derivative.
As for the second part of your post, when we allow the functional derivative to be the delta function, we actually extend this definition since the delta function is not really a function, but rather a linear functional on functions. In this case $[\frac{\mathbb{d}}{\mathbb{d}\epsilon}F[\rho+\epsilon\phi]]_{\epsilon=0}$ is some linear functional that can not be represented as an integration with a function. Hence it is not a bounded linear functional $L^2 \rightarrow \mathbb{R}$, but it is still well-defined using the extended definition.


text:
Q: CUDA no operator += for volatile cuda::std::complex I have a kernel that uses cuda::std::complex<float>, and in this kernel I want to do warp reduction, following this post.
The warpReduce function:
template <typename T, unsigned int blockSize>
__device__ void warpReduce(volatile T *sdata, unsigned int tid) {
    if (blockSize >= 64) sdata[tid] += sdata[tid + 32];
    if (blockSize >= 32) sdata[tid] += sdata[tid + 16];
    if (blockSize >= 16) sdata[tid] += sdata[tid + 8];
    if (blockSize >= 8) sdata[tid] += sdata[tid + 4];
    if (blockSize >= 4) sdata[tid] += sdata[tid + 2];
    if (blockSize >= 2) sdata[tid] += sdata[tid + 1];
}

I'm getting the error:  error : no operator "+=" matches these operands, operand types are: volatile cuda::std::complex<float> += volatile cuda::std::complex<float>.
Simply removing the volatile as mentioned in this post doesnt work.
Is there any way I can still use a complex type (thrust/cuda::std) in warp reduction?
kernel
template <unsigned int blockSize>
__global__ void reduce6(cuda::std::complex<float>*g_idata, cuda::std::complex<float>*g_odata, unsigned int n) {
    extern __shared__ int sdata[];
    unsigned int tid = threadIdx.x;
    unsigned int i = blockIdx.x*(blockSize*2) + tid;
    unsigned int gridSize = blockSize*2*gridDim.x;
    sdata[tid] = 0;
    while (i < n) { sdata[tid] += g_idata[i] + g_idata[i+blockSize]; i += gridSize; }
    __syncthreads();
    if (blockSize >= 512) { if (tid < 256) { sdata[tid] += sdata[tid + 256]; } __syncthreads(); }
    if (blockSize >= 256) { if (tid < 128) { sdata[tid] += sdata[tid + 128]; } __syncthreads(); }
    if (blockSize >= 128) { if (tid < 64) { sdata[tid] += sdata[tid + 64]; } __syncthreads(); }
    if (tid < 32) warpReduce<cuda::std::complex<float>, blockSize>(sdata, tid);
    if (tid == 0) g_odata[blockIdx.x] = sdata[0];
}

I found a workaround by doing a reinterpret cast to float2/double2 first. But I dont know if this has any other implications. I read about undefined behaviour. Other suggestions?
This works:
template <typename T>
struct myComplex;

template <>
struct myComplex<float>
{
    typedef float2 type;
};

template <>
struct myComplex<double>
{
    typedef double2 type;
};

template <typename T>
__device__ void warpReduce(volatile T *SharedData, int tid)
{
    SharedData[tid].x += SharedData[tid + 32].x;
    SharedData[tid].x += SharedData[tid + 16].x;
    SharedData[tid].x += SharedData[tid + 8].x;
    SharedData[tid].x += SharedData[tid + 4].x;
    SharedData[tid].x += SharedData[tid + 2].x;
    SharedData[tid].x += SharedData[tid + 1].x;

    SharedData[tid].y += SharedData[tid + 32].y;
    SharedData[tid].y += SharedData[tid + 16].y;
    SharedData[tid].y += SharedData[tid + 8].y;
    SharedData[tid].y += SharedData[tid + 4].y;
    SharedData[tid].y += SharedData[tid + 2].y;
    SharedData[tid].y += SharedData[tid + 1].y;
}

// and then in the kernel:
warpReduce(reinterpret_cast<typename myComplex<T>::type *>(data), tid);

A: According to my testing, in CUDA 11.7, the issue revolves around the use of volatile.
According to this blog, this style of programming (implicit warp-synchronous) is deprecated.
additionally, this part of your posted code could not possibly be correct:
extern __shared__ int sdata[];

Combining these ideas, we can do the following:
$ cat t7.cu
#include <cuda/std/complex>
#include <iostream>
// assumes blocksize is 64 or larger power of 2 up to max of 512 (or 1024 see below)
template <typename T>
__device__ void warpReduce(T *sdata, unsigned int tid) {

  T v = sdata[tid];
  v += sdata[tid+32];
  sdata[tid] = v;     __syncwarp();
  v += sdata[tid+16]; __syncwarp();
  sdata[tid] = v;     __syncwarp();
  v += sdata[tid+8];  __syncwarp();
  sdata[tid] = v;     __syncwarp();
  v += sdata[tid+4];  __syncwarp();
  sdata[tid] = v;     __syncwarp();
  v += sdata[tid+2];  __syncwarp();
  sdata[tid] = v;     __syncwarp();
  v += sdata[tid+1];  __syncwarp();
  sdata[tid] = v;
}

template <unsigned int blockSize, typename T>
__global__ void reduce6(T *g_idata, T *g_odata, size_t n) {
    extern __shared__ T sdata[];
    unsigned int tid = threadIdx.x;
    size_t i = blockIdx.x*(blockSize*2) + tid;
    size_t gridSize = blockSize*2*gridDim.x;
    sdata[tid] = 0;
    while (i < n) { sdata[tid] += g_idata[i] + g_idata[i+blockSize]; i += gridSize; }
    __syncthreads();
//  if (blockSize == 1024) { if (tid < 512) { sdata[tid] += sdata[tid + 512]; } __syncthreads(); }  // uncomment to support blocksize of 1024
    if (blockSize >= 512)  { if (tid < 256) { sdata[tid] += sdata[tid + 256]; } __syncthreads(); }
    if (blockSize >= 256)  { if (tid < 128) { sdata[tid] += sdata[tid + 128]; } __syncthreads(); }
    if (blockSize >= 128)  { if (tid < 64)  { sdata[tid] += sdata[tid + 64];  } __syncthreads(); }
    if (tid < 32) warpReduce(sdata, tid);
    if (tid == 0) g_odata[blockIdx.x] = sdata[0];
}

using my_t = cuda::std::complex<float>;
int main(){
  size_t n = 2048;
  const unsigned blk = 128;
  unsigned grid = n/blk/2;
  my_t *i, *h_i;
  my_t *o, *h_o;
  h_i = new my_t[n];
  h_o = new my_t[grid];
  for (size_t i = 0; i < n; i++) h_i[i] = {1,1};
  cudaMalloc(&i, n*sizeof(my_t));
  cudaMalloc(&o, grid*sizeof(my_t));
  cudaMemcpy(i, h_i, n*sizeof(my_t), cudaMemcpyHostToDevice);
  reduce6<blk><<<grid,blk, blk*sizeof(my_t)>>>(i, o, n);
  cudaMemcpy(h_o, o, grid*sizeof(my_t), cudaMemcpyDeviceToHost);
  for (int i = 0; i < grid; i++)
    std::cout << cuda::std::real(h_o[i]) << "," <<  cuda::std::imag(h_o[i]) <<  std::endl;
  cudaDeviceSynchronize();
}
$ nvcc -o t7 t7.cu
$ compute-sanitizer ./t7
========= COMPUTE-SANITIZER
256,256
256,256
256,256
256,256
256,256
256,256
256,256
256,256
========= ERROR SUMMARY: 0 errors
$