text:
Q: A buffer overrun has occurred in c++ This program will get a string (char Array) of a math expression from the user and parse it then save each part(numbers and operators separately) in an element of an array called exp.I debugged this program before in c# and it worked quite properly but from now as I am studying C++ in college I have to program in this language so when I debug this program in visual studio I get an error that says:
"A buffer overrun has occurred in LineCalculator.exe which has corrupted the program's internal state. Press Break to debug the program or Continue to terminate the program."
please help, what should I do?
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <math.h>
using namespace std;

struct str{
    char text[10];
};
void input();
void CurrentObs(char source[],char current , int i,str exp[],int c,int ExpNum);
void ExpAssign(int i ,int c , int ExpNum,char current ,char source[],str exp[]);
int _tmain(int argc, _TCHAR* argv[])
{
    input();
    return 0;
}
void input()*//for getting the string from the user*
{
    char source[50];
    gets(source);
    struct str exp[20];
    int i=-1;
    int c=0;
    int ExpNum=-1;
    do{
        i++;
        char current=source[i];
        CurrentObs(source,current,i,exp,c,ExpNum);
    }while(i<50);
    //the next loop will print the parsed expressions in separate lines
    for(int b=0;b<20;b++)
        cout<<exp[b].text<<endl;
}
//the next function is to check if the current character is one of the signs mentioned in the signs array or not
void CurrentObs(char source[],char current , int i,str exp[],int c,int ExpNum)
{
    struct str signs[7]={"+","-","/","*","=","(",")"};
    for (int x=0;x<7;x++)
        if (current==*signs[i].text)
        {
            ExpNum++;
            ExpAssign(i,c,ExpNum,current,source,exp);
            break;
        }
}
void ExpAssign(int i ,int c , int ExpNum,char current ,char source[],str exp[])
{
    char parsed[10];
    for (int j = c; j < i; j++)
        parsed[j-c]=source[j];
    strcpy(exp[ExpNum].text,parsed);
    c=i+1;


text:
Q: Extracting lines from zone file I have a DNS zone file that looks like the following:
record A 1.1.1.1
       A 1.1.1.2
       A 1.1.1.3
other_record A 1.1.1.4
             A 1.1.1.5
another_rec  A 1.1.1.6

I need to extract all lines that belong to record (so the first one and the two below it) without any of the other lines (the actual file has many more records like this so greping the first line and the 2 other below is not a valid solution).
Expected result:
record A 1.1.1.1
       A 1.1.1.2
       A 1.1.1.3

A: awk '/^[^[:space:]]/{f = ($1=="record" ? 1 : 0)} f' file

A: This might work for you (GNU sed):
sed '/^record/{:a;n;/^\S/Q;ba};d' file

This terminates following the first occurrence of record,
or:
sed '/^\S/h;G;/^record/MP;d' file

This prints all occurrences of record.

A: You could also think about using a dns zone file parsers available in various languages like python etc.
Once you have a handle on zone file content as an object then its pretty easy to manipulate it the way you want.
I got this one after doing quick web search - https://github.com/blockstack/zone-file-py . (there are bunch of others... you need to see which one works for you best)

A: Could you please try following and let me know if this helps.
awk '/^[a-z]+/ && !/^record/{flag=""} /^record/{flag=1} flag'  Input_file

A: awk '!/_/&&NR!=5' file

record A 1.1.1.1
       A 1.1.1.2
       A 1.1.1.3

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I set the environment based on route? I want to have a different environment if I'm browsing a specific path (domain.com/path1), is this possible in Laravel 4 and if so, how? I know of the $app->detectEnvironment() method but I don't know how to use it for this.

A: This is possible with the $app->detectEnvironment() method (in /bootstrap/start.php), but instead of sending on an array you use a closure.
$env = $app->detectEnvironment(function(){
    // get current http_host
    $baseurl = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;

    // our available environment
    $envs = [
        'foo' => ['foo.com', 'bar.foo.com'],
        'kex' => ['kex.foo.com']
    ];

    // default environment, you should not change this
    $environment = 'production';

    // search trough each available environment to see if it matched our http_host
    foreach($envs as $key => $env) {
        foreach ($env as $url) {
            if ($url == $baseurl) {
                $environment = $key;

                // match found, lets break our loop
                break 2;
            }
        }
    }

    // we create segments of /our/path so we can check if it matches your condition
    $segments = explode('/', isset($_SERVER['REQUEST_URI']) ? trim($_SERVER['REQUEST_URI']) : null);

    // check if the first (second) segment matches our /path
    if (isset($segments[1]) && $segments[1] == 'path')
        return $environment . '-route'; // append -route to our environment and return it

    return $environment;
});

Line 2 to 24 mimics Laravel's default method (using arrays). What you're after below that.


text:
Q: Beamer: code fragment with listings I am having difficulty adding code fragment to my slides in beamer with listings package.
My code:
\documentclass{beamer}
%\usepackage[utf8]{inputenc}
\usetheme{Warsaw}
\usepackage{listings}

\title{My slies}
\author{Me }
\date{October 2020}

%slide number
\expandafter\def\expandafter\insertshorttitle\expandafter{%
  \insertshorttitle\hfill%
  \insertframenumber\,/\,\inserttotalframenumber}

\begin{document}

\begin{frame}{Slide 1}

 \begin{lstlisting}[basicstyle=\footnotesize]
def LosScore(y_pred, y_test):
  mse = []
  for i in range(len(y_test)):
     mse.append(np.mean(np.square((y_test[i]-y_pred[i]))))
return mse
\end{lstlisting}

\end{frame}

\end{document}

Error:
Runaway argument?

! Paragraph ended before \lst@next was complete.
<to be read again>
                   \par
l.27 \end{frame}

I suspect you've forgotten a `}', causing me to apply this
control sequence to too much text. How can we recover?
My plan is to forget the whole thing and hope for the best.


text:
Q: How to configure http_basic firewall in Symfony 4 to return JSON in response body on authentication failure? By default, when you configure a http_basic firewall in Symfony, the firewall will return "401 Unauthorized" and an empty body for requests with invalid credentials.
I'd like to have it return a custom JSON (eg: {'errorCode' => 'AUTHORIZATION_FAILURE', 'errorMessage' => 'The provided credentials are not valid'}). Is this possible?
My onAuthenticationFailure method does not return my custom response. It returns the default response.
My AuthenticationListener class that will subscribe to these events:
<?php
namespace App\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

class AuthenticationListener
{
    public function onAuthenticationFailure(AuthenticationFailureEvent $event)
    {
        //executes on failed login
        $content = array('errorCode' => 'AUTHORIZATION_FAILURE', 'errorMessage' => 'The provided credentials are not valid');
        // dd(json_encode($content));

        //the bellow code is not working
        $response = new Response();
        $response->headers->set('Content-Type', 'application/json');
        $response->setContent(json_encode($content))
                ->setStatusCode(200);

        return $response;
    }
}
?>

my security YAML
firewalls:
        api:
            pattern: ^/1
            anonymous: false
            provider: in_api
            http_basic: ~

my service YAML
# authentication failure event listener
    acme.security.authentication_failure_event_listener:
        class: App\EventListener\AuthenticationListener
        arguments: [ api ]
        tags:
            - { name: kernel.event_listener, priority: 100, event: security.authentication.failure, method: onAuthenticationFailure }

A: When I use header('Content-Type: application/json');echo json_encode($content);exit; it returns the expected result.


text:
Q: How to add a listener to every incoming message in 'botframwork-webchat' I'm using Microsoft chatbot in my react js project, with botframework-webchat. I wanna add a listener to every incoming message.
The requirement is to identify a certain message (Last message) and the content of it. Base on the content, user should be redirected to a result screen. If I can access the result, I can do the navigation. I searched for solutions, but couldn't find any.
Here is my code
const Chatbot = (props) => {
  const directLine = useMemo(
    () => createDirectLine({ token: process.env.REACT_APP_DIRECT_LINE_SECRET, locale: 'sv-se' }),
    []
  );

  const styleOptions = {
    bubbleBackground: 'white',
    bubbleBorder: '#26acab',
    bubbleFromUserBackground: 'white',
    bubbleFromUserBorder: '#26acab',
    botAvatarImage: './Icon.ico',
    botAvatarBackgroundColor: 'transparent',
    userAvatarBackgroundColor: '#26acab',
    userAvatarInitials: bubbleInitials,
    rootHeight: '50%',
    rootWidth: '100%',
    hideUploadButton: true,
    primaryFont: "'Avenir LT Std', sans-serif",
    hideSendBox: true,
  };

  useEffect(() => {
    var initiatingActivity = {
      from: {
        id: '001',
        name: 'noviral',
        token: msalToken,
        locale: language === 'en' ? 'en-US' : 'sv-se',
      },
      name: 'startConversation',
      type: 'event',
      value: 'Hi noviral!',
    };

    directLine.postActivity(initiatingActivity).subscribe(function (id) {
      if (console) {
        console.log('Chat bot initiated');
      }
    });

  }, []);

  return (
    <Layout className="login-layout">

            <ReactWebChat
              directLine={directLine}
              userID={'001'}
              username="Noviral"
              locale={language === 'en' ? 'en-US' : 'sv-se'}
              styleOptions={styleOptions}
            ></ReactWebChat>

    </Layout>
  );
};

export default withTranslation()(Chatbot);

Can anyone help me with this? Thanks in advance

A: You can pass a custom store to ReactWebChat which will get called whenever you receive message
import  {  createStoreWithDevTools } from 'botframework-webchat

const store =  createStoreWithDevTools( {},
    ({ dispatch }) => next => action => {
     if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
        console.log(action.payload); //this will have incoming message data
      }

      return next(action);
    });

<ReactWebChat directLine={directLine} store={store} userID="YOUR_USER_ID" />;


text:
Q: How to add an element to multi-dimensional JSON array if the element key is a variable There is a JSON file with an array like
{
    "general_array":[
        {"key_1":["a","b","c"]}
    ]
}

I want to add an element to the array e.g.
{"key_2":["d","e","f"]}

but the value of new key I get from a variable e.g.
var newKey = 'key_2';

I'm trying to add the element to the existed array as following
// ... getting file content
// var jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';

var jsonObj = JSON.parse(jsonFileContent);

var newKey = 'key_2';

jsonObj.general_array.push({newKey:['d','e','f']});

var newJsonFileContent = JSON.stringify(jsonObj);

// and rewrite the file ...
// console.log(newJsonFileContent);

But in the file I get
{
    "general_array":[
        {"key_1":["a","b","c"]},
        {"newKey":["d","e","f"]}
    ]
}

i.e. as the new element key I get the NAME of variable, but I need its VALUE
How to add the value?

UPDATED
The solution with [newKey] works in most of browsers, but it doesn't work in Internet Explorer 11
I need a solution to be working in IE11 too, so the question is still actual

A: You can use [newKey] to get the value of the variable as a key name:

var jsonFileContent = `
{
    "general_array":[
        {"key_1":["a","b","c"]}
    ]
}`;
var jsonObj = JSON.parse(jsonFileContent);

var newKey = 'key_2';

var tempObj = {};
tempObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(tempObj);

var newJsonFileContent = JSON.stringify(jsonObj);
console.log(newJsonFileContent);

A: To use the value of a variable as a JSON key, enclose it in square brackets, like so:
{[newKey]:['d','e','f']}

let jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';

let jsonObj = JSON.parse(jsonFileContent);

let newKey = 'key_2';

jsonObj.general_array.push({[newKey]:['d','e','f']});

let newJsonFileContent = JSON.stringify(jsonObj);

console.log(newJsonFileContent)

This is the computed property name syntax.  It's a shorthand/syntax sugaring for someObject[someKey] = somevalue

A: Try changing this line:
jsonObj.general_array.push({newKey:['d','e','f']});

For this:
var newObj = {};
newObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(newObj);


text:
Q: Is greatest element not the maximal element? My book says "The subset of $\mathcal{P}(\mathbf{N})$ consisting of all finite subsets of $\mathbf{N}$ has no maximal element".
Can someone explain this? Is it saying that there will not be a greatest element either? What about $\mathbf{N}$? Is $\phi$ the minimal element?


text:
Q: Can't insert data using sql server 2012 stored procedure and codeigniter Everytime i tried to insert data using a SQL server 2012 Stored Procedure in codeigniter it throws me the same error message:

A Database Error Occurred
Error Number: 07002/0
[Microsoft][ODBC Driver 11 for SQL Server]Campo COUNT erróneo o error
  de sintaxis
spa_insert_enterp ?,?,?,?,?
Filename:
  C:/Apache24/htdocs/sys_credenciales/system/database/DB_driver.php
Line Number: 691

That could be translated to: "sql server - COUNT field incorrect or syntax error"
Heres my CodeIgniter controller code:
public function agregar_empresa(){
    date_default_timezone_set('America/Santiago');
    $cur_date=date("Y-m-d H:i:s", time());
    $datetime_variable = new DateTime();
    $datetime_formatted = date_format($datetime_variable, 'Y-m-d H:i:s');
    $sp="spa_insert_enterp ?,?,?,?,?";
    $result=$this->db->query($sp,$_POST['nm_rs_empresa'],$_POST['nr_rut_empresa'],$_POST['nm_desc_empresa'],$_POST['nm_rubro'],$cur_date);
    //$query = $this->db->query(      "verificacion_fechas '".$codigo."',".$estado.",'".$llave_maestra."','".$fecha_actual."'");

}

Here is my Stored Procedure code:
ALTER  PROCEDURE [dbo].[spa_insert_enterp](
@nm_rs_empresa_in varchar(50),@nr_rut_empresa_in varchar(30),@nm_desc_empresa_in varchar(100),@nm_rubro_in varchar(20),@fc_empresa_in datetime
)
AS
BEGIN TRANSACTION
SET NOCOUNT ON;

insert into empresa
(nm_rs_empresa,nr_rut_empresa,nm_desc_empresa,nm_rubro,fc_empresa)
values
( @nm_rs_empresa_in,@nr_rut_empresa_in,@nm_desc_empresa_in,@nm_rubro_in ,@fc_empresa_in);

commit transaction;

I tried with the both date type variables in the code, but nothing happened.
Thank to you in advance.


text:
Q: PDF/A: How to spot the missing glyph? I am trying to have my rendered PDF validate as PDF/A. It fails with the error message that The glyph for character 0 in font ... is missing.
Visually inspecting the document, I find no obvious missing glyphs. How can I pinpoint the exact location in the document? A cursory glance at he log file did not help. (I am using LuaLaTeX, in case that's important.)


text:
Q: Cannot able to update chef run_list I have cookbook name sample and under recipes I have two recipes namely default.rb and execute.rb. When I give run_list as recipe[sample], it is working well. It is basically taking default.rb. How can I add both the recipes to run_list.
I tried recipe[sample::default],recipe[sample::execute], but it is not working.

A: You have to quote the run list parameter for the knife command:
knife run list set nodename "recipe[sample::default],recipe[sample::execute]"

Another possibility is to use knife node run list add:
knife run list add nodename "recipe[sample::execute]"


text:
Q: Prove that $TS$ is subbundle of $TM|_S$ for immersed submanifold I was doing Lee's smooth manifold exercise,in problem 10-14 needs to prove the following result:

Let $S\subset M$ be some smooth immersed submanifold,prove that $TS$
is subbundle of $TM|_S$.

It seems we need to use the local frame criterion,which needs to find a neigborhood such that exist k  smooth local section  $\sigma_1,...,\sigma_k :U\to TM|_S$
as  frame for $T_pS$ for each $p \in U$.
To prove this observe that $i:S^k\to M^n$ is smooth immersion,I have  idea how to prove it when $S$ is embedded submanifold,which can be shown as follows:
First for $p\in S$,there exist slice chart around it that is $(U\cap S,\pi\circ\varphi = (x^1,...,x^k))$ as chart for $S$,where $(U,\varphi =(x^1,...,x^n))$ is the corresponding chart for $M$.
We know chart $(U,\varphi =(x^1,...,x^n))$ provide a local trivialization for $TM$,we want to find the local section for $TM|_S$(needed for the local section criterion) which is obvious given by this trivialization.
Now construct the local section as follows:
$$\sigma_i : U\cup S \to (U\cap S) \times \Bbb{R}^n \to \pi^{-1}(U\cap S) \to TM|_S$$
Such that this map maps $p \mapsto (p,e_i) \mapsto \frac{\partial}{\partial x^i}|_p $
Our guess may be $\sigma_1,...,\sigma_k$ span the $TS$ but I can't make it clear.

A: I wrote this a while ago, and now I kind of having difficulty to follow my proof. But I'm sure I convinced by this proof at the time I wrote this. Let me know if something unclear.
Setup : Let $ \pi|_S : TM|_S \to S$ be the ambient tangent bundle, $\iota : S \hookrightarrow M$ is an immersed submanifold of dimension $k$ of a $n$-dimensional smooth manifold $M$.  For any $p \in S$, we have an $k$-dimensional subspace $d\iota_p (T_pS) \subseteq T_pM$. We want to show that $\bigcup_{p \in S} d\iota_p(T_pS) \subseteq TM|_S$ is a smooth subbundle of rank-$k$. To do this, it is enough to show that for any $p \in S$ there is a neighbourhood $V$ of $p$ and smooth local sections $\sigma_1,\dots,\sigma_k :V \to TM|_S$ such that at any $q \in V$, $\sigma_1(q),\dots,\sigma_k(q)$ form a basis for subspace $d\iota_q(T_qS)$.
Proof :  Since $S \subseteq M$ is an immersed submanifold, then $S$ locally embedded. So for any $p \in S$, there exists a neighbourhood $V \subseteq S$ of $p$ such that $V$ is embedded submanifold of $M$. By shrinking $V$ if necessary, we may assume that $V \subseteq S$ such that $\iota(V)=V \subseteq U$, so $V = V \cap U$ is a single slice in $U$, where $(U,\varphi)$ is a slice chart for $V$. That is
$$
\varphi(V) = \{(x^1,\dots,x^n) \in \varphi(U) : x^{m+1} = \cdots= x^n = 0   \} \subseteq \varphi(U).
$$
By Theorem 5.8, we have smooth (global) chart $(V,\psi)$ where the coordinate functions $\psi (V) = \{ (x^1,\dots,x^m)\} \subseteq \mathbb{R}^m$ are exactly the nonvanishing coordinates of image $\varphi(V)$ in $\varphi(U)$. Hence the representation of $\iota : S \hookrightarrow M$ in smooth charts $(V,\psi)$ and $(U,\varphi)$ is
\begin{equation}\tag{$\star$}
(x^1,\dots,x^m) \mapsto (x^1,\dots,x^m,0,\dots,0).
\end{equation}
Now for $i=1,\dots,m$, the coordinate vector fields $\tau_i : V \to TS$ defined as $\tau_i(q) = \frac{\partial}{\partial x^i}\big|_q$ are smooth local frame (since the component functions are constant, hence smooth) for $TS$ over $V$. Define local sections $\sigma_i : V \to TM|_S$ defined as $\sigma_i(q) = d\iota_q (\tau_i(q))$, for $i =1,\dots,m$, where $d\iota_q : T_qS \to T_qM$ is the differential of $\iota : S \hookrightarrow M$ at $q\in S$. From ($\star$), we can compute $\sigma_i$ as
$$
\sigma_i(q) = d\iota_q \circ \tau_i(q) = d\iota_q \Big(\frac{\partial}{\partial x^i}\bigg|_q \Big) = \frac{\partial}{\partial x^i}\bigg|_q,
$$
which is form a basis for $d\iota_q(T_qS) \subseteq T_qM$.
We have to show that these sections are smooth sections on $TM|_S$. Since $\sigma_i (V) \subseteq \bigcup_{q \in V} T_qM = (\pi|_S)^{-1}(V) = TM|_V$ and $TM|_V$ is open in $TM|_S$, then we only need to check the smoothness in $TM|_V$. For the local trivialization of $TM$ over slice chart $U$ as above is $\Phi : \pi^{-1}(U) \to U \times \mathbb{R}^n$, defined as
$$
\Phi \Big(v^i \frac{\partial}{\partial x^i}\Big|_p \Big) = (p,(v^1,\dots,v^n)).
$$
So the local trivialization for $TM|_V$ is just the restriction of $\Phi$ to $\pi^{-1}(U \cap V)$. Denote this as  $\Psi = \Phi|_U : \pi^{-1}(U \cap V) \to (U \cap V) \times \mathbb{R}^n$. Therefore
$$
\Psi \circ \sigma_i (q) =\Phi(\sigma_i(q)) =(q,e_i),
$$
which is obviously smooth. Hence $\sigma_i$ are the smooth local sections tha we seek. Since we can do this for every point $p \in S$, therefore $TS$ identified as its image $d\iota(TS) \subseteq TM|_S$ is a smooth subbundle.


text:
Q: How can drag music to my apple iPhone 4s I want to know how to drag and sync all my apple devices to linux because i already tried using Rythymbox,Banshee,Clementine,etc....

A: There are other apps you can use. Dropbox has a music player that will play music from dropbox, and there's a dropbox app for iPhone. There are other apps that will play from other cloud storage services that work with the iPhone. But Apple just doesn't seem to want to work with Linux - probably some conflict between their business model of charging for air and sunlight when they can and the Open Source community's dislike of proprietary formats and DRM.


text:
Q: Is there a closed form solution to $y \frac{dy}{dx} = \sqrt{x^2+y^2}+x$? I'm looking for a closed-form solution to the differential equation
$$y \frac{dy}{dx} = \sqrt{x^2+y^2}+x. $$
This arises in trying to plot the field lines from a uniformly magnetized conical shell.

A: Yes, take for example $y(x) = \sqrt{3}\, x$

A: $\frac{dy}{dx}=\frac{x}{y}+\sqrt{\left(\frac{x}{y}\right)^2+1}$
Let $y=tx$.
$\implies \frac{dy}{dx}=t+x\frac{dt}{dx}$
$\implies t+x\frac{dt}{dx}=\frac{1}{t} +\sqrt{\left(\frac{1}{t}\right)^2+1}$
$\implies \frac{dx}{x}=\frac{dt}{\sqrt{\left(\frac{1}{t}\right)^2+1} +\frac{1}{t}-t}$
Integrating on both sides,
$\ln(x)+c=\int \frac{tdt}{1-t^2+\sqrt{1+t^2}}$
Let $1+t^2=z^2\implies zdz=tdt$
$\implies \ln(|x|)+c=\int \frac{zdz}{1-(z^2-1)+z}$
$\implies \ln(|x|)+c=\int \frac{zdz}{2+z-z^2}=\frac{-1}{2}\left ( \int \frac{(2z-1)dz}{z^2-z-2}+\int \frac{dz}{z^2-z-2} \right)$
$\implies \ln(|x|)+c=\frac{-1}{2} \left( \ln(|z^2-z-2| )+\frac{1}{3}\ln\left(\frac{|2-z|}{|z+1|}\right)\right)$
$\implies c|x|=|z^2-z-2|^{\frac{-1}{2}}\left(\frac{|2-z|}{|1+z|}\right)^{\frac{-1}{6}}$
Where $z=\sqrt{1+\left(\frac{y}{x}\right)^2}$.


text:
Q: How can I solve problem with execute two stored procedures? I wanted to exec two stored procedures nested but I don't have much information about it. I created T-SQL code below, it doesn't work. Can you give me an idea? Thank you in advance.
DECLARE @currency_val decimal(18, 2);
DECLARE @first_price decimal(18, 2) = 80;
DECLARE @curr_unit nvarchar(50) = 'eur';

BEGIN
     exec sp_TLKARSILIK @first_price, @curr_unit @currency_val = @currency_val
END

BEGIN
    exec sp_DOVIZKARSILIK @currency_val, 'eur'
END

A: If you want to use the output of first store procedure as input of second, it should like this:
declare @ouput1 as int

begin
    exec sp_first 'what_ever', @output1 output
    exec sp_second @output1
end

note the "output" descriptor for the @output1 parameter.

A: If you mean that the value of the second SP input parameter is not correct. This is because both SPs run simultaneously. The second SP must be run after the completion of the first SP. You can use a while statement to do this.
You can test the following code:
    DECLARE @currency_val decimal(18, 2) = -1;
    DECLARE @first_price decimal(18, 2) = 80;
    DECLARE @curr_unit nvarchar(50) = 'eur';

    BEGIN
         exec sp_TLKARSILIK @first_price, @curr_unit @currency_val = @currency_val
    END

WHILE 1=1
BEGIN
IF @currency_val <> -1
BREAK
END
    BEGIN
        exec sp_DOVIZKARSILIK @currency_val, 'eur'
    END


text:
Q: How to test emails that are set to deliver later I can't figure out how to get the syntax to work for asserting that an email has been enqueued properly. Specifically, how do you pass in the arguments to the mailer when the argument is an object?
For example, if you want to pass in a contact object to the example from the documentation:
  assert_enqueued_email_with ContactMailer, :welcome, @contact do
    ContactMailer.welcome(@contact).deliver_later
  end

  assert_enqueued_email_with ContactMailer, :welcome, args: @contact do
    ContactMailer.welcome.deliver_later
  end

  assert_enqueued_email_with ContactMailer, :welcome, [@contact] do
    ContactMailer.welcome.deliver_later
  end

None of these appear to work. If you look at the actual enqueued job, the object looks like this:
{:job=>ActionMailer::DeliveryJob, :args=>["ContactMailer", "welcome", "deliver_now", {"_aj_globalid"=>"gid://app_name/Contact/1015983224"}], :queue=>"mailers"}

Any help is appreciated!

A: You need to pass an array of arguments:
assert_enqueued_email_with ContactMailer, :welcome, args: [@contact] do
  ContactMailer.welcome(@contact).deliver_later
end

A: I know this is probably too late to help you, but I ran across the same issue recently, so hopefully this workaround will help the next person. Under the hood, assert_enqueued_email_with just uses assert_enqueued_with, and we can use it directly to create a test that will find the enqueued email like so.
assert_enqueued_with(job: ContactMailer.delivery_job, args: ['ContactMailer', 'welcome', 'deliver_now', @contact], queue: 'mailers')

The only difference between this test, and what assert_enqueued_email_with generates is @contact isn't wrapped in an extra array.
Edit: I wanted to come back in to mention that I only encountered this error during the middle of an update from Rails 5.2 to Rails 6.0. Once I got further into the update this went away and assert_enqueued_with worked as expected, while the previous workaround using assert_enqueued_with no longer matched. Specifically it was after setting delivery_job to the new default.
Rails.application.config.action_mailer.delivery_job = "ActionMailer::MailDeliveryJob"

A: I had the same problem so my solution was to access the array of enqueued jobs directly and do a comparison manually.
assert_equal ActiveJob::Base.queue_adapter.enqueued_jobs[0][:args][0], "UserMailer"
assert_equal ActiveJob::Base.queue_adapter.enqueued_jobs[1][:args][0], "MarketingMailer"

A: You could try specifying wait time
Notifier.welcome(User.first).deliver_later(wait: 1.hour)

More options for deliver_later:
http://api.rubyonrails.org/classes/ActionMailer/MessageDelivery.html#method-i-deliver_later


text:
Q: Is the Grothendieck ring of varieties reduced? A neat construction of Bjorn Poonen shows that the Grothendieck ring of varieties (over a field of char. 0) is not a domain: http://arxiv.org/abs/math/0204306
Is the Grothendieck ring of varieties reduced? (My guess: the answer is yes, the proof is easy enough that several people have observed this without writing it up anywhere. But I don't know how to show it.)

A: Qing Liu's example probably works, only we don't know if an abelian variety in
positive characteric is determined by its class in
$K_0(\mathrm{Var}_k)$. However, we do know that in characteristic zero (this is
what Bjorn Poonen uses in his examples) and the non-cancellation is a purely
arithmetic phenomenon and hence can be realised in characteristic zero.
Hence, we let $\mathcal A$ be a maximal order in a definite (i.e., $\mathcal
A\otimes\mathbb R$ is non-split) quaternion algebra over $\mathbb Q$. There is
an abelian variety $A$ over some field $k$ of characteristic zero with $\mathcal
A=\mathrm{End}(A)$ (Bjorn works hard to get his example defined over $\mathbb
Q$, here I make no such claim). For any (right) f.g. projective (i.e., torsion
free) $\mathcal A$-module $M$ we may define an abelian variety
$M\bigotimes_{\mathcal A}A$ characterised by $\mathrm{Hom}(M\bigotimes_{\mathcal
  A}A,B)=\mathrm{Hom}_{\mathcal A}(M,\mathrm{Hom}(A,B))$ for all abelian
varieties (concretely it is constructed by realising $M$ is the kernel of an
idempotent of some $\mathcal A^n$ and then taking the kernel of the same
idempotent acting on $A^n$). In any case we see that $M$ and $N$ are isomorphic
precisely when $M\bigotimes_{\mathcal A}A$ is isomorphic to
$N\bigotimes_{\mathcal A}A$.
Now (all the arithmetic results used below can be found in for instance Irving
Reiner: Maximal orders, Academic Press, London-New York), the class group of
$\mathcal A$ is equal to the ray class group of $\mathbb Q$ with respect to the
infinite prime, i.e., the group of fractional ideals of $\mathbb Q$ modulo
ideals with a strictly positive generators. As that is all ideals we find that
the class group is trivial. Furthermore, we have the Eichler stability theorem
which says that projective modules of rank $\geq2$ are determined by their rank and
image in the class group and hence are determined by their rank (the rank
condition comes in in that $\mathrm{M}_k(\mathcal A)$ is a central simple
algebra which is indefinite at the infinite prime). In particular if $M_1$ and
$M_2$ are two rank $1$ modules over $\mathcal A$ and $A_1$ and $A_2$ are the
corresponding abelian varieties we get that $A_1\bigoplus A_2\cong A\bigoplus A$
as the left (resp. right) hand side is associated to $M_1\bigoplus M_2$ (resp.
$\mathcal A^2$). Therefore, to get an example it is enough to give an example of
an $\mathcal A$ for which there exist $M_1\not\cong M_2$. The number (or more
easily the mass) of isomorphism classes of ideals can be computed using mass
formulas and tends to infinity with the discriminant of $\mathcal A$. It is
interesting to note that when the discriminant is a prime $p$ we can go
backwards using supersingular elliptic curves: The mass is equal to the mass of
supersingular elliptic curves in characteristic $p$ and the latter mass can be
computed geometrically to be equal to $(p-1)/24$.


text:
Q: /usr/local/bin/conver cannot find error on imagemagic for movie.py I want use moviepy so, I checking example snippets from official moviepy web site.
I installed all requirements and When I try to run moviepy on jupyter notebook, I get this error:
Code :
txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white')
Error :
OSError: MoviePy Error: creation of None failed because of the following error:

[Errno 2] No such file or directory: '/usr/local/bin/convert'.

This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or that the path you specified is incorrect

My os : M1 BigSur 11.2.3  - MacOS
Also I checked
ls /opt/homebrew/opt
ls /usr/local/Cellar
ls -l /usr/local/opt/

But I cannot find anything about "convert"
Btw I can user imagemagic convert from terminal like that:

magick convert

output is like that:
Version: ImageMagick 7.0.11-7 Q16 arm 2021-04-12 https://imagemagick.org
Copyright: (C) 1999-2021 ImageMagick Studio LLC
License: https://imagemagick.org/script/license.php
Features: Cipher DPC HDRI Modules OpenMP(4.5)
Delegates (built-in): bzlib freetype gslib heic jng jp2 jpeg lcms lqr ltdl lzma openexr png ps tiff webp xml zlib
Usage: convert [options ...] file [ [options ...] file ...] [options ...] file

Image Settings:
  -adjoin              join images into a single multi-image file
  -affine matrix       affine transform matrix
  -alpha option        activate, deactivate, reset, or set the alpha channel
  -antialias           remove pixel-aliasing

How can solve this? Any tip or solution?

A: I solved this error.
I checked my PATH

echo $PATH

After that, I checked path folders and I find 'convert' from /opt/homebrew/bin/convert
After that I copied this file to /usr/local/bin/
So,

sudo cp /opt/homebrew/bin/convert /usr/local/bin/

solved my issue.


text:
Q: Sustainsys.Saml2 multitenant implementation with app.Map() I have multi tenant application where each tenant can use different IdP to authenticate. Below code correctly redirects to IdP but problem is to get back the response to ACS endpoint.
Key is the Configuration method which configures the paths and their authentication:
[assembly: OwinStartup(typeof(SSOSamlDemoASPNET.App_Start.Startup))]
namespace SSOSamlDemoASPNET.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Map("/client/okta", (appx) =>
            {
                ConfigureAuthentication(appx, "/client/okta/Saml2", ...);
            });

            app.Map("/client/azuread", (appx) =>
            {
                ConfigureAuthentication(appx, "/client/azuread/Saml2", ...);
            });
        }

        private static void ConfigureAuthentication(IAppBuilder app, string modulePath, string audience, string issuer, string metadataUrl)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                CookieName = "LoggedUser",
                CookiePath = "/",
                CookieManager = new SystemWebCookieManager(),
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            ConfigureSaml(app, modulePath, audience, issuer, metadataUrl);
        }

        private static void ConfigureSaml(IAppBuilder app, string modulePath, string audience, string issuer, string metadataUrl)
        {
            var saml2options = new Saml2AuthenticationOptions(false);
            var spOptions = new SPOptions
            {
                EntityId = new EntityId(audience),
                ModulePath = modulePath,
                PublicOrigin = new Uri("https://localhost:44340/"),
            };
            spOptions.Logger = new ConsoleLoggerAdapter();
            saml2options.SPOptions = spOptions;

            saml2options.IdentityProviders.Add(new IdentityProvider(new EntityId(issuer), spOptions)
            {
                AllowUnsolicitedAuthnResponse = true,
                MetadataLocation = metadataUrl,
                LoadMetadata = true,
                Binding = Saml2BindingType.HttpPost,
            });

            app.UseSaml2Authentication(saml2options);
        }
    }
}

Authenticating against individual IdP is done like this:
authProperties.Dictionary["idp"] = "https://sts.windows.net/xxx/";
authProperties.RedirectUri = "https://localhost:44340/client/azuread/ExternalLoginCallback";
HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(authProperties, "Saml2");

When inspecting code of the Sustainsys.Saml2 library (especially Saml2AuthenticationHandler). I found the conditions do not take into account OwinRequest.PathBase and therefore the identity is not coming back to the application.
An example can be (Saml2AuthenticationHandler.Invoke method).

*

*Options.SPOptions.ModulePath = /client/azuread/Saml2

*Request.Path = /Saml2/Acs
==> therefore the code inside the condition is not executed.

public override async Task<bool> InvokeAsync()
{
    var Saml2Path = new PathString(Options.SPOptions.ModulePath);

    if (Request.Path.StartsWithSegments(Saml2Path, out PathString remainingPath))
    {
        if (remainingPath == new PathString("/" + CommandFactory.AcsCommandName))
        {
            var ticket = (MultipleIdentityAuthenticationTicket)await AuthenticateAsync();
            if (ticket.Identities.Any())
            {
                Context.Authentication.SignIn(ticket.Properties, ticket.Identities.ToArray());
                // No need to redirect here. Command result is applied in AuthenticateCoreAsync.
            }
            else
            {
                Response.Redirect(ticket.Properties.RedirectUri);
            }
            return true;
        }

Is there any way to change this behavioral? e.g. saml2Options.Notifications to get this working?

A: That is obviously a bug/lack of feature, but nothing that will be fixed on the Owin module - it's on life support.
The solution for a multi tenancy owin app is to register one Saml2 middleware and add multiple IdentityProviders to that one. The middleware will handle all responses on the same endpoint and use the configuration from the right IdentityProvider based on where the response came from.


text:
Q: Transforming definite integral with finite bounds using u-subs into improper integral is possible? Can i transforming this integral:
$$\int_0^1 e^{-xt}\ln\left(\frac{1-x}{x}\right) \Bbb dx\quad t>0$$
By setting :
$$x=-\frac{1}{u}\rightarrow u=-\frac 1x$$
$$x=0\rightarrow u=-\infty$$
$$x=1\rightarrow u=-1$$
My new integral becomes an improper integral:
$$\int_{-\infty}^{-1} \frac{e^{t/u}\ln(-(1+u))}{u^2} \Bbb du$$
Tried to check with Wolfram Alpha when $t=1$, $t=2$, and $t=3$ gave me the same result. But is this allowed in math since we treat it's an undefined expression. Can you explain please?

A: $$I=\int_0^1 e^{-tx} \log \left(\frac{1-x}{x}\right) \, dx$$
Substitute $\frac{1-x}{x}=u\to x=\frac{1}{u+1},\;dx=-\frac{1}{(u+1)^2}$
$$I=\int_0^{\infty } \frac{e^{-\frac{t}{u+1}} \log u}{(u+1)^2} \, du$$
The $u$ integral is almost as hard as the original, though.


text:
Q: Persistant model data in ASP.NET MVC I have two controller functions: one for default viewing, and one for postback. The first one I use to assign some default values to the model's list. The second is to add additional values to the list. After either, the page displays the list's contents. Right now, I'm losing everything in the list except what the latest controller function did.
I'd like my model data to persist, how can this be done?

A: I suppose you have a situation like this:
public class Model {
  public List<..> List { get; set; }
  ...
}

public class MyController
{
  public ActionResult List() {
    return View(new Model { List = new List<..> { /* some items */ } });
  }

  [HttpPost]
  public ActionResult AddToList(Model model, string itemText) {
    model.List.Add(/* another item with specified text*/);
    return View("List", model);
  }
}

In the displayed list page you either have a 1 item added with the AddToList action or the entire list of items initialized in the List action. What happens is natural, because you don't post the list back.
If this is the case, then you have to post back the entire model, including the list itself in order to add an item to the existing list.
This is really a problem of generating the correct View for the List page. The form that triggers the AddToList action must contain the date of the entire model/list. The HTML generated by the view should look something like this:
...
<form method="POST" action="/MyController/AddToList">
   <input type="hidden" name="model.List[0]" value="value1" />
   ...
   <input type="hidden" name="model.List[N]" value="valueN" />
   New item text: <input type="text" name="itemText" />
   ...
</form>
...

A: Persist your data in database(use EF(http://msdn.microsoft.com/en-us/library/bb399572.aspx)).


text:
Q: Custom spinner adapter simple_spinner_dropdown_item not displaying correctly I am getting data from an SQLite database and assigning them to data objects. I am using a custom spinner adapter (implements SpinnerAdapter) to put them in spinners so as to override the getItem() and getItemId() methods. However, the android.R.layout.simple_spinner_dropdown_item is not displaying correctly (screenshots from my Galaxy Tab 2 10.1):

By contrast this is a spinner which is populated from an array in R.array (the correct look/size):

Done by this code:
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.quote_prices, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

I am unable to get this look by implementing/extending some sort of adapter (I have also tried extending BaseAdapter to no avail). This is the code for my spinner adapter as it stands:
public class MySpinnerAdapter implements SpinnerAdapter {

    private Context context;
    /**
     * The internal data (the ArrayList with the Objects).
     */
    private List<? extends BaseDO> data;

    public MySpinnerAdapter(Context context, List<?extends BaseDO> data){
        this.context = context;
        this.data = data;
    }

    /**
     * Returns the Size of the ArrayList
     */
    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return data.get(position).getId();
    }

    @Override
    public int getItemViewType(int position) {
        return 0;
    }

    @Override
    public int getViewTypeCount() {
        return 1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(android.R.layout.simple_spinner_dropdown_item, null);
        }
        ((TextView) convertView).setText(data.get(position).toString());
        return convertView;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = (TextView) View.inflate(context, android.R.layout.simple_spinner_item, null);
        textView.setText(data.get(position).toString());
        return textView;
    }

    @Override
    public void registerDataSetObserver(DataSetObserver observer) {

    }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {

    }

    public List<? extends BaseDO> getData() {
        return data;
    }

}

Any help would be appreciated.
EDIT: I forgot to mention that this is called using
spnnrTerm.setAdapter(new MySpinnerAdapter(getActivity(), termList));

A: I know this question is old but I've been having the same issue and have just figured out the problem. After examining the source for ArrayAdapter.java I noticed it was passing the ViewGroup to the inflater and I wasn't. This was the problem all along.
    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
        }
        ((TextView) convertView).setText(data.get(position).toString());
        return convertView;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = (TextView) View.inflate(context, android.R.layout.simple_spinner_item, null);
        textView.setText(data.get(position).toString());
        return textView;
    }


text:
Q: How can I use the PCL visualizer (Windows) and avoid the WM_QUIT message closing my application when the visualizer closes I am using the PCL visualizer saveScreenshot() to create a png of my pointcloud. That's all working, but when I call viewer.close(), the Windows implementation calls TerminateApp which sends a WM_QUIT that closes my application. What I want to happen is the visualizer window close and have my application continue.
I don't need any user interaction with the visualizer window. I'm just using it to get the .png from the pointcloud.
I tried initializing the visualizer without an interactor, but saveScreenshot() doesn't work with a null interactor.
Is there some way to set up the interactor without a message proc?

A: You can use pcl::io::savePNGFile() to export a PNG directly from your program

A: Can savePNGFile use camera intrinsics? Would I add camera intrinsics to the cloud to get the PNG I want?


text:
Q: reset R shiny actionButton to use it more than once Does someone know how to make actionButton (R shiny) reset to initial value in order to use it more than once?
Please find below a reproductible example:
In this example, I would like to change the chart color by selecting the corresponding button: my issue is that it cannot reload the chart after one iteration.
library(shiny)

ui <- fluidPage(

  actionButton(inputId = "button1",label = "Select red"),
  actionButton(inputId = "button2",label = "Select blue"),
  plotOutput("distPlot")

)

server <- function(input, output) {

   output$distPlot <- renderPlot({
      x    <- faithful[, 2]
      bins <- seq(min(x), max(x))

      my_color <- "green"
      if (input$button1){my_color <- "red"}
      if (input$button2){my_color <- "blue"}

      hist(x, breaks = bins, col = my_color)
   })
}

shinyApp(ui = ui, server = server)

Thank you in advance

A: It's not good idea to reset ActionButton in Shiny usually.
I would suggest you to use ObserveEvent and store the color into reactiveValues.
library(shiny)

ui <- fluidPage(
  actionButton(inputId = "button1", label = "Select red"),
  actionButton(inputId = "button2", label = "Select blue"),
  plotOutput("distPlot")
)

server <- function(input, output) {
  r <- reactiveValues(my_color = "green")

  output$distPlot <- renderPlot({
    x <- faithful[, 2]
    bins <- seq(min(x), max(x))
    hist(x, breaks = bins, col = r$my_color)
  })

  observeEvent(input$button1, {
    r$my_color <- "red"
  })

  observeEvent(input$button2, {
    r$my_color <- "blue"
  })
}

shinyApp(ui = ui, server = server)


text:
Q: ORA-00911: invalid character issue? So I have procedure that compiles without issue, but when I run it it returns:
Error report -
ORA-00911: invalid character
ORA-06512: at "MYDATABASE.MY_PROCEDURE", line 4
ORA-06512: at line 2
00911. 00000 -  "invalid character"
*Cause:    identifiers may not start with any ASCII character other than
           letters and numbers.  $#_ are also allowed after the first
           character.  Identifiers enclosed by doublequotes may contain
           any character other than a doublequote.  Alternative quotes
           (q'#...#') cannot use spaces, tabs, or carriage returns as
           delimiters.  For all other contexts, consult the SQL Language
           Reference Manual.
*Action:

Here's procedure
CREATE OR REPLACE PROCEDURE MY_PROCEDURE
IS
BEGIN
EXECUTE IMMEDIATE 'ALTER TABLE CHILD_TABLE ADD CONSTRAINT FK_CHILD_TABLE_PARENT_TABLE FOREIGN KEY (PARENT_TABLE_ID) REFERENCES PARENT_TABLE(ID) ON DELETE CASCADE;';
END;

Here's how I call it :)
BEGIN
MY_PROCEDURE;
END;

I can mention that there's no fault in
ALTER TABLE CHILD_TABLE ADD CONSTRAINT FK_CHILD_TABLE_PARENT_TABLE FOREIGN KEY (PARENT_TABLE_ID) REFERENCES PARENT_TABLE(ID) ON DELETE CASCADE;

Because it runs without issue outside of procedure body :)

A: Remove the ; inside a query in EXECUTE IMMEDIATE:
CREATE OR REPLACE PROCEDURE MY_PROCEDURE
IS
BEGIN
EXECUTE IMMEDIATE 'ALTER TABLE CHILD_TABLE ADD CONSTRAINT FK_CHILD_TABLE_PARENT_TABLE FOREIGN KEY (PARENT_TABLE_ID) REFERENCES PARENT_TABLE(ID) ON DELETE CASCADE';
END;


text:
Q: Can sub-columns be created in a pandas data frame? Data frame
I am working with a data frame in Jupyter Notebooks and I am having some difficulty with it. The data frame consists of locations and these are represented by coordinates. These points represent a route taken by a driver on a given day.
There are 3 columns at the moment; Start, Intermediary or End.
A driver begins the day at the Start point, visits 1 or more Intermediary points and returns to the End point at the end of the day. The Start point is like a base location so the End point is identical to the Start point.
It's very basic but I am having trouble visualising this data. I was thinking something like this below to help improve my situation:
|     Start      |       Intermediary       |        End        |
|       |        |            |             |         |         |
_________________________________________________________________
| s_lat | s_lng  |  i_lat     |  i_lng      | e_lat   | e_lng   |

Or would it be best if I scrap the top 3 columns (Start, Intermediary, End)?
I am keen not to start a discussion here as per the Guidelines so I am keen to learn something new about Python Pandas and if there is a way I can improve my current method.

A: I think need here MultiIndex created by MultiIndex.from_product:
mux = pd.MultiIndex.from_product([['Start','Intermediary','End'], ['lat','lng']])
df = pd.DataFrame(data, columns=mux)

EDIT:
Setup:
temp=u"""                          start                                   intermediary                           end
('54.957055',' -7.740156')        ('54.956915136264', ' -7.753690062122')     ('54.957055','-7.740156')
('54.8913208', '-7.5740475')    ('54.864402885577', '-7.653445692445'),('54','0')   ('54.8913208','-7.5740475')
('55.2375819', '-7.2357427')     ('55.253936739337', '-7.259624609577'), ('54','2'),('54','1')   ('55.2375819','-7.2357427')
('54.5298806', '-8.1350247')    ('54.504374314741', '-8.188334960168')      ('54.5298806','-8.1350247')
('54.2810187',  ' -7.896937')   ('54.303836850038', '-8.180136033695'), ('54','3')       ('54.2810187','-7.896937')

"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(pd.compat.StringIO(temp), sep="\s{3,}")

print (df)
                           start  \
0     ('54.957055',' -7.740156')
1   ('54.8913208', '-7.5740475')
2   ('55.2375819', '-7.2357427')
3   ('54.5298806', '-8.1350247')
4  ('54.2810187',  ' -7.896937')

                                        intermediary  \
0            ('54.956915136264', ' -7.753690062122')
1  ('54.864402885577', '-7.653445692445'),('54','0')
2  ('55.253936739337', '-7.259624609577'), ('54',...
3             ('54.504374314741', '-8.188334960168')
4  ('54.303836850038', '-8.180136033695'), ('54',...

                           end
0    ('54.957055','-7.740156')
1  ('54.8913208','-7.5740475')
2  ('55.2375819','-7.2357427')
3  ('54.5298806','-8.1350247')
4   ('54.2810187','-7.896937')

import ast

#convert string values to tuples
df = df.applymap(lambda x: ast.literal_eval(x))
#convert onpy pairs values to nested lists
df['intermediary'] = df['intermediary'].apply(lambda x: list(x) if isinstance(x[1], tuple) else [x])

#DataFrame by first Start column
df1 = pd.DataFrame(df['start'].values.tolist(), columns=['lat','lng'])

#DataFrame by intermediary column with reshape for 2 columns df
df2 = (pd.concat([pd.DataFrame(x, columns=['lat','lng']) for x in df['intermediary']], keys=df.index)
       .reset_index(level=1, drop=True)
       .add_prefix('intermediary_'))
print (df2)

#join all DataFrames together
df3 = df1.add_prefix('start_').join(df2).join(df1.add_prefix('end_'))

#create MultiIndex by split
df3.columns = df3.columns.str.split('_', expand=True)

print (df3)

        start                 intermediary                           end  \
          lat         lng              lat               lng         lat
0   54.957055   -7.740156  54.956915136264   -7.753690062122   54.957055
1  54.8913208  -7.5740475  54.864402885577   -7.653445692445  54.8913208
1  54.8913208  -7.5740475               54                 0  54.8913208
2  55.2375819  -7.2357427  55.253936739337   -7.259624609577  55.2375819
2  55.2375819  -7.2357427               54                 2  55.2375819
2  55.2375819  -7.2357427               54                 1  55.2375819
3  54.5298806  -8.1350247  54.504374314741   -8.188334960168  54.5298806
4  54.2810187   -7.896937  54.303836850038   -8.180136033695  54.2810187
4  54.2810187   -7.896937               54                 3  54.2810187

          lng
0   -7.740156
1  -7.5740475
1  -7.5740475
2  -7.2357427
2  -7.2357427
2  -7.2357427
3  -8.1350247
4   -7.896937
4   -7.896937

A: To add a top to column to a pd.DataFrame run:
def add_top_column(df, top_col, inplace=False):
    if not inplace:
        df = df.copy()

    df.columns = pd.MultiIndex.from_product([[top_col], df.columns])
    return df

orig_df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
new_df = add_top_column(orig_df, "new column")

In order to combine 3 DataFrames each with its own new top column:
new_df2 = add_top_column(orig_df, "new column2")
new_df3 = add_top_column(orig_df, "new column3")
print(pd.concat([new_df, new_df2, new_df3], axis=1))

"""
# And this is the expected output:
  new column    new column2    new column3
           a  b           a  b           a  b
0          1  2           1  2           1  2
1          3  4           3  4           3  4
"""

Note that if the DataFrames' index do not match, you might need to reset the index.

A: You can read an Excel file with 2 headers (2 levels of columns).
   df = pd.read_excel(
        sourceFilePath,
        index_col = [0],
        header = [0, 1]
    )

You can reshape your df like this in order to keep just 1 header (its easier to work with only 1 header):
df = df.stack([0,1], dropna=False).to_frame('Valeur').reset_index()


text:
Q: How do I write to the application window log with MVC I have a simple MVC application that sometimes fails in production. I would like to write a message to the log that I can view with server manager. It seems like a simple thing to do but I've not found any reference to others doing it.
Can someone please help. I'm stuck "-(
Marie

A: http://msdn.microsoft.com/en-us/library/6w20x90k.aspx
System.Diagnostices.Eventlog.WriteEntry("Application", "your message here");


text:
Q: Compiler through command line Using putty, I want to manage compiler mode through command line, but the answer received is always the compiler help:
myuser@serv01 [~]# php public_html/shell/compiler.php state
Content-type: text/html

Usage:  php -f compiler.php -- [options]

state         Show Compilation State
compile       Run Compilation Process
clear         Disable Compiler include path and Remove compiled files
enable        Enable Compiler include path
disable       Disable Compiler include path
help          This help

What am I doing wrong?

A: This issue related to php configuration. Magento shell script uses $_SERVER['argv'] variables to run particular shell script (see shell/abstract.php). You should enable register_argc_argv setting in php.ini if php is not running in CLI mode.
register_argc_argv = On

ADDITIONAL
Create test.php file and add these lines for debugging:
echo php_sapi_name();//this should be printed as "cli"
print_r($_SERVER['argv']);// this should print out arguments

And run the script php -f test.php some extra args
If no results try to run script following:
php -cli public_html/shell/compiler.php state


text:
Q: Как получить значение jquery в выбранном блоке? Ребят, всем привет. Есть такая верстка:

<input type="hidden" value="1" name="id"/>
<button class="add_cart">Добавить</button>

<input type="hidden" value="2" name="id"/>
<button class="add_cart">Добавить</button>

<input type="hidden" value="3" name="id"/>
<button class="add_cart">Добавить</button>

Когда нажимаю на "добавить", я хочу получить значение inputa name='id'. Как это реализовать из данной верстке?
A: $(document).on('click', '.add_cart', function() {
    var id = $(this).prev().val();
    alert(id);
});

или если вёрстка таки поменяется
$(document).on('click', '.add_cart', function() {
    var id = $(this).closest('.product_list').find('input[name="id"]').val();
    alert(id);
});

A:
jsfiddle.net/30dw5ncs/

Вот оптимальнее вариант, на родном JS

jsfiddle.net/30dw5ncs/1/

$('.add_cart').on('click', function(){
    var id = this.previousElementSibling.value;

    alert(id);
});

<input type="hidden" value="1" name="id"/>
<button class="add_cart">Добавить</button>

<input type="hidden" value="2" name="id"/>
<button class="add_cart">Добавить</button>

<input type="hidden" value="3" name="id"/>
<button class="add_cart">Добавить</button>

A: Решение строится на основе этих 2х вещей:

*

*
Get the siblings of each element in the set of matched elements, optionally filtered by a selector

*
Attribute Equals Selector


text:
Q: How to make a static class to reference string variables with C++? So I am trying to make a general C++ static that just holds string variables. I am using Unreal Engine 4 in this project. I have a working solution, but am looking to see if what I do in C# can be done in C++.
Working Solution (C++):
DFControllerGameModeBase.h
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "DFControllerGameModeBase.generated.h"

#define MoveForwardInput        "MoveForward"

Implementation:
#include "DFControllerGameModeBase.h"

void ADFCharacter::Play(){
.....

string text = MoveForwardInput;

}

However this is what I do in C# with Unity:
using System;

namespace Assets.Scripts.Helpers
{

    public static class Utilities
    {
        public static string MoveForward = "MoveForward";
    }
}

Implementation:
using Assets.Scripts.Helpers;

void Play(){

string text = Utilities.MoveForward;

}

A: If you have no problem with encapsulation and will not be using the statics in Blueprint, then just using #define will do.
You also want to use capital letters for #define naming convention.
#define MOVE_FORWARD_INPUT "MoveForward"

But if you want it encapsulated and be able to call it in the Blueprint. Then you'll have to create a static helper class.
.h
class Utilities
{
public:
    static const FString MoveForward;

    //create BP getter function here
}

.cpp
const FString Utilities::MoveForward = "MoveForward";


text:
Q: Microsoft Power Automate Wrong OAuth Token I created a Custom Connector with Microsoft Automate.
I need the Connector to get a OAuth Token v2 but get a v1 Token.
When I use the same configuration in Postman I get a v2 Token.
The application manifes has the entry "accessTokenAcceptedVersion": 2

A: What you're describing isn't possible, the application where you're requesting the token for dictates the token version.
It's not described in your question, so I'm assuming that you have an app exposing the scope (with team.create) and have an other application that you are using to request a token?
Are you sure you are checking the right token?
Have you inspected the tokens at https://JWT.ms, be sure to check the audience (if it's graph by accident, it will always be a v1 token)
And last note, why do you care about the token version? Shouldn't really matter which one is used.


text:
Q: How to use ndb.OR in a loop? The correct way of using an ndb.OR is like this:
q = News.query(ndb.OR(News.source == 'GRD', News.source == 'IND'))

Which results in an OR-filter.

Query(kind='News', filters=OR(FilterNode('source', '=', 'GRD'),
  FilterNode('source', '=', 'IND')))

But how do I do that in a loop?
When I try this:
q = News.query()
for source in sources:
    q = q.filter(ndb.OR(News.source == source))

It becomes an AND-filter:

Query(kind='News', filters=AND(FilterNode('source', '=', 'GRD'),
  FilterNode('source', '=', 'IND')))

A: When you repeatedly apply filters like that, you are chaining the filters, with each filter filtering the already filtered results.
To filter by any of your sources you can use IN.  Quoting from the docs:

Similarly, the IN operation

property IN [value1, value2, ...]

which tests for membership in a list of possible values, is implemented as

(property == value1) OR (property == value2) OR ...

So you could do:
qry = News.query(News.source.IN(sources))


text:
Q: adding fade transition to images using jquery This question has been asked here, Image Replacement (gallery style) with Fade-In's / Fade-Out's
This is the script http://www.webdesignerwall.com/demo/jquery/img-replacement.html
But, I'm not sure if it accomplishes what I want, I can't get it to work.
I just want to get a smooth cross fade transition between this image replacement. I've been searching and messing with picture gallery scripts all night.
Any help?

A: tvanfosson suggested something like this in his answer to the question you noted:
http://jsfiddle.net/ambiguous/SH5Q9/
The basic idea is to wrap a <div> around the the large image and then apply the fadeOut() and fadeIn() effects to that <div>.
Also, you would do well to set yourself up on http://jsfiddle.net, it is a great tool for playing around with things and makes it easy to show people on SO what you've tried already.


text:
Q: How can I do this curl request in a Laravel test? I'm working under TDD in a Laravel 8 project, I'm making a token generation test, a client has to send its user and password and then my app has to generate the token and send it back. I'm making the test for this, but I don't know how to make the request, the request that I want to do is something like this curl:
curl -X "GET" https://127.0.0.1:8000/token
-H "Accept: application/json"
-H "Content-Type: appication/json"
-u "JohnDoe:johndoeiscool123"

As you can see, there are some headers and there is one -u field, I don't know how to set this -u in a Laravel test, I have this:
public function test_getting_token() {

    $response = $this->get("/token", [

        "Accept: application/json",
        "Content-Type: application/json",

    ]);

}

Can someone help me please?


text:
Q: how to expand variables to multiple rules in makefile? Say that I have two variables in Makefile
CXXFILES = a.cpp b.cpp
OBJFILES = a.o b.o

I would like to write a rule that will expand to
a.cpp : a.o
  g++ -o a.o a.cpp
b.cpp : b.o
  g++ -o b.o b.cpp

Note that I'm not looking for
%.o : %.cpp
  g++ -o $@ $<

because I don't want to match all .cpp files -- I only want those files specified by a variable.

A: Sounds like a job for a Static Pattern Rule:

Here is an example, which compiles each of foo.o and bar.o from the
  corresponding .c file:
objects = foo.o bar.o

all: $(objects)

$(objects): %.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@


text:
Q: JList have some troubles with indexes so i cant remove items i created a GUI with an ADD and REMOVE button to save items to a JList. The add button works perfectly but when i want to remove something i stumble across a problem. My remove button works like this, when i press it, i get the selected index that i have marked and removes the item at the index. My problem is that when i press the item i want to remove and then hit REMOVE it doesnt save the index and it just returns -1 which tells me that no index has been marked. Any tips how i work around this?
 private void removeProductActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    productList.getModel();
    int selectedIndex = productList.getSelectedIndex();

    if(selectedIndex != -1){

        listModel.remove(selectedIndex);
    }
}

A: are you sure your JList is setup correctly?
public static void main(String[] args) {

    DefaultListModel<String> model = new DefaultListModel<>();
    model.addElement("1");
    model.addElement("2");
    model.addElement("3");
    model.addElement("4");

    JList<String> test = new JList<>(model);
    test.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    test.setSelectedIndex(2);

    System.out.println("items before removal");
    for (int i = 0; i < model.getSize(); i++) {
        System.out.println(model.getElementAt(i));
    }

    int selectedIndex = test.getSelectedIndex();
    if (selectedIndex > 0) {
        System.out.println(String.format("removing item at index %d : %s", selectedIndex, model.getElementAt(selectedIndex)));
        model.remove(selectedIndex);
    }

    System.out.println("items after removal");
    for (int i = 0; i < model.getSize(); i++) {
        System.out.println(model.getElementAt(i));
    }
}

A: So i did find a solution, i dont know if it was the best but it is working.
If anyone finds anything which will be better just post it.
What i've done is i'm using a listselectionlistener and when a item is pressed its saves the index into a global variable which my REMOVE button reads the value from.
    private void indexListener() {
    ListSelectionListener listSelectionListener = new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent listSelectionEvent) {
            productList.getModel();
            selectedIndex = listSelectionEvent.getFirstIndex();

        }

    };
    productList.addListSelectionListener(listSelectionListener);

}


text:
Q: Setting sqljdbc driver in Apache Tomcat files I am developing an android app that connects with a computer and draws some tables from MS SQL Server. To do that i created a servlet that gets the requests from the android app and do some things to a database of SQL Server. In the beginning i was using eclipse to develope the servlet and everything was fine. Now i want to run the servlet without eclipse. So i installed Apache Tomcat and i added my servlet in there. The servlet is running and the android app connects fine with the servlet. The problem is that when the servlet tries to connect to SQL Server it fails. This is probably because it can't see the jar file of the driver. When i added the driver on eclipse except the jar file i added a dll file named sqljdbc_auth. Does anybody knows where should i put and what files of the driver so that the servlet can do the connection with the SQL Server ???
Thank you very much.


text:
Q: Need help using split function This function adds up the numbers between zero in a string.  For example ('25025') becomes 25+25.  However, if I have a 0 at start and/or end of the string of the string argument being sent to test_string, it creates a space in the at the start/end of the list and won't compute.  What can I add to this function to make it filter out both 0s and blank spaces?
def test_one(test_string):
      test = test_string.split("0")
      numbers=[int(x) for x in test]
      print(sum(numbers))

test_one('2022022022')
test_one('02022020')
test_one('25025')

A: If you're ok with keeping your current approach, then this should do:
test = test_string.strip('0').split("0")
numbers = [int(x) for x in test]

Otherwise, you could use a comprehension in a generator expression altogether:
sum(int(x) for x in test_string.strip('0').split("0"))
#                                 ^

A: Replace this:
numbers=[int(x) for x in test]

With this:
numbers=[int(x) for x in test if x]

This code is self-explanatory: convert x to integer and append it to the list if bool(x) is True, thus skipping all the empty strings.
str.split("0") treats "0" as a delimiter and doesn't include any occurrences of it in the result. Check the docs for some examples and more explanation.

A: You can use string one of methods strip()/rstrip()/lstrip().
>>> s = '0138076023'
>>> s.lstrip('0')
'138076023'
>>> s.strip('0')
'138076023'
>>> s = '   asasd   '
>>> s.strip()
'asasd'
>>>

Docs about these methods can be found here

A: Try this
def test_one(test_string):
    test = test_string.split("0")
    print(test)
    if test[0] != '':
        numbers=[int(x) for x in test]
    else:
        test = test[1:]
        numbers=[int(x) for x in test]
    print(sum(numbers))

test_one('2022022022')
test_one('02022022022')

both  test_one('2022022022') and test_one('02022022022') will return the same
There've been a mistake on my side regarding case when string ends in zero. Made a correction.


text:
Q: D3.js identifying links between nodes to change link thickness I have been setting up graphs to dynamically scale in reference to the width and height of the svg or bounding box, and with nodes and node borders this is relatively simple. By using d.depth and assigning the desired ratio to assign a relative radius to a node at a certain depth, this is giving me no problems and nodes at lower depths become smaller to avoid overlap. Then, for the node border I assign a ratio between the node radius and the thickness of the border.
This has proven to be an ideal solution to a problem that arises when adding a zoom feature by scaling the container. This is the problem:

The text, the nodes, and the node borders no longer bunch up, but the links remain the same weight.
I would also like to scale the thickness of the edges between nodes but I do not know how to identify edges so that I can either assign a thickness in relation to the radius of the parent or child node
d3.json("aviation.json", function(root) {
  var nodes = balloon.nodes(root),
      links = balloon.links(nodes);

var link= svg.selectAll("path")
    .data(links)
  .enter().append("path")
    .attr("d",diagonal)
    .attr("stroke", "black")
    .attr("shape-rendering", "auto")
    .attr("fill", "none")
    .data(nodes)
    .attr("stroke-width", function(d) {return (1/5000*diameter);});

  var node = svg.selectAll("g.node")
    .data(nodes)
    .enter()
    .append("g")
    .attr("class", "node");

  node.append("circle")
      .attr("r", function(d) { return d.r;})
      .attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; })
      .attr("fill", "white")
      .attr("opacity", "0.05")
      .attr("stroke-width", function(d) {return d.r/600;}) //here I am referecing d.r
                                                          //to find the stroke width.
      .attr("stroke-opacity", ".5")
      .on("Click", function(d) { return zoomClick});

var text = svg.selectAll("g.text")
      .data(nodes)
      .enter()
      .append("text")
      .attr("dx", function(d) { return d.x })
      .attr("dy", function(d) { return d.y })
      .attr("font-family", "Helvetica")
      .attr("font-size", function(d)  {return d.children ? d.r/7 : d.r/4;})
      .attr("stroke-width", function(d) {return d.r/400;})
      .attr("stroke-opacity", "1")
      .attr("fill", "white")
      .attr("pointer-events", "all")
      .style("text-anchor", "middle")
      .text(function(d) { return d.name; })


text:
Q: Visual Studio Style Undo/Redo Button in WPF I want to make a Ribbon Undo/Redo Button that looks and functions like Visual Studio's Undo/Redo Buttons.
I've been trying to use RibbonSplitButton to mimic the behavior, but it turns out it only accepts menuitems inside its Items Property.
Does anybody have an idea on how to go about this?
Thanks in Advance.
p.s. worst case scenario would be writing a custom control to override the existing splitbutton but does anybody know what to override?

A: It should not be a problem that only MenuItems are allowed as long as you can bind to it using an ItemsSource property or the like. Your application just needs a Undo and Redo stack of commands which should be provide methods for Undo/Redo and a UI friendly display string. These stacks can then be bound to the list and hopefully DataTemplated to show the display string and call the right methods upon click.


text:
Q: Can we compute trend for all columns by group? I have a data frame as shown below. I want to compute the trends of all numeric columns and if they are significant or not per name.
   library(EnvStats)
  dat=structure(list(date = c("1983-12-01", "1984-01-01",
  "1984-02-01",
                    "1984-03-01", "1984-04-01", "1984-05-01"),
  rig = c(68.1, 62.4,

   67.5, 78.9, 81.7, 72.2), pass = c(9.57, 10.49, 11.97,
  11.43, 9.54,

  8.98), name = structure(c(1L, 2L, 3L, 4L, 5L, 6L), levels =
  c("az",  "az", "nc", "nc", "et", "et"), class = "factor")),
  row.names = c(NA, 6L), class = "data.frame")

Is there a function in R to do this? We can use:
kendallTrendTest(rig ~ date)

but how should I do this to have the output like this for all colums?:
  name    rig_trend_slope   rig_trend_pvalue pass_trend_slope   pass_trend_pvalue
  az
  nc
  et

A: As @Quiten mentioned the number of observations in the data are limited, so a group by approach would return error.  If we want to do this on multiple columns, loop across the columns in summarise, extract the needed components from the list output as a tibble and then use unnest_wider to create wide dataset
library(dplyr)
library(tidyr)
library(EnvStats)
library(tibble)
library(flextable)
library(officer)
dat1 <- dat %>%
  mutate(date2 = as.numeric(as.Date(date))) %>%
  # group_by(name) %>%
  # or use reframe in the devel version
  summarise(across(rig:pass, ~
                     {tmp <- kendallTrendTest(reformulate('date2',
     response = cur_column()))
                     tibble(trend_slope = tmp$estimate['slope'],
                            trend_pvalue = tmp$p.value)})) %>%
  unnest_wider(where(is_tibble), names_sep = "_") %>%
  flextable %>%
  colformat_double(i=1,digit=2 )
for(nm in dat1$col_keys)
  {dat1 <- dat1 %>%
  color(i= as.formula(sprintf("~%s<0", nm)), j=nm, color="red")
  }

-output

To save as word format, we may use save_as_docx from officer package
tf <- tempfile(fileext = ".docx")
save_as_docx(
  dat1, path = tf
)

-output

NOTE: Here the group_by(name) is commented as there are only 2 observations and it returns in error for all the cases.  With the full dataset, uncomment the group_by(name)
The broom::tidy seems to have an issue with the class from kendallTrendTest

A: First, you only have two values per group which is not ideal. To calculate the trend per group you could use dplyr with group_by and do to perform the test. Also make sure your x variable in your kendallTrendTest is numeric. You could use tidy to get some coefficients. Here is a reproducible example:
library(dplyr)
library(EnvStats)
library(broom)

models <- dat %>%
  mutate(date2 = as.numeric(as.Date(date))) %>%
  group_by(name) %>%
  do(model = kendallTrendTest(rig ~ date2, data = .))

models %>%
  broom::tidy(model)


text:
Q: Javascript RegExpresion here is my string
str = "asd;images30/127ef-30-30-wm.jpg;59 | asd;images30/127ef-30-30-wm.jpg;60 | "

and regexp is
var re = new RegExp(".*?;.*?;"+$(this).parent().attr("id")+" | ","ig");

and replace function is
str.replace(re,'');

i actually want to remove asd;images30/127ef-30-30-wm.jpg;59 | from string.
Above Regular expression return
 | asd;images30/127ef-30-30-wm.jpg;60 |

whereas expected is
asd;images30/127ef-30-30-wm.jpg;60 |

A: You have to replace the | in your RegExp call with \\|. This is necessary because the single backslash will be ignored (if the character afterward had been used within escape sequences, e.g., if it were an n, these two would become a newline escape sequence, but for characters not part of escape sequences, a single backslash is ignored), and the additional one will cause the single one to appear. Then it can be used in the regular expression to indicate you are escaping a literal pipe symbol and not the built-in regex "alternate" symbol.
Note that if your id from jQuery could be non-numeric, you might also need to escape this value. You can escape it with a function like this.
To hard-code an ID here (based on your example, the value was apparently 59), if you remove the double backslashes, it won't remove the first pipe:
str = "asd;images30/127ef-30-30-wm.jpg;59 | asd;images30/127ef-30-30-wm.jpg;60 | ";
var re = new RegExp(".*?;.*?;"+59+" \\| ","ig");
str = str.replace(re,'');

alert(str)


text:
Q: Is there an efficient way to convert a3d scene to a 2d Enhanced Metafile I am developing a CAD application using Delphi2010 and OpenGL. Currently, i am working on a module to export the current view to an Image file.
This is pretty straigthforward for raster formats (render scene to offscreen Buffer of desired Dimensions, write buffer to disk), but I also wish to be able to export an axis-aligned 2d-View of my scene to a vector format, preferably Winows EMF.
I was thinking about calculating my transformations and projection in software, or misuse glFeedback functionality. Since i would have to implement my own z-buffering, this approach seems to be rather laborious, not to mention the performance issues i might face rendering a complex scene without hardware acceleration.
Since my Google-fu did not lead to a result, i want to ask if anyone of you has experience with this problem (convert Opengl-3d-scene to 2d-Vectorimage), or if there is any 3rd-party library known to implement this.

A: This is a very hard task, it involves analytical hidden lines removal, polygon splitting and Z-sorting for final output as explained here: http://www.cs.drexel.edu/~david/Classes/CS430/HWs/p214-weiler.pdf

A: There is a C library that does this.  It can output PostScript, PDF and SVG.  It supports smooth shading too.
While you probably won't be able to use it directly, it might give you some ideas:
http://www.geuz.org/gl2ps/


text:
Q: Lisp: Problem with package prefix in macro/function definitions I want to create a macro (or function) which will contain package-prefixed symbols. This is possible only if those packages have already been defined. Why? As long as i have defined the packages by the time the macro/function gets called, why is there a problem if they are undefined when the macro/function is defined?
The reason I want this is that i want to have convenience functions in my init file for starting-stopping stuff i develop in different projects-packages but I dont want to load all the projects just to be able to define the convenience functions, since i only develop one project at a time.

A: The source code is read by the Lisp reader before evaluation (see read). The reader can't intern the symbols if the packages aren't already defined.

A: (funcall (find-symbol "RENDER-SUPER-FANCY-GRAPHICS"
                      "THIS-PACKAGE-DOES-NOT-YET-EXIST")
         *standard-output* :width 1000 :height 800)


text:
Q: Wireframe tool for WordPress theme I want to develop a WordPress theme from scratch. Is there any wireframe tool in which I can design the a complete page and it exports the html/php file against it. I want a free tool.

A: I personally do not know of any free tool that would achieve what you are looking for. The closest thing would be to use a "slice and chop" company that would take your designs and slice them up for you at a price though.
There is a great "blank" wordpress theme out there that I use on all of my projects. It has all of the files you need for a theme, with most (if not all) of the queries that you need. All you have to do is pretty much style it.
However, the Wordpress Codex is a great resource for learning all the nuts and bolts of wordpress.  I know it has been a life saver to me over the years.

A: The only one I know is Artisteer. It's a commercial product but it offers a free trial. Here's a demo of how it can be used specifically for creating Wordpress themes.
You could also start a theme with the help of Wordpress Theme Generator.

A: I have purchased Artisteer, and am quite happy with it, in the latest version 3.1 which was just released, they added a lot of essential features (to me) and improved the basic template (reduced complexity and other improvements).
You can download a fully featured version, the generated theme comes filled with preview images, but you can see how it works and if it works for you.
However, it is not a wireframe tool at all, it is just a tool to create visually pleasing templates for many CMS systems (or pure HTML), it helps the non-creative folk generate a neat looking website without tearing their hair out. The major feature for us graphically challenged is the "Suggest" feature, which is the main base of the app.
And for the price, there is nothing quite like it... Give it a try.

A: Take a look at this website weaver
Website weaver is no longer free, it changed to spiderweb press which is
125$


text:
Q: Replace Validation Monitors with tf.train.SessionRunHook when using Estimators I am running a DNNClassifier, for which I am monitoring accuracy while training. monitors.ValidationMonitor from contrib/learn has been working great, in my implementation I define it:
validation_monitor = skflow.monitors.ValidationMonitor(input_fn=lambda: input_fn(A_test, Cl2_test), eval_steps=1, every_n_steps=50)

and then use call from:
clf.fit(input_fn=lambda: input_fn(A, Cl2),
            steps=1000, monitors=[validation_monitor])

where:
clf = tensorflow.contrib.learn.DNNClassifier(...

This works fine. That said, validation monitors appear to be deprecated and a similar functionality to be replaced with tf.train.SessionRunHook.
I am a newbie in TensorFlow, and it does not seem trivial to me how such a replacing implementation would look like. Any suggestion are highly appreciated. Again, I need to validate the training after a specific number of steps.
Thanks very much in advance.

A: I managed to come up with a way to extend tf.train.SessionRunHook as suggested.
import tensorflow as tf

class ValidationHook(tf.train.SessionRunHook):
    def __init__(self, model_fn, params, input_fn, checkpoint_dir,
                 every_n_secs=None, every_n_steps=None):
        self._iter_count = 0
        self._estimator = tf.estimator.Estimator(
            model_fn=model_fn,
            params=params,
            model_dir=checkpoint_dir
        )
        self._input_fn = input_fn
        self._timer = tf.train.SecondOrStepTimer(every_n_secs, every_n_steps)
        self._should_trigger = False

    def begin(self):
        self._timer.reset()
        self._iter_count = 0

    def before_run(self, run_context):
        self._should_trigger = self._timer.should_trigger_for_step(self._iter_count)

    def after_run(self, run_context, run_values):
        if self._should_trigger:
            self._estimator.evaluate(
                self._input_fn
            )
            self._timer.update_last_triggered_step(self._iter_count)
        self._iter_count += 1

and used it as a training_hook in Estimator.train:
estimator.train(input_fn=_input_fn(...),
                steps=num_epochs * num_steps_per_epoch,
                hooks=[ValidationHook(...)])

It doesn't have any fancy things a ValidationMonitor has like early-stopping and whatnot but this should be a start.

A: There's an undocumented utility called monitors.replace_monitors_with_hooks() which converts monitors to hooks. The method accepts (i) a list which may contain both monitors and hooks and (ii) the Estimator for which the hooks will be used, and then returns a list of hooks by wrapping a SessionRunHook around each Monitor.
from tensorflow.contrib.learn.python.learn import monitors as monitor_lib

clf = tf.estimator.Estimator(...)

list_of_monitors_and_hooks = [tf.contrib.learn.monitors.ValidationMonitor(...)]
hooks = monitor_lib.replace_monitors_with_hooks(list_of_monitors_and_hooks, clf)

This isn't really a true solution to the problem of fully replacing the ValidationMonitor—we're just wrapping it up with a non-deprecated function instead. However, I can say this has worked for me so far in that it maintained all the functionality I need from the ValidationMonitor (i.e. evaluating every n steps, early stopping using a metric, etc.)
One more thing—to use this hook you'll need to update from a tf.contrib.learn.Estimator (which only accepts monitors) to the more full-fledged and official tf.estimator.Estimator (which only accepts hooks). So, you should instantiate your classifier as a tf.estimator.DNNClassifier, and train using its method train() instead (which is just a re-naming of fit()):
clf = tf.estimator.Estimator(...)

...

clf.train(
    input_fn=...
    ...
    hooks=hooks)

A: https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#train
https://www.tensorflow.org/api_docs/python/tf/train/CheckpointSaverListener
I use the checkpoint save listener to monitor the training, the estimator you use likely to have a parameter called saving_listeners. It gets called every time a checkpoint is created and that is a parameter you can set in the config of your estimator. So the hook is:
class ValidationListener(tf.train.CheckpointSaverListener):
    def __init__(self, estimator, input_fn):
        self._estimator = estimator
        self._input_fn = input_fn
        self._evaluation_loss = 9999

    def after_save(self, run_context, run_values):
        print("--- done writing checkpoint. ---")
        evaluation = self._estimator.evaluate(input_fn=self._input_fn)
        print(evaluation)
        if evaluation['loss'] < self._evaluation_loss:
            self._evaluation_loss = evaluation['loss']
        else:
            return True # Stop Training

When Training:
early_stopping = tf.contrib.estimator.stop_if_no_decrease_hook(
    hard_estimator,
    metric_name='loss',
    max_steps_without_decrease=500,
    min_steps=100)

monitor_validation = ValidationListener(estimator=hard_estimator, input_fn=hard_validation_input_fn)

hard_estimator.train(
    input_fn = train_input_fn,
    hooks=[early_stopping],
    steps=1000,
    saving_listeners=[monitor_validation]
)

Hope this helps.

A: Since you want to validate the training after every n_steps, tf will use the latest saved checkpoint. You can use a custom CheckpointSaverListener class to add the evaluation step after the checkpoint is saved using CheckpointSaverHook.
Pass the model classifier object and evaluation input function to the class
Reference https://www.tensorflow.org/api_docs/python/tf/train/CheckpointSaverListener
class ExampleCheckpointSaverListener(CheckpointSaverListener):
  def __init(self):
    self.classifier = classifier
    self.eval_input_fn = eval_input_fn

  def begin(self):
    # You can add ops to the graph here.
    print('Starting the session.')
    self.your_tensor = ...

  def before_save(self, session, global_step_value):
    print('About to write a checkpoint')
    eval_op = self.classifier.evaluate(input_fn=self.eval_input_fn)
    print(eval_op)

  def after_save(self, session, global_step_value):
    print('Done writing checkpoint.')

  def end(self, session, global_step_value):
    print('Done with the session.')

...
listener = ExampleCheckpointSaverListener(Myclassifier, eval_input_fn )
saver_hook = tf.train.CheckpointSaverHook(
    checkpoint_dir, listeners=[listener])
with tf.train.MonitoredTrainingSession(chief_only_hooks=[saver_hook]):


text:
Q: Setting user_version in sqlite I have seen other questions on here about reading the user_version, and that seems to be working fine for me.  However I'm trying to use sqlite in FMDB to set my version number and it isn't setting.
_db = [self openDatabase];
[_db executeUpdate:[StudentController creationString]];
[_db executeUpdate:[ReadingController creationString]];
[_db executeUpdate:[SessionController creationString]];
NSLog(@"User version is %i", userVersion);
NSString *query = [NSString stringWithFormat:@"PRAGMA USER_VERSION = %i", userVersion];
[_db executeQuery:query];

the output I get is:
2014-01-16 22:16:25.438 MyApp[2810:1c103] User version is 2
2014-01-16 22:16:25.439 MyApp[2810:1c103] Query is PRAGMA USER_VERSION = 2
2014-01-16 22:18:09.272 MyApp[2810:1c103] Database copied and created

and after running the app for a bit, with the database saving and loading just fine, I restart the app and read the version number and I call this to check the version number:
FMResultSet *ps = [_db executeQuery:@"PRAGMA USER_VERSION"];

NSDictionary *results = [[NSDictionary alloc] init];
while ([ps next]) {
     results = [NSDictionary dictionaryWithDictionary:[ps resultDictionary]];
}

and results is a nicely formed dictionary:
(lldb) po results
$0 = 0x09bf5770 {
    "user_version" = 0;
}
(lldb)

I would like to know: why is the user version number is not setting for me?

A: If you need to set PRAGMA user_version use:
[self.db setUserVersion:yourUserVersion]; // yourUserVersion is of uint32_t type

To read current user_version user
[self.db userVersion];                   // returned value is of uint32_t type

FMDB encapsulate it since 2013 so you don't have to deal with it yourself.
Documentation:
http://ccgus.github.io/fmdb/html/Categories/FMDatabase+FMDatabaseAdditions.html
PS: @HalR I think you can accept my answer as is it probably more useful for visitor searching for "how to set user_version PRAGMA" and it also solves your problem with neater solution as well.

A: I was about to post a bounty when I figured out the issue.  And as often happens, I was just being a bonehead
I was doing executeQuery where I should have been doing executeUpdate
_db = [self openDatabase];
[_db executeUpdate:[StudentController creationString]];
[_db executeUpdate:[ReadingController creationString]];
[_db executeUpdate:[SessionController creationString]];
NSLog(@"User version is %i", userVersion);
NSString *query = [NSString stringWithFormat:@"PRAGMA USER_VERSION = %i", userVersion];
[_db executeQuery:query];

should instead be:
_db = [self openDatabase];
[_db executeUpdate:[StudentController creationString]];
[_db executeUpdate:[ReadingController creationString]];
[_db executeUpdate:[SessionController creationString]];
NSLog(@"User version is %i", userVersion);
NSString *query = [NSString stringWithFormat:@"PRAGMA USER_VERSION = %i", userVersion];
[_db executeUpdate:query];

executing a Pragma is NOT a query, executeQuery doesn't do anything with it.  It is instead in the same category as UPDATE, INSERT, and DELETE.


text:
Q: Android: Trying to compile native code, getting UnsatisfiedLinkError: No implementation found I am trying to fork AndroidPdfViewer to replace its underlying library from PdfiumAndroid to android-pdfium.
My problem is, when I load AndroidPdfViewer and PdfiumAndroid in Android Studio, I can't get the project to work, even before changing anything.
The problem is PdfiumAndroid has JNI code that define many previously declared functions, but the linker can't link the definitions in C++ to the declarations in Java. The error message has two errors:
E/barteksc.sample: No implementation found for long com.shockwave.pdfium.PdfiumCore.nativeOpenDocument(int, java.lang.String) (tried Java_com_shockwave_pdfium_PdfiumCore_nativeOpenDocument and Java_com_shockwave_pdfium_PdfiumCore_nativeOpenDocument__ILjava_lang_String_2)
E/PDFView: load pdf error
    java.lang.UnsatisfiedLinkError: No implementation found for long com.shockwave.pdfium.PdfiumCore.nativeOpenDocument(int, java.lang.String) (tried Java_com_shockwave_pdfium_PdfiumCore_nativeOpenDocument and Java_com_shockwave_pdfium_PdfiumCore_nativeOpenDocument__ILjava_lang_String_2)
        at com.shockwave.pdfium.PdfiumCore.nativeOpenDocument(Native Method)
        at com.shockwave.pdfium.PdfiumCore.newDocument(PdfiumCore.java:135)

Here is the gradle file. It looks like there is something missing, although these are the original files before any modifications.
I tried to add this to proguard-rules.pro
-keep class com.shockwave.** { *; }

it removed the first error, but the second is still there.

A: Solved it.
If anyone is having the same issue, I did the following to solve it:

*

*Installed android-ndk tools

*Edited Application.mk file to remove mips and mips64 since they are not supported anymore, and updated android version to 19 since it's the minimum right now.

*run ndk-build in the jni folder / directory.

That created what I was said about in my question

It looks like there is something missing

That created a libs folder that has the necessary definitions for the linker.


text:
Q: Hiding all Leaf Nodes while Showing Child Nodes on an ASP.Net Tree View In my website, I have a TreeView that has this structure:

Root
|-Leaf
|-Parent
|--Leaf
|--Leaf
|--Child
|---Leaf
|---Leaf
|--Child
|---Leaf
|---Leaf

Is it possible to make the tree in a "collapsed" state where all the Leaf nodes and ONLY leaf nodes are hidden from view until its parent node is expanded? The ideal solution would be to do this without a postback, but any solution at this time would be helpful.
The "collapsed" view would look like this:

Root
|-Parent
|--Child
|--Child

Expanding the Root, Parent or Child nodes should show their Leaf nodes. Collapsing the node should re-hide its leaf nodes, but leave the child nodes visible.

A: Here's a server-side (untested) solution:
TreeNodeCollection nodes = TreeView1.Nodes;
foreach (node in nodes)
{
   if (node.ChildNodes.Count == 0)
   {
      node.Parent().Collapse();
   }
}

A client-side solution is definitely a preferred option.


text:
Q: How can I stream an audio recording realtime in ionic to Firebase? I'm trying to implement realtime speech to text recognition with Google API service using Ionic as a frontend. I am not able to find a library that can record from Ionic and stream the recording in realtime to be stored in the google bucket storage. Do you have any suggestions?

A: I don't think you need to use any special library/plugin to do this, you can simply use Web Technologies to achieve this by using MediaDevices API to getUserMedia for getting Audio stream from device microphone and using Web Speech API for speech recognition, and use WebSocket to transmit real-time audio stream to Google Speech-to-Text API and receive real-time response back.
For further reading, check the following resources:
Delivering a Smooth Cross-Browser Speech to Text Experience
Speaking with a Webpage - Streaming speech transcripts

A: Assuming that you want to use the React Native framework. You can checkout Media plugin from the Ionic framework that can be used to record the audio files. Here is an example(which is developed using angular, but you can understand the underlying concept). Also for using Firebase to stream in real-time, check out the firebase plugin.
There are Streaming media plugin, which can also be used in your case.
For more reference, I would suggest using the official documentation and look into this blog post


text:
Q: Extending CatalogProduct model (the Item table) I want to extend the CatalogProduct model with my own model. I followed the CartModule example on GitHub. I think I did all the parts that the example had, but I still couldn't get it working.
Here are the items that I did:

*

*Installed the VirtoCommerce.CatalogModule.Data from NuGet to the module that I created.

*Created a MyProduct class, which inherit the CatalogProduct class.

*Created MyProductEntity class, which inherit the ItemEntity, and I override the ToModel, FromModel, and Patch functions.

*Created MyProductRepositoty class, which inherits the CatalogRepositoryImpl, and override the OnModelCreating function to tell which table I want to map to.

*Modified the Module.cs file, and implemented the SetupDatabase(), Initialize(), and PostInitialize().

*Here is what I put in for Initialize()
_container.RegisterType<ICatalogRepository>(new InjectionFactory(c => new MyProductRepository(_connectionStringName, _container.Resolve<AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor())));

*Here is what I put in for PostInitialize()
AbstractTypeFactory<CatalogProduct>.OverrideType<CatalogProduct, MyProduct>();
AbstractTypeFactory<ItemEntity>.OverrideType<ItemEntity, MyProductEntity>();

*Rebuilt my module, and restarted the IIS

*I hit the localhost/admin/docs/VirtoCommerce.Catalog/v1 to see if the fields that I add to my model return from the Product definitions. It didn't.

Are there some steps I am missing? I actually got the migration working. It actually created the "MyProduct" table in the database.
Another question is that is it a good idea to add columns to the existing "Item" table? or is it advised to create a new table when extending the domain model?
Thank you all in advanced!

A: The reason why you could not see changes in API is that besides domain model Catalog module also uses web model - e.g. for Product, and API controllers return these web model objects. That's the difference with Cart module in example.
In order to see the changes, you need to use your extended type for web model and extend converter.
As you can see, catalog module extensions not so straightforward in vc-platform 2x version. This will be mitigated in 3x (NET Core) platform version by eliminating web model.
Easier built-in way of extending Catalog objects functionality in platform 2x is by using dynamic properties (in UI, by code).

Another question is that is it a good idea to add columns to the
  existing "Item" table? or is it advised to create a new table when
  extending the domain model?

Recommended way is to create new table.


text:
Q: cURL retrieving CSV file My hosting company must have changed their server or something, I've had this code running flawlessly for 8-10 years..YEARS!.. and today its stopped. Im wondering if the use of cURL today has changed much from when I wrote this 8-10 years ago.. please help. It grabs the csv and continues for a very very long time to get the file.. i exit the browser after 20 mins.. should and used to only take maybe 25 seconds tops. The first line below was also an issue.. somehow on any other server it showed the correct 3 months back date.. on my server my sites hosted on.. it shows 1969.. so at first I assumed the date trying to get data from 1969 was the lagg/holdup.. but when I fixed this to new code it still lags.
//$newdates = date("Ymd",strtotime(date('Ymj')) - (60 * 24 * 60 * 60));
// the above for some reason doesnt work anymore gives the 1969 date.. so below fixed

$newdates = date("Ymd", strtotime("-3 months"));
$tm = "http://123.theserver.net/data/sel_data=*&query_str=lud>'$newdates'&dl_type=file&send_done=no&e=.csv";
$ch = curl_init($tm);
$fp = fopen("/home/sites/www.mydomain.com/mx/data.csv", 'w');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

Kinda frusterated cause the hosting co says they havent changed anything..and there 2000 miles away,  so is there newer updated code Im missing here?
Thanks so much!!

A: Try:
$newdates = date("Ymd", strtotime("-3 months"));
$url_init = "http://123.theserver.net/data/sel_data=*&query_str=lud>'$newdates'&dl_type=file&send_done=no&e=.csv";

$ch = curl_init($url_init);

    if (!$ch) die ("Curl not loaded");

$fp = fopen("/home/sites/www.mydomain.com/mx/data.csv", 'w');

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

if( ! $tmp = curl_exec($ch))
{
   echo curl_error($ch);
}

else
{

header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$start.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $tmp;
}
curl_close($ch);

A: *

*Check that the URL is being formed correctly.

*Make sure that the remote server is not the one taking forever.

*Check the load averages on your server. It could be a very slow write due to a severe IO bottleneck.

Also, never ever ever say something to your host like "my code worked fine for X years before and now it's broken so it's your fault" because that is the exact moment when we stop giving a sh*t. Your code is probably not the problem in this particular case, but so many people lob this excuse at us and the fact is that sh*t code can work for years until it hits the asymptote of its efficiency graph and there are just so many levels of not caring... their job is to make sure that the server is working, they don't get paid to debug your code for you.
What you should be doing is investigating the problem to the best of you abilities, including your findings and supporting evidence in the support ticket, and never once implying that the server ops "must have changed something".