text:
Q: Explain why "-" is not a "-" I was writing an automation script in python that dealt with sending commands through a Telnet session. For some reason I couldn't get it to work. After a ton of frustrating debugging, I found that when I was translating a command of:
"ulimit -s 1024"

The - in the command became something weird in utf-8. I had to translate it in bytes because I was sending it using Telnet (I know I should use ssh, but it honestly is fine in my case) and I realized it was weird because when I printed the command in bytes it would be:
b"ulimit \x##\x##\x##s 1024"

I don't remember the exact numbers, but I fixed it by copying and pasting a new "-" that I used two lines up in the function and worked fine.
I did copy and paste in the part from two lines up, but I typed the ulimit -s part. I was also using IDLE
Anyone know what happened?

A: You managed to enter something like an U+2013 EN DASH or an U+2014 EM DASH, which both look a lot like the ASCII character U+002D HYPHEN MINUS.
Because either of these characters are outside of the basic Latin-1 alphabet, encoding either one of these to UTF-8 results in a 3-byte sequence:
>>> print('\u2013')
–
>>> print('\u2013'.encode('utf8'))
b'\xe2\x80\x93'
>>> print('\u2014')
—
>>> print('\u2014'.encode('utf8'))
b'\xe2\x80\x94'

Those two are not the only confusable characters; a few more:

*

*U+2010 HYPHEN ‐ (UTF8: E2 80 90)

*U+2011 NON-BREAKING HYPHEN ‑ (UTF8: E2 80 91)

*U+2012 FIGURE DASH ‒ (UTF8: E2 80 92)

*U+FE58 SMALL EM DASH ﹘ (UTF8: EF B9 98)

*U+FE63 SMALL HYPHEN-MINUS ﹣ (UTF8: EF B9 A3)

etc.

A:
Anyone know what happened?

I can see two possibilities here. One is that you inadvertently copy-pasted a line of code from a Web page or other document where the - had been replaced by an emdash (it usually happens to me with quote signs and typographic quote signs), which looks like a minus sign but it's a UTF8 multibyte sequence.
The other is that somehow the IDLE editor effected a "spelling check" like that of Microsoft Word, which replaces (among others) quote signs with typographic quote signs, three consecutive dots with an ellipsis and minus signs with emdashes. This might have been triggered by some rare keystroke combination typed in error (for example I sometimes trigger the Windows 7 Screen Magnifier while trying to type in, I think, a { symbol - which on my keyboard is Shift AltGr [).


text:
Q: Returning vector from template function Hoping for some clarification here. The code below executes fine, but when I uncomment that else statement a compilation error occurs. It's because in main I'm specifying a type int event though there's the possibility of type string. I've simplified my actual code to what's below to narrow down on the problem, what can I do to make it so that vector data in main can be of whatever type getNextLineOfData returns?
#include <vector>
using namespace std;

template< typename T>
std::vector<T> getNextLineOfData(bool someBoolean)
    {
        std::vector<T> data;
        if (someBoolean)
        {
            data.push_back(1);
            data.push_back(2);
            data.push_back(3);
        }
        /*
        else
        {
            data.push_back("1");
            data.push_back("2");
            data.push_back("3");
        }
        */
return data;
    };

int main()
{
vector<int> data = getNextLineOfData<int>(true);
return 0;
}

A: You are confusing compile time operations with runtime operations in your code snippet. When you template the function getNextLineOfData and instantiate it with getNextLineOfData<int>, the compiler goes ahead and generates a function that returns a vector for you. The if statement however is only evaluated at run time. So when the compiler tries to build your code it sees that you are adding both 1 and "1" to your vector<int> container based on the conditional. This is not allowed.
You could solve your problem with template specialization.
#include <vector>

using namespace std;

template<typename T>
std::vector<T> getNextLineOfData() {
  // default
}

template<>
std::vector<int> getNextLineOfData()
    {
        std::vector<int> data;

            data.push_back(1);
            data.push_back(2);
            data.push_back(3);

            return data;
    };

template<>
std::vector<std::string> getNextLineOfData()
    {
        std::vector<std::string> data;

            data.push_back("1");
            data.push_back("2");
            data.push_back("3");

            return data;
    };
int main()
{
    vector<int> data = getNextLineOfData<int>();
    return 0;
}

EDIT: As @BobTFish points out, it might be better to overload the function rather than template specialize it. The solution above solves the problem the way you had it initially set up.

A: Reading from extra information in comments, I would suggest something like:
void getNextLine(std::vector<std::string>& output)
{
    output.push_back("string data as you please");
}

void getNextLine(std::vector<int>& output)
{
    output.push_back(1);
}

bool nextLineIsIntData()
{
    // somehow determine if the coming data is strings or ints
    return false;
}

int main()
{
    std::vector<std::string> stringData;
    std::vector<int> intData;
    if (nextLineIsIntData())
        getNextLine(intData);
    else
        getNextLine(stringData);
    // do whatever you want
}

A: Well what you are doing is simply illegal. When you look at the if-else statement you say, well if some condition is true than this will execute but this won't, so it stands too reason that the compiler will ignore the part that is not executed. This is flat out wrong. What you need to do, which is layed out in previous answers is too overload or specialize the function for the different data types.
I should also mention that what you are trying to do is bad style. You are essentially relying on the user too pass the correct bool value, which influences the types you push_back() into the vector. Why do this when you have the power of template pattern matching at your disposal which completely removes the need to rely on correct user input.
In this case and any similar ones you come across it's much better to let the compiler decide

redpajama_set_name: RedPajamaStackExchange


text:
Q: (Unity C#) NPC Movement Script + Animations Not Running Smoothly I have created a NPC that follows the main player. When the player is in a certain range of the NPC, the NPC is supposed to walk, run, and attack based on the distance between the player and the NPC.The NPC has a C# MutantMovement Script attached, which also contains Animations. The NPC is also a NavMesh Agent. My problem is that the Animations do not run smoothly with the logic. I hope someone can help. Below is the MutantMovement Script and the Animation Controller.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

[RequireComponent (typeof (NavMeshAgent))]
[RequireComponent (typeof (Animator))]
public class MutantMovement : MonoBehaviour {
    [SerializeField] private float _range = 10f;
    public Transform _goal; // destination
    public Transform _player;
    private Animator _anim;
    private bool _alive;
    private float _distance;
    private NavMeshAgent _agent;

    void Start ()
    {
        _goal = GameObject.Find("Player").transform;
        _player = GameObject.Find("Player").transform;
        _alive = true;
        // get a reference to the NavMesh Agent component
        _agent = GetComponent<NavMeshAgent>();
        _anim = GetComponent<Animator>();
    }

    void Update()
    {

        Vector3 direction = _goal.position - this.transform.position;
        float angle = Vector3.Angle(direction, this.transform.forward);
        if(Vector3.Distance(_goal.position, this.transform.position) < 10 &&
angle < 50){

            _anim.SetBool("isIdle", false);
            if ((_alive && direction.magnitude > 5))
            {
                _agent.destination = _goal.position;
                _anim.SetBool("isWalking", true);
                _anim.SetBool("isAttacking", false);
                _anim.SetBool("isRunning", false);
                if((_alive && direction.magnitude > 6.5)){
                    _agent.destination = _goal.position;
                    _anim.SetBool("isRunning", true);
                    _anim.SetBool("isWalking", false);
                    _anim.SetBool("isAttacking", false);
                }
            }
            else{
                _agent.isStopped = false;
                _anim.SetBool("isAttacking", true);
                _anim.SetBool("isWalking", false);
                _anim.SetBool("isRunning", false);
            }
        }else{
            _anim.SetBool("isIdle", true);
            _anim.SetBool("isWalking", false);
            _anim.SetBool("isAttacking", false);
        }
    }
    public void SetAlive(bool alive)
    {
        _alive = alive;
    }
}

Animation Controller

A: I would use Animator triggers rather than booleans in your particular case, so the transitions from one animation to another are triggered only once.
In your state machine, you can then set the transitions so :
walking or attacking ---[trigger run]----> running animation
running or walking -----[trigger attack]---> attack animation
running or attacking ----[trigger walk] ---> walking animation

It makes it overall easier as you don't have to turn the other bools to false when triggering a new animation state.
Another thing you can check to make sure the transitions are fluid, is to have a look at the exit time of your animations - if you turn "Has Exit Time" off, your transitions will be instant. You can find this option if you open your animator controller and click on your state machine transition arrow.


text:
Q: How to draw a curved cone 3D with rotating sections I try to draw a curved cone 3D with the top and bottom sections are rotated 45 and -45. It seems not working since each edge does not connected to each other. Here is the code:
\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{tikz-3dplot}
\begin{document}
\tdplotsetmaincoords{20}{0}
\begin{tikzpicture}[tdplot_main_coords,declare
function={r1=2;r2=1.25;h=10;curvature=5;bd=0;}]

\path[fill=gray!50] plot[variable=\x,samples at={0,60,...,300},rotate around={-45:(0,0,0)}]
({r1*cos(\x)},0,{r1*sin(\x)});

\draw[thick,dashed] plot[variable=\x,samples at={0,60,120,180},rotate around={-45:(0,0,0)}]
({r1*cos(\x)},0,{r1*sin(\x)});

\draw[thick] plot[variable=\x,samples at={180,240,300,0},rotate around={-45:(0,0,0)}]
({r1*cos(\x)},0,{r1*sin(\x)});

\foreach \X in {60,120,...,360}
{\draw[thick] \ifnum \X<180 [dashed] \fi
    plot[variable=\x,domain=r2:r1]
    ({\x*cos(\X)-curvature*(\x-r1)*(\x-r2)*cos(bd)},{-h*(\x-r1)/(r1-r2)},
    {\x*sin(\X)-curvature*(\x-r1)*(\x-r2)*sin(bd)});}

\path[fill=gray!25,fill opacity=0.8,] plot[variable=\x,samples at={0,60,...,300},rotate around={45:(0,h,0)}]
({r2*cos(\x)},h,{r2*sin(\x)});
\draw[thick] plot[variable=\x,samples at={0,60,120,180},rotate around={45:(0,h,0)}]
({r2*cos(\x)},h,{r2*sin(\x)});
\draw[thick] plot[variable=\x,samples at={180,240,300,0},rotate around={45:(0,h,0)}]
({r2*cos(\x)},h,{r2*sin(\x)});

\end{tikzpicture}
\end{document}

A: It would be great if you disclose the source of your code. The above code was written for a specific task, for which it works. Here you need a slightly different approach.
\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{tikz-3dplot}
\usetikzlibrary{backgrounds}
\begin{document}
\tdplotsetmaincoords{20}{0}
\begin{tikzpicture}[tdplot_main_coords,declare
function={r1=2;r2=1.25;h=10;curvature=5;bd=0;rot=0.125;}]

\foreach \X [count=\Y] in {60,120,...,360}
{\draw[thick] \ifnum \X<180 [dashed] \fi
    plot[variable=\x,domain=r2:r1]
    ({\x*cos(\X)-curvature*(\x-r1)*(\x-r2)*cos(bd)},{h*(1+rot*cos(\X))*(\x-(r1+r2)/2)/(r2-r1)},
    {\x*sin(\X)-curvature*(\x-r1)*(\x-r2)*sin(bd)})
    coordinate (b-\Y)
    ({r2*cos(\X)-curvature*(r2-r1)*(r2-r2)*cos(bd)},{h*(1+rot*cos(\X))*(r2-(r1+r2)/2)/(r2-r1)},
    {r2*sin(\X)-curvature*(r2-r1)*(r2-r2)*sin(bd)}) coordinate (t-\Y);}

\begin{scope}[on background layer]
 \path[fill=gray!50] plot[variable=\x,samples at={1,...,6}]  (b-\x);
 \draw[thick,dashed] plot[variable=\x,samples at={6,1,2,3}]  (b-\x);
 \draw[thick] plot[variable=\x,samples at={3,4,5,6}]  (b-\x);
\end{scope}

\path[fill=gray!25,fill opacity=0.8,] plot[variable=\x,samples at={1,...,6}] (t-\x);
\draw[thick] plot[variable=\x,samples at={1,...,6,1}]  (t-\x);
\end{tikzpicture}
\end{document}


text:
Q: Getting the column names of the selected row in SQL? I have a program with 2 forms and both forms have their own grid. Grid1 is on form1, Grid2 is on form2. I want Grid2 to serve as a pop up window which is used for editing. When a user doubleclicks a row on Grid1, it should do a requery on just that row and display that single row on Grid2. I can't figure out how to get the column names of the selectedrow then do a query on it's unique identifers. What I have so far:
(This is on form1 by the way)
 Public Sub dgvForm1_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvForm1.CellDoubleClick

Dim i As Integer = 0
Dim rowIndex As Integer
Dim cellName as string

While dgvForm1.SelectedRows.Item(0).Cells(i).ColumnIndex < dgvForm1.ColumnCount

      rowIndex = dgvForm1.SelectedRows.Item(0).HeaderCell.RowIndex
      cellName = dgvForm1.SelectedRows.Item(0).HeaderCell.toString
      Select Case cellName
             Case "control_no"
                 Dim sControlNum = cellName.ToString
             Case "store_id"
                 Dim sStoreNum = cellName.ToString
      End Select

      i = i + 1
End While
end sub

I simply just want the user to doubleclick a row that is displayed on a datagridview with many other records, and that triggers a doubleclick event. This would then loop through the selectedrow's column names until it finds both control_id and store_id and gets their values. P.s. I tried google for a good hour or so but I had a hard time getting any techniques to work.
UPDATE:
   I should probably add, this is a bound datagrid that uses sqlClient and its dataadapter/dataset method.

A: myTable.Columns.ColumnName.
Read more at http://msdn.microsoft.com/en-us/library/system.data.datacolumn.columnname.aspx


text:
Q: Logging console history with errors in R or Rstudio For educational purposes we are logging all commands that students type in the rstudio console during labs. In addition we would like to store if call was successful or raised an error, to identify students which struggling to get the syntax right.
The best I can come up with is something like this:
options(error = function(){
  timestamp("USER ERROR", quiet = TRUE)
})

This adds an ## ERROR comment on the history log when an exception occurs. Thereby we could analyze history files to see which commands were followed by an ## ERROR comment.
However R's internal history system is not well suited for logging because it is in-memory, limited size and needs to be stored manually with savehistory(). Also I would prefer to store log one-line-per-call, i.e. escape linebreaks for multi-line commands.
Is there perhaps a hook or in the R or RStudio console for logging actual executed commands? That would allow me to insert each evaluated expression (and error) in a database along with a username and timestamp.

A: A possible solution would be to use addTaskCallback or the taskCallbackManager with a function that writes each top-level command to your database. The callback will only fire on the successful completion of a command, so you would still need to call a logging function on an error.
# error handler
logErr <- function() {
  # turn logging callback off while we process errors separately
  tcbm$suspend(TRUE)
  # turn them back on when we're done
  on.exit(tcbm$suspend(FALSE))
  sc <- sys.calls()
  sclen <- length(sc)  # last call is this function call
  if(sclen > 1L) {
    cat("myError:\n", do.call(paste, c(lapply(sc[-sclen], deparse), sep="\n")), "\n")
  } else {
    # syntax error, so no call stack
    # show the last line entered
    # (this won't be helpful if it's a parse error in a function)
    file1 <- tempfile("Rrawhist")
    savehistory(file1)
    rawhist <- readLines(file1)
    unlink(file1)
    cat("myError:\n", rawhist[length(rawhist)], "\n")
  }
}
options(error=logErr)
# top-level callback handler
log <- function(expr, value, ok, visible) {
  cat(deparse(expr), "\n")
  TRUE
}
tcbm <- taskCallbackManager()
tcbm$add(log, name = "log")

This isn't a complete solution, but I hope it gives you enough to get started. Here's an example of what the output looks like.
> f <- function() stop("error")
f <- function() stop("error")
> hi
Error: object 'hi' not found
myError:
 hi
> f()
Error in f() : error
myError:
 f()
stop("error")


text:
Q: iPhone - recognizing a wave form/frequency I capture a sound using my App. Suppose this sound is a sinusoidal 1 KHz sound and there is a background sound present. How do I identify that this 1 KHz sound is present on the sound?
I mean, I can imagine how elements can be found in images, as for example, if you are looking for a yellow square on an image, all you have to do is to specify the color you want, give it a certain tolerance, and look for a group of pixels that have that color and form a square shape. But what about sounds? How do you identify a wave form and frequency when all you get is an amplitude value that represents 1/44.000 of the wave form in one second?
I don't want the code, as this is too complex for this post, but if you guys can point me on the right direction of how this is done, free source codes that can exemplify the techniques or the math behind it, I appreciate. Thanks

A: You just need to do a FFT (Fast Fourrier Transform) of the wave to have the frequencies it is composed of. This is a classic task in signal processing (Fourrier Transforms are transformations to switch between time and frequency spaces) so you should find a lot of resources on the subject.
Maybe look at the CoreAudio framework and sample codes too.
(See also CoreAudio overview and the Audio and Video topics in Apple's doc)


text:
Q: How to access Google Cloud SQL from domain's user account via google Apps Script Admin of a domain created a Google Cloud SQL instance....Now a user of that domain wants to access Google Cloud SQL via google Apps Script, but he is not able to access....
When I run this code from admin account it works :
var conn = Jdbc.getCloudSqlConnection("jdbc:google:rdbms://"+instance_name+"/"+database_name,"root","");
but when i run this code from a domain user then it gives this error :
Failed to establish a database connection. Check connection string, username and password.

A: Does that user have access to the database ? see doc here.   Or you can also provide userName and password as advanced arguments in parameters


text:
Q: Perform wildcard searches with multiple columns in one parameter using dynamic SQL My application has only street number & street name fields. I need to declare street name & unit type as one parameter field in my query. I need to perform wildcard searches (on street name field) by any value and return the following results.
Possible searches:
Street Number: 1234
Street Name:
OR
Street Number: 1234
Street Name: Lakeshore SE
OR
Street Number:
Street Name: SE
OR
Street Number:
Street Name: Lake DR SE

Here is the table results:
+-----------------------------------+-------------------+-----------+
|               STREET_NUMBER       |    STREET_NAME    | UNIT_TYPE |
+-----------------------------------+-------------------+-----------+
|                   1234            |    LAKESHORE DR   |    SE     |
+-----------------------------------+-------------------+-----------+

Here is my stored proc:
@Street varchar (100) = NULL
,@StreetNumber varchar (100) = NULL

AS
BEGIN
SET NOCOUNT ON;

DECLARE @sql nvarchar(max) = N'
SELECT *
FROM ADDRESS_DETAIL
WHERE 1 = 1'

    + CASE WHEN @Street IS NOT NULL THEN
    N' AND STREET_NAME + UNIT_TYPE LIKE ''%'' + @Street + ''%'''  ELSE N'' END
    + CASE WHEN @StreetNumber IS NOT NULL THEN
    N' AND STREET_NUMBER LIKE @StreetNumber' ELSE N'' END

DECLARE @params nvarchar(max) = N'
@Street varchar (60)
,@StreetNumber varchar (60)';

PRINT @sql;

EXEC sys.sp_executesql @sql, @params,
@Street,
@StreetNumber;

END

A: Major kudos for parameterizing your dynamic sql. That is not something I see most people do. But I don't think you need dynamic sql here. I am a little concerned about your leading wildcards here because it renders the query non-sargable. But that is true with dynamic sql or not.
Here is another way to write this procedure that might be a bit simpler.
create procedure YourProc
(
    @Street varchar (100) = NULL
    ,@StreetNumber varchar (100) = NULL
) AS
BEGIN
    SET NOCOUNT ON;

    SELECT *
    FROM ADDRESS_DETAIL
    WHERE
    (
        STREET_NAME + UNIT_TYPE LIKE '%' + @Street + '%'
        OR
        @Street IS NULL
    )
    AND
    (
        STREET_NUMBER LIKE '%' + @StreetNumber + '%'
        OR
        @StreetNumber IS NULL
    )
END

My guess is you need to change the first predicate to something like this.
@Street like '%' + STREET_NAME + '%' + UNIT_TYPE + '%'

Another thought...you could replace all your spaces with the wildcard to eliminate multiple spaces causing you issues.
where STREET_NAME + UNIT_TYPE like replace('@STREET', ' ', '%')


text:
Q: Create a row per 15 minute interval between two dates in a MySQL table I have a table that contains a column with datetime data type. I would like to write a MySQL query which populates the table with a row for each 15 minute interval between two dates (e.g. 2017-01-01 00:00:00 and 2017-06-30 23:45:00).
The purpose of this table is to be able to store a number for each interval like this:
Time interval | Forecast
2017-01-01 00:00:00 | 528
2017-01-01 00:15:00 | 492
2017-01-01 00:30:00 | 474
2017-01-01 00:45:00 | 482
2017-01-01 01:00:00 | 456
2017-01-01 01:15:00 | 421
2017-01-01 01:30:00 | 375
2017-01-01 01:45:00 | 322
What would be the easiest way of achieving this?
Also, there will be some intervals with no forecast (probably about 30% of them will be 0), should I avoid creating that row at all and at a later point write a query that returns 0 if the interval does not exist in the table?


text:
Q: Why is my InfoPath 2010 form having styling issues? The form loads well into SharePoint and looks proper in Chrome and Firefox but for some reason my font styles are not applying and my input field settings aren't taking affect in IE 7 and 8.
Very frustrating, especially because there's no where to check the code to see if there's some stray tags that should have been cleared out.
Anybody run into this before?
Whats the best method to clean it up?

A: problem solved. it was a stylesheet issue. the stylesheet was being loaded in twice for some reason. This created this bizarre conflict.


text:
Q: how to add success key in web api json array C# web api 2 [Route("api/GetMenuBykidnew")]
        [HttpGet]
        public IHttpActionResult GetMenuBykidnew(int kid, string Username)
        {
        ApiBusiness ApiBus = new ApiBusiness();

        var result = ApiBus.GetKitchenMenubyKitchennew(kid, Username);
        return result;

    }

[
    {
        "CartId": 1016,
        "OrderId": 124,
        "Username": "7887878787",
        "KitchenId": null,
        "CartAddedDate": "2020-01-21T00:00:00",
        "MenuId": 2055,
        "MenuName": "Veg Fried Rice",
        "MenuVariantId": 2055,
        "Rate": 91,
        "Quantity": 4,
        "ListPrice": 91,
        "ListGST": 4.55,
        "ListPacking": 5,
        "TotalPrice": 100.55,
        "MenuStatus": 0
    }
]
Expected result
success:[
    {
        "CartId": 1016,
        "OrderId": 124,
        "Username": "8892696780",
        "KitchenId": null,
        "CartAddedDate": "2020-01-21T00:00:00",
        "MenuId": 2055,
        "MenuName": "Veg Fried Rice",
        "MenuVariantId": 2055,
        "Rate": 91,
        "Quantity": 4,
        "ListPrice": 91,
        "ListGST": 4.55,
        "ListPacking": 5,
        "TotalPrice": 100.55,
        "MenuStatus": 0
    }
]


text:
Q: Tesseract make training missing ground truth for training I'm trying to train Tesseract with image and i found this https://github.com/tesseract-ocr/tesstrain
I've followed the instructions on how to train images but I keep on getting this error
Tesseract Open Source OCR Engine v5.0.0-alpha-635-g90405 with Leptonica
Page 1
Warning: Invalid resolution 0 dpi. Using 70 instead.
find data/foo-ground-truth -name '*.lstmf' | python3 shuffle.py 0 > "data/foo/all-lstmf"
Error: missing ground truth for training
Makefile:147: recipe for target 'data/foo/list.train' failed
make: *** [data/foo/list.train] Error 1

It keeps on showing this error Error: missing ground truth for training
command i used make training
the image and ground truth text are from the same repo ocrd-testset.zip
what could possibly the solution to fix this?
EDIT:
Sorry forgot to mention that I only used 1 pair of training image from the ocrd-testset.zip

A: I followed the instructions in https://github.com/tesseract-ocr/tesstrain on Windows10.
It keeps on showing this error Error: missing ground truth for training at first. It because the code don't work on Windows:

    (ALL_LSTMF): $(patsubst %.gt.txt,%.lstmf,$(shell find $(GROUND_TRUTH_DIR) -name '*.gt.txt'))
            @mkdir -p $(OUTPUT_DIR)
            find $(GROUND_TRUTH_DIR) -name '*.lstmf' | python3 shuffle.py $(RANDOM_SEED) > "$@"

and I change it to :
    $(ALL_LSTMF): $(patsubst %.gt.txt,%.lstmf,$(wildcard $(GROUND_TRUTH_DIR)/*.gt.txt))
        @mkdir -p $(OUTPUT_DIR)
        find $(GROUND_TRUTH_DIR) -name '*.lstmf' -exec echo {} \; | sort -R -o "$@"

Then the error disappeared.
The changed code comes from the old version of tesseract-ocr/tesstrain. It should work on both linux and windows.Maybe you could try it.


text:
Q: How do I add new object or push into array Mongodb Compass NodeJS Express (update is not a function)? At this moment I try to find the query which works in this case, but then want to update the object. So I want to check if review object exist and if not then create that key name first and then push that object into an array. Else push into that in existing object of array.
Default object looks like (without review object):

const mongoose = require('mongoose');

const musicSchema = mongoose.Schema({
    id: {
        type: Number,
        required: true
    },
    artist: {
        type: String,
        required: true
    },
    title: {
        type: String,
        required: true
    },
    release_year: {
        type: Number,
        required: true
    },
    genre_id: {
        type: Number,
        required: true
    },
    image_url: {
        type: String,
        required: true
    },
    reviews: [{
        id: {
            type: Number,
            required: true
        },
        locale: {
            type: String,
            required: true
        },
        rating: {
            type: Number,
            required: true
        },
        comment: {
            type: String,
            required: true
        }
    }]
});

const Music = mongoose.model("Music", musicSchema); // now we have to create our model
console.log;

module.exports = Music;  // export our created model

app.post('/addReview/:id', async (req, res) => {
  let idNumber = parseInt(req.params.id);  // 501437
  let reviewObject = req.body; // {id: "501437", locale: "nl", rating: 3, text: "helello"}
  try {
    const music = client.db('database').collection('music');
    const query = { id: idNumber };
    const musicSong = await music.findOne(query);
    await musicSong.update({ $push: { reviews: reviewObject } }); // error comes from here
  } catch (err) {
    console.log(err);
  }
});

A: *

*check if reviews field is not exists then initialise it to blank array

*push object to reviews

*save() to save main document

app.post('/addReview/:id', async (req, res) => {
  let idNumber = parseInt(req.params.id);  // 501437
  let reviewObject = req.body; // {id: "501437", locale: "nl", rating: 3, text: "helello"}
  try {
    const music = client.db('database').collection('music');
    const query = { id: idNumber };
    let musicSong = await music.findOne(query);
    if (!Array.isArray(musicSong.reviews)) {
      musicSong.reviews = [];
    }
    musicSong.reviews.push(reviewObject);
    music.save();
  } catch (err) {
    console.log(err);
  }
});

Second option using updateOne():
It does not require to find, check and save operations if you use update methods,
app.post('/addReview/:id', async (req, res) => {
  const query = { id: parseInt(req.params.id) };
  let reviewObject = req.body;
  try {
    const music = client.db('database').collection('music');
    await music.updateOne(query, { $push: { reviews: reviewObject } });
  } catch (err) {
    console.log(err);
  }
});


text:
Q: Time complexity of only accessing rows in a matrix while accessing all elements of a matrix we can use to for loops and time complexity is O(n^2).
But, when we are only accessing rows from a 2D array, what is the time complexity? Is it O(n) when n = number of rows?
Ex:-
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < arr.length; i++)
  for (int j = 0; j < arr[0].length; j++)

The time complexity for the above lines is O(n^2).
But if we access the matrix in the following way will the time complexity still be O(n^2) or will it be O(n)
for (int rows[] : arr) - Time complexity is O(n) or O(n^2)

A: If you are going to iterate all cells for each row, so it still be O(n^2).
There is no real difference between those two methods when considering run time.

A: int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < arr.length; i++)
  for (int j = 0; j < arr[0].length; j++)

This is having complexity of O(n) and not O(n^2). That is you are traversing and seeing n items only once and the it linearly increases when n increases.


text:
Q: Using Network Analyst in ArcGIS Desktop? I would like to open up a new settlement with fiberglass and i want to know how much route in meter I need to open up each house in this settlement.
For this purpose I will use the network analyst in ArcGIS.
The problem with this tool is that it always calculates the distance between the settlements entrance and each house.
The point is that there should be one route entering the main street in this settlement and from this main route there should be little routes to each house.
The main route should be only calcuated once and not for every house.
Does anybody have a solution?

A: If you will work extensively with such type of analysis, you might consider looking at geometric networks, they might suit your needs better.
As a workaround, do the following:

*

*After solving the Route, use the GP tool Copy Traversed Source Features. This will export your edges that were traversed.

*In the Edges feature class, delete duplicates (they will have the same SourceOID value). Either use Delete Identical GP tool (Advanced license) or write a custom Python script / build a model (or just Dissolve on the SourceOID field).


text:
Q: The how,what and why of directed angles I recently came to know about directed angles.I felt it was a strong convention but didnt understand much of it i understood the basics but I would like to know more about its applications like if we can use sine rule using directed angles and all.Also I would like to know any lookout to when we even use this convention.
Any help would be appreciated.Thanks in advance.


text:
Q: Can I make grouped bars in plotly polar bar chart? I have a polar bar chart with stacked bars in plotly, which gives me the figure below using the code I've added as well (example found here: Wind Rode Charts):

import plotly.io as pio
pio.renderers.default = 'svg'
#pio.renderers.default = 'browser'

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

df = px.data.wind()

fig = px.bar_polar(df, r="frequency", theta="direction",
                    color="strength", template="ggplot2",
                    color_discrete_sequence= px.colors.sequential.Plasma_r)
fig.show()

fig.update_layout(legend=dict(
    orientation="h",
    yanchor="top",
    y=-0.2,
    xanchor="center",
    x=0.5),
    polar=dict(radialaxis=dict(showticklabels=True, ticks='', dtick=1, linewidth=0)
    )
)

fig.update_polars(angularaxis_dtick=1,
                  angularaxis_exponentformat="power")

fig.show()

Now, I would like to group some bars together, similar to the figure below (examples python graph gallery):

I cannot figure out how to do this with plotly so I keep both the stacked bars AND the grouping. Any hint or suggestions would be highly appreciated.
Thanks!


text:
Q: How do I set the record's position relative to a group in SQL? I have a series of records that can be grouped by a group_id
Example records:
╭───╥──────────┬───────────────────╮
│id ║ group_id │ position_in_group │
╞═══╬══════════╪═══════════════════╡
│ 1 ║    2     │        null       │
│ 2 ║    1     │        null       │
│ 3 ║    1     │        null       │
│ 4 ║    1     │        null       │
│ 5 ║    2     │        null       │
│ 6 ║    2     │        null       │
│ 7 ║    3     │        null       │
│ 8 ║    3     │        null       │
│ 9 ║    3     │        null       │
└───╨──────────┴───────────────────┘

I want to set the position_in_group for each record. It is the position of the record inside the group if I GROUP BY group_id.
For example:
  In the group with id 1, the record with id=2 is the first, so its position_in_group would be 1.
The final table would be:
╭───╥──────────┬───────────────────╮
│id ║ group_id │ position_in_group │
╞═══╬══════════╪═══════════════════╡
│ 1 ║    2     │        1          │
│ 2 ║    1     │        1          │
│ 3 ║    1     │        2          │
│ 4 ║    1     │        3          │
│ 5 ║    2     │        2          │
│ 6 ║    2     │        3          │
│ 7 ║    3     │        1          │
│ 8 ║    3     │        2          │
│ 9 ║    3     │        3          │
└───╨──────────┴───────────────────┘

Is there any way I can do this in a SQL query?

A: One method is to use variables.  A bit challenging in MySQL, but it can look like this:
set @g := -1;
set @rn := 0;

update t
    set position_in_group = (@rn := if(@g = group_id, @rn + 1,
                                       if(@g := group_id, 1, 1)
                                      )
                            )
    order by group_id, id;

Note:  You need to initialize the variables separately from the update statement, because MySQL does not support joins and order by in the same update statement.

A: There's no need to store this data...
SELECT id
     , group_id
     , rank
  FROM
     ( SELECT id
            , group_id
            , CASE WHEN group_id = @prev THEN @i:=@i+1 ELSE @i:=1 END rank
            , @prev:=group_id prev
         FROM my_table x
            , (SELECT @i:=1,@prev:=null) vars
        ORDER
           BY group_id
            , id
     ) a
 ORDER
    BY id;

...but if you really want to...
UPDATE my_table a
  JOIN
     ( SELECT id
            , group_id
            , CASE WHEN group_id = @prev THEN @i:=@i+1 ELSE @i:=1 END rank
            , @prev:=group_id prev
         FROM my_table x
            , (SELECT @i:=1,@prev:=null) vars
        ORDER
           BY group_id
            , id
     ) b
    ON b.id = a.id
   SET a.rank = b.rank;

A: this solution was implemented by another user abcdn see https://stackoverflow.com/a/32105418/3762855
SELECT a.id, a.group_id, (
    SELECT count(*) from groups b where a.id >= b.id AND a.group_id = b.group_id
) AS row_number FROM groups a;

A: I found out a way to do this with pure SQL and without variables with a self JOIN:
UPDATE my_table
JOIN (
  SELECT c.aid AS id, COUNT(*)-1 AS position_in_group
  FROM (
    SELECT a.id AS aid, b.id AS bid, a.group_id
    FROM my_table AS a
    JOIN my_table AS b ON (a.group_id=b.group_id AND a.id >= b.id)
  ) AS c
  GROUP BY c.aid
) AS d ON my_table.id = d.id
SET my_table.position_in_group = d.position_in_group;

I self join the table with itself to create matching pairs (records in the same group) without duplicate pairs.
Then I just count those pairs grouping by the id of the left record.


text:
Q: How can I check my website is currently protect against csrf? I am working on a dJango web and follow the tutorial to protect it against CSRF, I did something and not sure is it write now install or not, how can I see or check it?

A: From the docs, to enable CSRF protection for your views, follow these steps:

*

*Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES in your settings.py. (It should come before any view middleware that assume that CSRF attacks have been dealt with.)

*In any template that uses a POST form, use the csrf_token tag inside the  element if the form is for an internal URL, e.g.:
<form action="." method="post">{% csrf_token %}

*In the corresponding view functions, ensure that the 'django.core.context_processors.csrf' context processor is being used.
Following these steps will check that CSRF tokens are included properly.
By default, a '403 Forbidden' response is sent to the user if an incoming request fails the checks performed by CsrfViewMiddleware. This should usually only be seen when there is a genuine Cross Site Request Forgery, or when, due to a programming error, the CSRF token has not been included with a POST form.
See the Docs for more info.

A: Check the MIDDLEWARE_CLASSES tuple in settings.py contains this
'django.middleware.csrf.CsrfViewMiddleware',

If this is there in the tuple , then csrf is installed.
Some like this:
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)


text:
Q: Legend title gets cut off I make a plot of Cumulative distribution functions of seven distributions. However, it does not show all the elements of the legend. The plot looks like this:

The distribution does not show "Distribution" in full. Can anyone tell me how to solve this?
The code looks like this:
  ggplot(df, aes(x, colour = Distribution)) + stat_ecdf() + scale_color_discrete(labels = c("N(0, 2)", 'Laplace(0, 1)',
                                  TeX("$0.85N(0, 0.2) + 0.15N(0, 20)$"),
                                  'Gamma(0.05, 0.1)', 'Exp(0.9)', TeX("$F_{3, 8}$"), TeX("$P(mu_i=0) = 0.95, P(mu_i=8) = 0.05$"))) +
  xlim(-3, 3) +
  xlab("Value") +
  ylab("Cumulative Density Function") +
  theme(legend.text.align = 0, legend.position="bottom", legend.text=element_text(size=10))

Also, I do not want to change the position of legend. Because the plot can be too narrow if put the legend left or right side.


text:
Q: JQuery's width() doesn't exclude padding for elements within hidden span I'm trying to get the width of a number of select elements that are hidden. Using width() on the JQuery objects returns a width that is the CSS-defined width but includes padding. Once I toggle the elements to show though, calling width() returns the correct value (i.e. width that excludes padding/border/margins).
sample HTML:
<span id="test" style="visibility:hidden">
    <select id="one">
        <option>1</option><option>2</option><option>3</option>
    </select>
</span>

CSS:
   select {
        width: 80px;
        padding: 0 0 0 15px;
    }

Expected width: 65, reported width: 80
Here's a JSFiddle demonstrating my problem: http://jsfiddle.net/2RH7C/4/
Is there a workaround besides setting "visibility: hidden" (instead of display: none), or cloning/moving the objects off screen? I'm using KnockoutJS data bindings to control visibility, and that binding sets display: none (http://knockoutjs.com/documentation/visible-binding.html).

A: It is the border that is 1px on each side.
With border:none; the result is 65.

A: This appears to be a bug in jQuery 1.7 that does not occur in jQuery 1.8:
http://jsfiddle.net/2RH7C/5/
If you don't have the option to update jQuery, then I'm afraid it seems like the "calculate with offscreen element" or visibility: hidden methods are your only options.

A: The javascript is correct. Using width() already eliminates padding. The rendered width will actually be 110px (80+15+15).


text:
Q: How to upload an existing .ipa-file with In-App-Purchases to ituneconnect without XCode For some speficic reasons I do not want to explain here, I want to upload an existing .ipa-file with In-App-Purchases to ituneconnect without XCode.
Is this possible? If yes, how? Or how can I upload an existing .ipa-file using XCode 7.x.x?
Note: I understand that a tool called 'Application Loader' exists. Hovever I believe that In-App-Purchases need to be added manually this way, which is not needed in my case...

A: I don't think it is possible. Is it your Application with your own code? Because you need to sign your applications with your own profile. Each application has it own set of certificates to make uploading to iTunes connect possible.


text:
Q: PCA plot with large dataframe I have a large data frame (~1400 rows) with the following columns:
    protein   IHD          CM         ARR         VD        CHD           CCD         VOO
0   q9uku9  0.000000    0.039457    0.032901    0.014793    0.006614    0.006591    0.000000
1   o75461  0.000000    0.005832    0.027698    0.000000    0.000000    0.006634    0.000000

etc.
I want to perform a PCA analysis and plot with the vectors, but I'm not sure how to do so with such a large data set. Does anyone have any suggestions?

A: Actually a 1400 x 8 dataframe is not that big on modern computers. You can use scikit-learn to perform PCA on your dataset. It is relatively simple:
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
cols = ['IHD', 'CM', 'ARR', 'VD', 'CHD', 'CCD', 'VOO']
df = pd.DataFrame(np.random.random((1400, 7)), columns = cols)
pca = PCA(n_components=2)
pca.fit(df)
print(pca.components_)
print(pca.explained_variance_)

# [[-0.38406974  0.02775874 -0.59754361 -0.55464116 -0.03878488
#   -0.41944628 0.09795539]
#  [-0.03181143 -0.52699813  0.14325425  0.02742668 -0.48571934
#   -0.33915335 0.590795  ]]
# [0.0913989  0.08975106]

You cannot plot the principal components, since they live in a 7-dimensional space. What you can do, as long as you keep the number of components less than three, is to plot the resulting dataset:
df2 = pd.DataFrame(pca.transform(df), columns = ['first', 'second'])
df2.plot.scatter(x = 'first', y = 'second')

As you can notice, I did not considered the column protein in doing PCA. The reason is that PCA works properly only with numerical column. See this discussion for some hints to handle categorical columns.


text:
Q: Keras Add_loss throwing Operator Not allowed in Graph error I created a basic loss function that takes the CDF (cumsum of pdf) and does a mean_squared error between the two.
Here is the code:
def tuner_loss(y_true, y_pred):
    y_actual=K.cumsum(y_true)
    y_pred=K.cumsum(y_pred)
    return K.mean(K.square(y_actual-y_pred))

I tried model.add_loss(loss_model) with loss="None" then tried
loss=loss_model, then commented out the model.add_loss and loss_model and directly put the  tuner_loss function into loss.
None of the them worked.
Here is that code:
input_layer= Input(179,)
y_actual=Input(199,)
x=Dense(32, activation='relu')(input_layer)
x=Dense(64, activation='relu')(x)
x=Dense(32, activation='relu')(x)
x=Dropout(0.2)(x)
x=Dense(64)(x)
output_layer = Dense(199, activation='softmax')(x)
model=Model(inputs=[input_layer, y_actual], outputs=output_layer)
#loss_model= tuner_loss(y_actual, output_layer)
#model.add_loss(loss_model)
model.compile(optimizer='adam', loss= tuner_loss(y_actual,output_layer), metrics=['accuracy'])

Any help would be greatly appreciated, I figure it has to be
something with how I'm manipulating the tf.tensors in the tuner_loss.
Here is error message I got running last code:

"OperatorNotAllowedInGraphError using a tf.Tensor as a Python bool
  is not allowed in Graph execution. Use Eager execution or decorate
  this function with @tf.function.

I tried the decorator on the tuner, that also threw an error, so that didn't work.
Neither did enabling eager execution...

A: Why not use the standard?
model = Model(input_layer, output_layer)
model.compile(loss = tuner_loss, ...)
model.fit(input_data, output_data, ...)


text:
Q: How Can I Increase the Timeout for Visual Studio Tests? I'm working on a pretty sizable suite of tests for some code I'm writing (in Visual Studio 2012).  For the most part, running the unit tests is no big deal.  But I'm also including a lot of integration tests which have more external infrastructure dependencies.  The number of tests, combined with re-setting the infrastructure dependencies between tests, has resulting in a rather lengthy test run for the full suite (around 45 minutes at the moment).
Running the tests is no big deal.  Unit tests will be run on check-in, integration tests nightly.  However, I'm running into an issue when trying to analyze code coverage for all of the tests.  No code coverage results are created, and the output window says the following:

This request operation sent to net.pipe://megara/vstest.discoveryengine/14108 did not receive a reply within the configured timeout (00:30:00).  The time allotted to this operation may have been a portion of a longer timeout.  This may be because the service is still processing the operation or because the service was unable to send a reply message.  Please consider increasing the operation timeout (by casting the channel/proxy to IContextChannel and setting the OperationTimeout property) and ensure that the service is able to connect to the client.

I'm not sure where it's directing me here.  I don't use any iContextChannel for anything, all of the test-running is built in to Visual Studio.  So I don't really know where/how I can increase any kind of timeout.  Does anybody know where I should look?

A: Try changing the time-out values in your solution .testsettings file.
If you don't have one, you can add it to the solution by using the right-click on solution -> Add New Item -> TestSettings menu. In there you can do time-outs on individual tests (default is 30 minutes), or set the timeout for an entire test run.
It's not clear if this is the root cause or not, but it is worth ruling out.

A: Old topic, but perhaps some new info: I didn't have any luck trying to set the timeout in the .testsettings file with Visual Studio 2015. No matter what I set it to in test settings, my tests would stop after 30 minutes.
There is now a [Timeout(milliseconds)] attribute which can be applied to individual test methods. This is even better than testsettings since you can fine tune individual tests to make sure they aren't taking longer than expected.
Unfortunately, I could not get this attribute to have any effect when attempting to set it higher than 30 minutes when using a .testsettings file, even if the .testsettings file defined a higher timeout. Values lower than 30 minutes were honored, but higher values would still stop at 30 minutes regardless of what testsettings said.
After I removed the .testsettings file, the timeout attributes seem to be working as expected - the test will run up to whatever timeout I set it to.
If you have trouble getting the timeout attribute to work, try removing .testsettings.


text:
Q: How to get a working CSS zigzag border? I'm trying to make a CSS zigzag vertical border. I've been looking at this Codepen for reference. My attempt simply makes diamonds and I've been playing around with it but can't seem to get it to work. Here's my Codepen.

body {
  margin: 0;
  padding: 0;
}
#ribbon {
  background: whitesmoke;
}
#ribbon ul {
  margin: 0;
  padding: 0;
  height: 100px;
  display: flex;
  list-style-type: none;
}
#ribbon ul li {
  display: flex;
  flex-grow: 1;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
#ribbon ul li:not(:last-child) {
  border-right: solid;
}
#ribbon .v-zigzag {
  background: linear-gradient(135deg, transparent, transparent 75%, #b6b5eb 75%, #b6b5eb), linear-gradient(225deg, transparent, transparent 75%, #b6b5eb 75%, #b6b5eb), linear-gradient(45deg, transparent, transparent 75%, #b6b5eb 75%, #b6b5eb), linear-gradient(315deg, transparent, transparent 75%, #b6b5eb 75%, #b6b5eb);
  background-position: right top;
  background-repeat: repeat-y;
  background-size: 10px 10px;
}

Mode 1

Mode 2

Mode 3

Mode 4

A: The sample code uses SVG images, they're encoded into the CSS. Update: No, it doesn't, sorry. But I still think it's the best solution.
It uses two zigzag patterns: One horizontal and other vertical. Then it just covers everything but the borders with an opaque element.
When you change the background alignment, the pattern just won't work anymore and you'll get these diamonds. You could think of a different pattern... or just cover the left part.

*

*Remove the :before as it's used for the horizontal lines

*Move the :after to the left margin and adjust its width to show only one bar
.bordered:after {
    ...
    left: 0;
    width: 26em;
Alternative solution (I came up with a better one using your current markup):

Test

.v-zigzag {
     position: relative;
     background: linear-gradient(45deg, #ccc 5px, transparent 0) 0 5px, linear-gradient(135deg, #ccc 5px, #fff 0) 0 5px;
     background-position: right top;
     background-repeat: repeat-y;
     background-size: 10px 10px;
}
.v-zigzag:before {
    content:"";
    position: absolute;
    background: linear-gradient(45deg, #fff 5px, transparent 0) 0 5px,linear-gradient(135deg, #fff 5px, transparent 0) 0 5px;
    background-color: transparent;
    background-position: right top;
    background-repeat: repeat-y;
    background-size: 10px 10px;
    width: 10px;
    right: 3px;
    top: 0;
    bottom: 0;
 }

Explanation:
The zigzag is not a border, it's actually the background of .v-zigzag. It isn't a line either, it's flat at the left side and zigzag at the right.
Then we use other background on top, like the first one but white, and we place it 3px to the right, covering most of the first background with the white zigzag. This way, the resulting zigzag line is actually the only part "visible" (not covered with white) of the background.
Instead of nested divs, we used the :before selector. The property content (even if it's an empty string) set to the :before or :after of an element, creates a "something" that behabes just like any other element, an element that is not actyally in the DOM but behaves as such. And this pseudoelement is which has the white zigzag and is floating over the gray background.


text:
Q: Download file in jQuery mobile project Just started to teach myself javascript and jQuery mobile to create cross platform apps. I want to be able to click on links in my app to download a PDF file from a document that is synchronized (overwrites) with the local (on the phone) version of the file.
From this, I found out I should use data-ajax="false", so here is my first attempt:
Download

Unfortunately, nothing happens when I click the link after I have built and transferred it to my phone. It works fine in web browser, but not in Phonegap app. Any ideas what could be wrong? And how can I do this in a better way, to achieve exactly what I intend to make it do? If the file is already downloaded, I want the link to say "Open" instead, and have a link to the local version of the file.

A: Android doesn't have a native PDF viewer in its browser, so it doesn't really know what to do with that PDF link, which means you'll need to download it yourself. One solution would be to use Cordova's File and File Transfer plugins. Here's a complete working example from scratch that downloads a PDF that I've parked on a server and allows the user to open it in a reader app, you can test this as follows. Open a command prompt in the directory where you keep your source code and:

*

*Create a Cordova project and move into the project directory. At the command prompt, type:
cordova create hello com.example.hello HelloWorld
cd hello

*In the www directory inside the project directory, replace the entire contents of the www/index.html file with:

<!DOCTYPE html>

        <title>Hello World</title>

        Download PDF

*In the project directory, at the command prompt, type cordova plugin add org.apache.cordova.file-transfer to add the File Transfer plugin.

*In the project directory, at the command prompt, type cordova plugin add org.apache.cordova.file to add the File plugin.

*In the project directory, at the command prompt, type cordova plugin add https://github.com/pwlin/cordova-plugin-file-opener2 to add the File Opener plugin.

*In the project directory, at the command prompt, type cordova run android to build and deploy the app to the emulator or your device.

*In the emulator or on the device, wait until you see the Got deviceready alert and dismiss it; the plugins are now available for use.

*In the emulator or on the device, click the Download PDF button.
You should see a "Download complete" dialog. Dismiss the dialog, and you should get another asking you to select the app to use to open the PDF file.


text:
Q: mousePressEvent not working as expected in QGraphicsScene I've been working on reimplementing a QGraphicsItem, but when the item is clicked, further functions I try to run with that class only affect the instance that was first clicked. My question is, how do I get around this, and only affect the instance that is explicitly clicked?
My class is as follows:
class PrefabPoly(QGraphicsPolygonItem):

    def __init__(self, points, pen, brush, graphicsItem, parent=None):
        super(PrefabPoly, self).__init__(QPolygon(points), graphicsItem, parent.scene)
        self.setPen(pen)
        self.setBrush(brush)
        self.setCursor(Qt.PointingHandCursor)
        self.parent = parent

    def mousePressEvent(self, e):
        print("press")
        if isinstance(self.parent, CreatePrefabGridWidget):
            self.setBrush(self.parent.cur_color)
        #The brush is only changed for the item that was clicked first!?!?

A: This was fixed by calling the original class function instead of totally overriding it.
In the mousePressEvent:
def mousePressEvent(self, e):
    print("press")
    if isinstance(self.parent, CreatePrefabGridWidget):
        self.setBrush(self.parent.cur_color)

    QGraphicsPolygonItem.mousePressEvent(self, e)


text:
Q: PHP preg_replace_callback() and create_function() with eval() do not work I'm trying to deploy my website on the Internet in order to test it in the real environment. It's some kind of text editor where users can use regular expressions and user-defined callback functions.
I have some problem with preg_replace_callback() function. My hosting has PHP version older than 5.3 and I cannot use anonymous function in my code (I have PHP 5.4 at localhost). So I have to rewrite this part of the code (which works correctly at localhost)

$newString = preg_replace_callback(
                    '#' . $this->pattern . '#' . $this->modifiers,
                    function($match)
                    {
                        return eval('return ' . $this->replacement . ';');
                    },
                    $string);

At this point I'm not talking about dangers of using eval() - this problem will be paid proper attention a bit later ("prohibited" word list check etc.). The problem is that my try below

$replacement = $this->replacement;
$newString = preg_replace_callback(
    '#' . $this->pattern . '#' . $this->modifiers,
    create_function('$match', '
                     global $replacement;
                     return eval(\'return \' . $replacement . \';\');
                    '),
                    $string);

does not work and no errors occur. What's wrong with my code?
Any help would be much appreciated.

New info. I've tried this

 Class A
{
    public function check()
    {
        $string = 'series 3-4';
        $pattern = 'series[ ]*(\d+)[ ]*-[ ]*(\d+)';
        $modifiers = 'um';
        $replacement = '$match[2] == $match[1] + 1 ? "series $match[1] and $match[2]" : "series $match[1]-$match[2]"';
        $newString = preg_replace_callback(
                            '#' . $pattern . '#' . $modifiers,
                            create_function('$match', '
                             global $replacement;
                             echo $replacement;
                             return eval(\'return \' . $replacement . \';\');
                            '),
                            $string);
        echo $newString;
    }
}

$a = new A;
$a->check();//get nothing

and found out that $replacement inside create_function() is empty. But when I use the same create_function() outside the class $replacement is not empty:
$string = 'series 3-4';
$pattern = 'series[ ]*(\d+)[ ]*-[ ]*(\d+)';
$modifiers = 'um';
$replacement = '$match[2] == $match[1] + 1 ? "series $match[1] and $match[2]" : "series $match[1]-$match[2]"';
$newString = preg_replace_callback(
                '#' . $pattern . '#' . $modifiers,
                create_function('$match', '
                 global $replacement;
                 echo $replacement . "<br/>";
                 return eval(\'return \' . $replacement . \';\');
                '),
                $string);
echo $newString;
//$match[2] == $match[1] + 1 ? "series $match[1] and $match[2]" : "series $match[1]-$match[2]"
//series 3 and 4

A: You may use a method in place of the lambda function:
Class A
{
    private $replacement;
    public function check()
    {
        $string = 'series 3-4';
        $pattern = 'series[ ]*(\d+)[ ]*-[ ]*(\d+)';
        $this->replacement = '$match[2] == $match[1] + 1 ? "series $match[1] and $match[2]" : "series $match[1]-$match[2]"';
        $modifiers = 'um';
        $newString = preg_replace_callback(
                            '#' . $pattern . '#' . $modifiers,
                            array($this, 'replacementCallback'),
                            $string);
        echo $newString;
    }

    private function replacementCallback($match)
    {
        return eval('return ' . $this->replacement . ';');
    }
}

$a = new A;
$a->check();

A: This works, inserting the $replacement string value properly formatted as PHP source into the source of the function:
function check()
{
    $string = 'series 3-4';
    $pattern = 'series[ ]*(\d+)[ ]*-[ ]*(\d+)';
    $modifiers = 'um';
    $replacement = '$match[2] == $match[1] + 1 ? "series $match[1] and $match[2]" : "series $match[1]-$match[2]"';
    $newString = preg_replace_callback(
                        '#' . $pattern . '#' . $modifiers,
                        create_function('$match', '
                            return eval("return " . '.var_export($replacement,true).' . ";");
                        '),
                        $string);
    echo $newString;
}
check(); // prints "series 3 and 4"
?>

But why bother putting in code and evaling it, when you can just put it in the source of the function directly:
<?
function check()
{
    $string = 'series 3-4';
    $pattern = 'series[ ]*(\d+)[ ]*-[ ]*(\d+)';
    $modifiers = 'um';
    $replacement = '$match[2] == $match[1] + 1 ? "series $match[1] and $match[2]" : "series $match[1]-$match[2]"';
    $newString = preg_replace_callback(
                        '#' . $pattern . '#' . $modifiers,
                        create_function('$match', '
                            return '.$replacement.';
                        '),
                        $string);
    echo $newString;
}
check(); // prints "series 3 and 4"
?>


text:
Q: Designing Admin Service Recently I got a chance to contribute to a project. The project is very vast and contains many independent modules like brand section, store section, user section etc. All these modules contain respective models that contains business logic. Admin has all capabilities like adding a brand to a parent organisation. Creating a user and assigning him any roles.
There are many business logic in built into each module. For example, normal users can not add any other user, but users with manager role can create 5 users under them. Admin can create any number of users. Similarly there are many other constraints. Right now what I am seeing is all validation has been put into controller layer. For example the controller first checks that if the user is normal user or admin or manager. Then if a manager, it checks for how many users he has already etc etc.Same goes with brands module and stores module. Right now admin module has no model, it just uses models from other module to perform operations. This has made the controller very thick. Also I think that these validations should go into model as these are business rules. But if I put these validations into model of respective modules, every function needs to be in two flavours, one for admin and another for non admin. These will lead to duplication of code.

*

*Is the current design of admin controller using other models is fine and maintainable.

*Is it ok for models to have only generic functions, like  right now user model is having generic functions like add user, check number of delegated users for a user and controller is using both of these methods to perform the operation.

*Should I write a wrapper over admin service wrapper for each module ? But this will destroy the cohesiveness of admin module.

Right now the product is working fine soon a number of other modules will be added. How can I make sure that code is maintainable ? Also I have read at many places that a model should talk to another model using services only. Should I write an admin service for each module ?


text:
Q: PhpMyAdmin database Export. I am exporting database from PHPMYADMIN. Database has 341 tables on remote server but when I import Sql file into local server PHPMYADMIN I got only 213 Tables.
Question :
How can I get all tables of database on localhost.

A: phpmyadmin should export all when you do export -> quick, but try to use the custom option and make sure all are selected. Also, may want to check the mysql mode (select @@global.sql_mode) of local and remote. If your local has default settings, there may be some tables with data in a column that's not allowed.

A: Assuming that your database is pretty large then you may have more success with exporting it via the command line rather than phpMyAdmin:
/usr/bin/mysqldump -u USERANME -p DATABASE_NAME > output.sql

Run that, you'll be prompted for your database password and then you'll get output.sql containing your database
You can then import this using ..
/usr/bin/mysql -u USERNAME -p DATABASE_NAME --no-create-db < output.sql


text:
Q: Which way of specifiying my beans in spring-integration.xml is better? I have two different ways of declaring a spring integration bean. They both seem to work. I'm using the Spring STS Eclipse based IDE.
This way:
<bean id="int-ftp:request-handler-advice-chain"
        class="org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice">
        <property name="trapException" value="true"></property>
        <property name="onFailureExpression" value="#root"></property>
        <property name="failureChannel" ref="errorChannel"></property>
</bean>

or this way:
<int-ftp:request-handler-advice-chain>
    <bean class="org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice">
        <property name="trapException" value="true" />
        <property name="onFailureExpression" value="#root" />
        <property name="failureChannel" ref="errorChannel" />
    </bean>
</int-ftp:request-handler-advice-chain>

Which way is better?

A: For the target <int-ftp:outbound-gateway> it doesn't matter. Works well, as you noticed already.
Only the difference that the second declaration is nested and the final bean is visible only from the <int-ftp:request-handler-advice-chain> context.
The first definition is top-level global bean, which is visible everywhere and can be reused from other bean as well.
You can find more info about Inner Beans in the Spring Framework.


text:
Q: Time-based Workflow Rules: based on field with workflow update TODAY() Trying to create a sales SLA process declaratively. I have a date field (Status Change Date) which is updated with a workflow rule to TODAY() whenever the Status field is edited. I'm trying to create a task when the status hasn't changed for 21 days, so I was using a Time-based workflow rule... Trigger when status = working, time-based workflow is 21 days from status change date create a task.
I'm not sure that it's working. To test I set the time-based workflow down to 1 day, changed the status which triggered the Status Change Date to update. I checked back today, but I did not see the task.
I looked into some documentation and found this. The line that concerns me is the following:
Time triggers don't support minutes or seconds.
Time triggers can't reference the following:
    DATE or DATETIME fields containing automatically derived functions, such as TODAY or NOW.
    Formula fields that include related-object merge fields.

Does this mean that the time-based workflow won't use the Status Change Date because it was set by the workflow rule to TODAY()?
If that's true, is there any declaritive way to trigger a task when a record is sitting in a status after a period of time?

A: This is the correct way to do this.
It will use the status change date assuming you are not using a formula field.
Assuming you have just set the field using TODAY it will be fine to use.
The trigger just cant reference a nondeterministic formula.
Try checking on the work flow to update field check reevaluate workflow criteria.
I created a workflow that updates a field to today based on status changed. The second workflow uses a formula that is set to true and will start a task (or in your case email) if the field value is not updated within the time period. - It creates the task every period unless the field is updated and stops it from sending.
You can use time-based workflow monitoring to help debug and check if its working. It should show up.
setup->monitoring->time based workflow


text:
Q: If $A$, $B$, and $C$ are sets, then $(A \cup B) − C = (A − C) \cup (B − C)$ I need to prove: $(A \cup B) − C = (A − C) \cup (B − C)$
The left side is the set that is either in $A$ or $B$ or both but not in $C$. The right side is the set in $A$ that doesn't contain $C$ or the set in $B$ that doesn't contain $C$. The Venn Diagram for this seems straightforward. But how would I perform a written proof.
I think this is a two part proof. First prove the left side implies the right, then that the right side implies the left.
How would I go about doing this exactly?

A: Here is an algebraic proof that uses indicator functions.
Recall that the indicator function $1_A$ of a set $A$ satisfies $1_A(x) = 1$ when $x \in A$ and $1_A(x) = 0$ otherwise.
It is easy to check that $1_{A \cup B} = \max(1_A, 1_B)$ and $1_{A\setminus B} = \max(0, 1_A -1_B)$.
Then we have
\begin{eqnarray}
1_{(A \cup B) \setminus C} &=& \max(0,1_{A \cup B}-1_C ) \\
&=& \max(0, \max(1_A, 1_B) - 1_C) \\
&=& \max(0, \max(1_A-1_C, 1_B-1_C)) \\
&=& \max(0, \max(0, 1_A-1_C), \max(0,1_B-1_C)) \\
&=& \max(\max(0, 1_A-1_C), \max(0,1_B-1_C)) \\
&=& 1_{(A \setminus C) \cup (B \setminus C)}
\end{eqnarray}

A: $$(A\cup B)\backslash C=(A\cup B)\cap C^c=(A\cap C^c)\cup(B\cap C^c)=(A\backslash C)\cup (B\backslash C)$$

A: I think your idea is right; if you prove the following two statements:
$$x \in L \rightarrow x\in R$$
$$x\in R\rightarrow x\in L$$
where $L$ and $R$ are the left and right sides of the equality, that suffices to show that $L=R$. For instance, suppose
$$x\in (A\cup B)-C$$
does it follow that $x\in (A-C)\cup(B-C)$? Or equivalently, that $x$ is in either $A-C$ or $B-C$?

A: My favorite method for problems such as these is to write out the two sides of the equation in set notation. For example, the LHS is
$$(A \cup B) - C = \{x \mid (x \in A \vee x \in B) \wedge x \not \in C\}.$$
My next step is to use the arithmetic of $\vee$ and $\wedge$ to expand the expression $(x \in A \vee x \in B) \wedge x \not \in C$. Recall that $\wedge$ distributes over $\vee$, so we get $(x \in A \vee x \in B) \wedge x \not \in C = (x \in A \wedge x \not \in C) \vee (x \in B \vee x \not \in C)$. So
$$(A \cup B) - C = \{x \mid (x \in A \vee x \in B) \wedge x \not \in C\} = \{x \mid (x \in A \wedge x \not \in C) \vee (x \in B \vee x \not \in C)\} = (A - C) \cup (B - C).$$


text:
Q: How to find the employee with most customers I have en employee table that looks like this
employeenumber int(11) PK
lastname varchar(50)
firstname varchar(50)

And a customer table that look like this
customernumber int(11) PK
salesrepemployeenumber int(11)
creditlimit double

How do I find the employee with most customers?
I know I have to make a query of the salesrepemployeenumber column in the customer table to find out which employee has the most customer with a count, max??? And then i need to return the employee number and the full name.
What is the solution???

A: Use a join/count/group by:
SELECT
    employees.employeenumber, -- employee id
    employees.lastname, -- sample employee name
    COUNT(customers.customernumber) AS customer_count -- the number of customers
FROM employees
LEFT OUTER JOIN customers -- I'm using a left join so we can see people with 0 as well
    -- get some shorter column names man
    ON customers.salesrepemployeenumber = employees.employeenumber
GROUP BY employees.employeenumber

In short, you select all of the employees, then merge them with the results of the customers tables, then group them by the employee's id. By using COUNT during a GROUP BY operation, we can count the number of distinct entries to a specific group.
From there it's a matter of selecting the largest value out of the results, which is as simple as using LIMIT/ORDER BY
SELECT ...
ORDER BY customer_count DESC
LIMIT 1

A: Join the two tables, group them by the primary key of the employee table and order the results by count descendingly, getting the first result (having the most results)
select employee.salesrepemployeenumber, employee.lastname, employee.firstname, count(*) as result
from employee
join customer
on employee.employeenumber = customer.salesrepemployeenumber
group by employeenumber
order by count(*) desc limit 0, 1;


text:
Q: Extracting data from a nested variant/JSON column in snowflake Below is the data I have from a Json file which is loaded into snowflake variant table and I want to extract 'Mike Robinson' from the value {\"objCode\":\"USER\",\"name\":\"Mike Robinson\",\"ID\":\"5e4edc9400fbf45c6a67786fe0b62466\"}, for the column DE:WSP PRG GPM Partner from the below example.
{
      "ID": "5e13939f00e62030bc40ae3a243f538c",
      "auditTypes": [],
      "categoryID": "6037d132005cf57b209d13eef407a03b",
      "customerID": "76bf18dd792b9b9ce0530a093a0a1933",
      "description": "Continue to grow Wise in current markets and expand public library opportunities in new markets.",
      "enteredByID": null,
      "entryDate": "2020-01-06T15:07:59:367-0500",
      "etl_load_ts": "2021-04-22_14:41:35:828",
      "extRefID": null,
      "hasDocuments": false,
      "hasMessages": false,
      "hasNotes": false,
      "isActive": true,
      "lastUpdateDate": "2021-04-15T11:32:21:311-0400",
      "lastUpdatedByID": "5e4edc9400fbf45c6a67786fe0b62466",
      "name": "Program: OCLC Wise (SB)",
      "objCode": "PRGM",
      "ownerID": "5e4edac200f823591158b896c670f51b",
      "parameterValues": {
        "DE:Program Show on WSP": "Yes",
        "DE:WSP PRG Executive Status Summary": "Overall health is YELLOW. For US libraries we had a key breakthrough on 2/17. After months of work with Linked In, we have achieved interoperability with Lynda.com. Many public libraries provide access to training via Lynda.com to benefit their patrons.",
        "DE:WSP PRG Financial Partner": "{\"objCode\":\"USER\",\"name\":\"Chad Beuck\",\"ID\":\"5e4eda6500f75fa86187f5c0b6dea9a2\"}",
        "DE:WSP PRG GPM Partner": "{\"objCode\":\"USER\",\"name\":\"Mike Robinson\",\"ID\":\"5e4edc9400fbf45c6a67786fe0b62466\"}",
        "DE:WSP PRG KD-1 Reason": "N/A",
        "DE:WSP PRG KD-2 Reason": "N/A",
        "DE:WSP PRG Key Decision Date Approved 1": "2021-02-01",
        "DE:WSP PRG Key Decision Date Approved 2": "2021-02-01",
        "DE:WSP PRG Key Decision Description 1": "N/A",
        "DE:WSP PRG Key Decision Description 2": "N/A",
        "DE:WSP PRG Key Decision ID 1": "0000",
        "DE:WSP PRG Key Decision ID 2": "N/A",
        "DE:WSP PRG Key Decision Owner 1": "N/A",
        "DE:WSP PRG Key Decision Owner 2": "N/A",
        "DE:WSP PRG Key Dependencies 1": "N/A",
        "DE:WSP PRG Key Dependencies 2": "N/A",
        "DE:WSP PRG Key R/I Description 1": "Recently heightened srutiny of security and privacy practices is resulting in project impacts for EMEA based projects.",
        "DE:WSP PRG Key R/I Description 2": "---",
        "DE:WSP PRG Key R/I Impact 1": "2",
        "DE:WSP PRG Key R/I Impact 2": "-",
        "DE:WSP PRG Key R/I Impact to Cost 1": "Indirect",
        "DE:WSP PRG Key R/I Impact to Cost 2": "---",
        "DE:WSP PRG Key R/I Impact to Sched 1": "Yes",
        "DE:WSP PRG Key R/I Impact to Sched 2": "---",
        "DE:WSP PRG Key R/I Probability 1": "-",
        "DE:WSP PRG Key R/I Probability 2": "-",
        "DE:WSP PRG Key Risk/Issue 1": "Issue",
        "DE:WSP PRG Key Risk/Issue 2": "---",
        "DE:WSP PRG Key Risk/Issue Choice 1": "Risk",
        "DE:WSP PRG Key Risk/Issue Choice 2": "Issue",
        "DE:WSP PRG Overall Health": "Yellow",
        "DE:WSP PRG Primary Business Value": "Provide a comprehensive view of all Wise work activities and understand their impact to the resource portfolio. Assure effective communications, coordination across workstreams in order to prevent delivery delays/failures.",
        "DE:WSP PRG Program Code #": "N/A",
        "DE:WSP PRG Program Sponsor": "{\"objCode\":\"USER\",\"name\":\"Scott Livingston\",\"ID\":\"5e4edbd300fa28183f47c65b9641d7cb\"}",
        "DE:WSP PRG Program Turned Red": "2021-02-01",
        "DE:WSP PRG Target For Green": "2021-03-03",
        "DE:WSP PRG Upcoming MS-1 Date": "2021-03-15",
        "DE:WSP PRG Upcoming MS-2 Date": "2021-02-26",
        "DE:WSP PRG Upcoming MS-3 Date": "2021-03-15",
        "DE:WSP PRG Upcoming MS-4 Date": "2021-03-22",
        "DE:WSP PRG Upcoming Milestone 1": "Fayetteville Go Live",
        "DE:WSP PRG Upcoming Milestone 2": "3475 - Path to GREEN Realized",
        "DE:WSP PRG Upcoming Milestone 3": "N/A",
        "DE:WSP PRG Upcoming Milestone 4": "N/A"
      },
      "portfolioID": "5bfc22ed00b20b189229e8201f3742b6",
      "securityRootID": "5e13939f00e62030bc40ae3a243f538c",
      "securityRootObjCode": "PRGM"
    },

A: parse_json(parse_json(val):"parameterValues"."DE:WSP PRG GPM Partner"):name returns "Mike Robinson":
with data as (
select
$$
{
      "ID": "5e13939f00e62030bc40ae3a243f538c",
      "auditTypes": [],
      "categoryID": "6037d132005cf57b209d13eef407a03b",
      "customerID": "76bf18dd792b9b9ce0530a093a0a1933",
      "description": "Continue to grow Wise in current markets and expand public library opportunities in new markets.",
      "enteredByID": null,
      "entryDate": "2020-01-06T15:07:59:367-0500",
      "etl_load_ts": "2021-04-22_14:41:35:828",
      "extRefID": null,
      "hasDocuments": false,
      "hasMessages": false,
      "hasNotes": false,
      "isActive": true,
      "lastUpdateDate": "2021-04-15T11:32:21:311-0400",
      "lastUpdatedByID": "5e4edc9400fbf45c6a67786fe0b62466",
      "name": "Program: OCLC Wise (SB)",
      "objCode": "PRGM",
      "ownerID": "5e4edac200f823591158b896c670f51b",
      "parameterValues": {
        "DE:Program Show on WSP": "Yes",
        "DE:WSP PRG Executive Status Summary": "Overall health is YELLOW. For US libraries we had a key breakthrough on 2/17. After months of work with Linked In, we have achieved interoperability with Lynda.com. Many public libraries provide access to training via Lynda.com to benefit their patrons.",
        "DE:WSP PRG Financial Partner": "{\"objCode\":\"USER\",\"name\":\"Chad Beuck\",\"ID\":\"5e4eda6500f75fa86187f5c0b6dea9a2\"}",
        "DE:WSP PRG GPM Partner": "{\"objCode\":\"USER\",\"name\":\"Mike Robinson\",\"ID\":\"5e4edc9400fbf45c6a67786fe0b62466\"}",
        "DE:WSP PRG KD-1 Reason": "N/A",
        "DE:WSP PRG KD-2 Reason": "N/A",
        "DE:WSP PRG Key Decision Date Approved 1": "2021-02-01",
        "DE:WSP PRG Key Decision Date Approved 2": "2021-02-01",
        "DE:WSP PRG Key Decision Description 1": "N/A",
        "DE:WSP PRG Key Decision Description 2": "N/A",
        "DE:WSP PRG Key Decision ID 1": "0000",
        "DE:WSP PRG Key Decision ID 2": "N/A",
        "DE:WSP PRG Key Decision Owner 1": "N/A",
        "DE:WSP PRG Key Decision Owner 2": "N/A",
        "DE:WSP PRG Key Dependencies 1": "N/A",
        "DE:WSP PRG Key Dependencies 2": "N/A",
        "DE:WSP PRG Key R/I Description 1": "Recently heightened srutiny of security and privacy practices is resulting in project impacts for EMEA based projects.",
        "DE:WSP PRG Key R/I Description 2": "---",
        "DE:WSP PRG Key R/I Impact 1": "2",
        "DE:WSP PRG Key R/I Impact 2": "-",
        "DE:WSP PRG Key R/I Impact to Cost 1": "Indirect",
        "DE:WSP PRG Key R/I Impact to Cost 2": "---",
        "DE:WSP PRG Key R/I Impact to Sched 1": "Yes",
        "DE:WSP PRG Key R/I Impact to Sched 2": "---",
        "DE:WSP PRG Key R/I Probability 1": "-",
        "DE:WSP PRG Key R/I Probability 2": "-",
        "DE:WSP PRG Key Risk/Issue 1": "Issue",
        "DE:WSP PRG Key Risk/Issue 2": "---",
        "DE:WSP PRG Key Risk/Issue Choice 1": "Risk",
        "DE:WSP PRG Key Risk/Issue Choice 2": "Issue",
        "DE:WSP PRG Overall Health": "Yellow",
        "DE:WSP PRG Primary Business Value": "Provide a comprehensive view of all Wise work activities and understand their impact to the resource portfolio. Assure effective communications, coordination across workstreams in order to prevent delivery delays/failures.",
        "DE:WSP PRG Program Code #": "N/A",
        "DE:WSP PRG Program Sponsor": "{\"objCode\":\"USER\",\"name\":\"Scott Livingston\",\"ID\":\"5e4edbd300fa28183f47c65b9641d7cb\"}",
        "DE:WSP PRG Program Turned Red": "2021-02-01",
        "DE:WSP PRG Target For Green": "2021-03-03",
        "DE:WSP PRG Upcoming MS-1 Date": "2021-03-15",
        "DE:WSP PRG Upcoming MS-2 Date": "2021-02-26",
        "DE:WSP PRG Upcoming MS-3 Date": "2021-03-15",
        "DE:WSP PRG Upcoming MS-4 Date": "2021-03-22",
        "DE:WSP PRG Upcoming Milestone 1": "Fayetteville Go Live",
        "DE:WSP PRG Upcoming Milestone 2": "3475 - Path to GREEN Realized",
        "DE:WSP PRG Upcoming Milestone 3": "N/A",
        "DE:WSP PRG Upcoming Milestone 4": "N/A"
      },
      "portfolioID": "5bfc22ed00b20b189229e8201f3742b6",
      "securityRootID": "5e13939f00e62030bc40ae3a243f538c",
      "securityRootObjCode": "PRGM"
    },
    $$ val
)

select parse_json(parse_json(val):"parameterValues"."DE:WSP PRG GPM Partner"):name::varchar
from data
;


text:
Q: LSH in Scala and Python API I was following this SO post Efficient string matching in Apache Spark to get some string matching using LSH algorithm. For some reason getting results thru python API, but not in Scala. I don't see really where what is missing in Scala code.
Here below are the both codes:
from pyspark.ml import Pipeline
from pyspark.ml.feature import RegexTokenizer, NGram, HashingTF, MinHashLSH

query = spark.createDataFrame(["Bob Jones"], "string").toDF("text")

db = spark.createDataFrame(["Tim Jones"], "string").toDF("text")

model = Pipeline(stages=[
    RegexTokenizer(
        pattern="", inputCol="text", outputCol="tokens", minTokenLength=1
    ),
    NGram(n=3, inputCol="tokens", outputCol="ngrams"),
    HashingTF(inputCol="ngrams", outputCol="vectors"),
    MinHashLSH(inputCol="vectors", outputCol="lsh")
]).fit(db)

db_hashed = model.transform(db)
query_hashed = model.transform(query)

model.stages[-1].approxSimilarityJoin(db_hashed, query_hashed, 0.75).show()

And it returns:

> +--------------------+--------------------+-------+ |            datasetA|            datasetB|distCol|
> +--------------------+--------------------+-------+ |[Tim Jones, [t, i...|[Bob Jones, [b, o...|    0.6|
> +--------------------+--------------------+-------+

However Scala returns nothing, and here is the code:
import org.apache.spark.ml.feature.RegexTokenizer
val tokenizer = new RegexTokenizer().setPattern("").setInputCol("text").setMinTokenLength(1).setOutputCol("tokens")
import org.apache.spark.ml.feature.NGram
val ngram = new NGram().setN(3).setInputCol("tokens").setOutputCol("ngrams")
import org.apache.spark.ml.feature.HashingTF
val vectorizer = new HashingTF().setInputCol("ngrams").setOutputCol("vectors")
import org.apache.spark.ml.feature.{MinHashLSH, MinHashLSHModel}
val lsh = new MinHashLSH().setInputCol("vectors").setOutputCol("lsh")
import org.apache.spark.ml.Pipeline
val pipeline = new Pipeline().setStages(Array(tokenizer, ngram, vectorizer, lsh))
val query = Seq("Bob Jones").toDF("text")
val db = Seq("Tim Jones").toDF("text")
val model = pipeline.fit(db)
val dbHashed = model.transform(db)
val queryHashed = model.transform(query)
model.stages.last.asInstanceOf[MinHashLSHModel].approxSimilarityJoin(dbHashed, queryHashed, 0.75).show

I am using Spark 3.0, I know its a test, but can't really test it on different version. And I doubt there is a bug like that :)

A: This code will work in Spark 3.0.1 if you set numHashTables correctly.
val lsh = new MinHashLSH().setInputCol("vectors").setOutputCol("lsh").setNumHashTables(3)


text:
Q: Can IntelliJ IDEA Community Edition support Ultimate's features somehow? I know that Community ediition doesn't support certain features of Ultimate but I want to know that there is NO way to make these features to run in anyway. For example, the Enterprise development (e.g. Tomcat, Glassfish, Oracle, etc.) or Web development (e.g. Spring, HTML5, etc. ). So, if I have to run these kind of development somehow can I succeed in doing these things only with the Community edition or I am locked and not able to do such things. Say, I don't have the luxury to go to Ultimate for some reason.

A: You may use IDEA Community Edition for editing the code, you just won't get any features specific to the servers you're using, e.g. run configurations. You'll have to launch your application using the command line. You'll be able to use Artifacts feature to build all the jars you need.
You won't get any Spring-specific code completion or code inspections, but you'll get a decent XML editor for its configuration files. You'll get some basic HTML editing features, but no JavaScript.
There's no way to get those features out of IntelliJ IDEA Community Edition source, they just aren't there.
BTW if you use Ultimate EAP as NimChimpsky suggests, and report plenty of bugs, the developers might be grateful for them and give you a free license in return at the moment of the release (around December).

A: If you are a cheapskate use the EAP from Jetbrain's Confluence page.
The early access might have bugs - but it's free, has all the features of the Ultimate edition, and then some.


text:
Q: Como salvar o conteúdo da minha página na url onclick? Bom dia pessoal, gostaria de saber como posso salvar o conteúdo da minha página na url com um id único. Igual o jsfiddle.net
Por exemplo, quando você acessa pela primeira vez, ele tem a url padrão: jsfiddle.net, porém ao clicar no botão "save", ele gera essa url: https://jsfiddle.net/eh3zpcko/, e a cada clique no "save" ele conta e gera a seguinte url: https://jsfiddle.net/eh3zpcko/1/. Gostaria de saber como posso fazer isso sem que o usuário esteja logado.
Isso aí acima é só um exemplo.
Desde já agradeço.


text:
Q: Add custom domain to specific URL of main domain I have a multivendor eCommerce site. for example, mainsite.com. where vendor shop URL is mainsite.com/s/shopname. I want to give vendors to add a custom domain pointing to their shop. How can I create this type of functionality on my site?
This feature is similar to adding a custom domain to sites (Google sites, Heroku, Wix, Github, etc..)


text:
Q: Is EME just an  tag with encryption? This is a touchy topic. I have tried to present the context, but keep the question focused on the technical question rather than a debate of right-versus-wrong. Please support whichever side of the debate you prefer with your wallet and feet, not in the comments or answer.

The Encrypted Media Extensions draft dated 7 January 2014, the drafters insist (my emphasis):

This specification does not define a content protection or Digital Rights Management system. Rather, it defines a common API that may be used to discover, select and interact with such systems as well as with simpler content encryption systems. Implementation of Digital Rights Management is not required for compliance with this specification.

Instead, they say:

The common API supports a simple set of content encryption capabilities, leaving application functions such as authentication and authorization to page authors. This is achieved by requiring content protection system-specific messaging to be mediated by the page rather than assuming out-of-band communication between the encryption system and a license or other server.

But I assume that EME is what everyone is up in arms about when they say that the W3C 'are introducing DRM' to HTML 5.

My (limited) understanding of the spec is:
It defines a generic hook for authenticating access to a media file on an HTML page. The authentication would be handled server-side not client-side ("leaving application functions such as authentication and authorization to page authors") but via HTTP ("requiring content protection system-specific messaging to be mediated by the page rather than assuming out-of-band communication"). One obvious use, and the motivation for EME (citation needed?), is consumer-oriented DRM. [1]
The intended effect is to replace client-side media wrappers (Flash, Silverlight...) with a simple hook into server-side authentication providers.
[1] Could there be other, security-oriented applications of EME?

So, assuming I got all that right, am I correct that this...
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="550" height="400" id="movie_name" align="middle">
    <param name="movie" value="movie_name.swf"/>

    <object type="application/x-shockwave-flash" data="movie_name.swf" width="550" height="400">
        <param name="movie" value="movie_name.swf"/>

    </object>

</object>

(where the SWF file imposes DRM via internal, client-side code and/or hooks to server-side authentication, executed in the browser via Flash)
would be replaced with something like this (adapted from html5media.info)? [2]
<video src="movie_name.mp4" eme="some_drm_key_or_something_here"
width="550" height="400" controls preload id="movie_name"></video>

[2] But where is the file stored, and for how long?

TL;DR Ignoring whether or not DRM is ethical/good business/a pain, is EME a means to formalise a vendor-neutral, server-dependent, no-plugins-required mechanism to authenticate access to media files? Implementation could, for example, add attributes to existing HTML5 media tags, and as long as the browser could a) authenticate and b) play the file format, the media would be viewable.

A: Yes.
And No.
First let me explain the NO.
EME does in its essence not define a DRM technique: it defines an API to access DRM modules in the browser (or in the operating system, or in a browser plug-in).
This means the user still has to have access to the required DRM method. If the browser vendor does not support it, you will need a plug-in. (Also, it's extremely unlikely that vendors will include support for the DRM of their competition: Google Chrome has support for Google's Widevine, IE11 had support for Microsoft's PlayReady. I would be very surprised if Firefox would choose to support any of these.)
Browser plug-ins however do not offer a valid option: they do not exist on mobile devices. It might be possible some browsers will allow apps to add DRM, but think of the security risks this would bring. The same risks go for plug-ins by the way. Think of the Adobe Flash security horrors.
Now on the YES front: there is a mechanism which is included in EME that should be supported by ALL browsers in form of clearkey. However the purpose of clearkey is to be able to test EME applications. Practical use will be limited unless the big media studios would see it as a proper DRM (which they don't).
So to round up:
In practice, EME is more pain than good. It brings more fragmentation for broadcasters since all browsers will support their own DRM schemes. This means the user will be bothered to either install insecure plug-ins and add-ons or to use certain specific browsers or devices to access content. At the other side of the spectrum, broadcasters will have to publish content using multiple DRM mechanisms, which will strangle them in license fees.


text:
Q: What is the most efficient method to conduct for hypothesis testing? To gather from the data whether the hypotheses I proposed are confirmed, I calculate the two means between different reform variables to see if the reform have influence on the performance indicators of the electricity generation sector. So I want to measure the significance of the difference between two sample means of our observation using t-statistic calculated as part of the t-test (i.e. as a scaled difference between two different means, where the absolute difference between them is rescaled using an estimate of the variability of the means). How do I start?

A: For those of you interested, I think the document mentioned in OP's comment is this pdf. The analysis is on page 44, part of which was posted here as the question.
Now, to the question. What they did is likely an "independent sample t-test." To start, you'll need to have at least two columns of data, one is the dependent variable which is continuous in nature, and one is a dichotomous variable that indicates the grouping.
Once you have those ready, then based on the software you use, you can try searching for appropriate readings or videos online. Or ask your technical questions on another forum Stack Overflow.
If you're going to compute the t-statistics by hand, then you can find plenty of examples online by performing a keyword-specific search.

In addition, the way Vagliasindi and Besant-Jones describe their analysis is not the most reader-friendly. I'd suggest you to consult a couple introductory statistics books, perhaps one for general statistics and one related to your field of interest.


text:
Q: Postgres is stuck in recovery mode I have a stand-alone instance of PostgreSQL which is in recovery mode. It has been saying
2014-03-24 18:45:57 MDT FATAL:  the database system is starting up

For many hours, and ps shows:
postgres  2637  0.1  0.1 116916  4420 ?        Ds   15:43   0:18 postgres: startup process   recovering 00000001000000040000007E

Is there any way to watch the progress of the recovery, ideally with an ETA? How can I get this process "un-stuck"?
I can stop postgres using the standard start/stop scripts, but when I start it again, it's still stuck in recovery mode.
Debian 7.4, Linux kernel 3.2.0, PostgreSQL 9.1.12

Output of strace -p 2637:
Process 2637 attached - interrupt to quit
close(154)                              = 0
getppid()                               = 2600
open("pg_clog/0003", O_RDWR|O_CREAT, 0600) = 154
lseek(154, 221184, SEEK_SET)            = 221184
write(154, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 8192) = 8192
fsync(154)                              = 0

The above output repeats seemingly infinitely.

A gdb backtrace (three subsequent bts were all practically identical):
(gdb) bt
#0  0x00007f0c8f917d70 in fsync () from /lib/x86_64-linux-gnu/libc.so.6
#1  0x00007f0c9169f255 in pg_fsync_no_writethrough (fd=<optimized out>) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/storage/file/fd.c:286
#2  0x00007f0c9169f265 in pg_fsync (fd=<optimized out>) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/storage/file/fd.c:274
#3  0x00007f0c9151917b in SlruPhysicalWritePage (ctl=ctl@entry=0x7f0c91b856c0, pageno=pageno@entry=123, slotno=slotno@entry=3, fdata=fdata@entry=0x0) at /home/cbe/projects/postgresql/9.1/postgresql-9.1- 9.1.12/build/../src/backend/access/transam/slru.c:801
#4  0x00007f0c91519925 in SlruInternalWritePage (ctl=ctl@entry=0x7f0c91b856c0, slotno=3, fdata=fdata@entry=0x0) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/slru.c:528
#5  0x00007f0c9151a1c7 in SimpleLruWritePage (ctl=ctl@entry=0x7f0c91b856c0, slotno=<optimized out>) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/slru.c:565
#6  0x00007f0c915018e3 in clog_redo (lsn=..., record=<optimized out>) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/clog.c:720
#7  0x00007f0c91515f08 in StartupXLOG () at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/xlog.c:6664
#8  0x00007f0c91518537 in StartupProcessMain () at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/xlog.c:10179
#9  0x00007f0c9152f1ba in AuxiliaryProcessMain (argc=<optimized out>, argc@entry=2, argv=<optimized out>, argv@entry=0x7fff651b0610) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/bootstrap/bootstrap.c:409
#10 0x00007f0c9167ddeb in StartChildProcess (type=StartupProcess) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/postmaster/postmaster.c:4512
#11 0x00007f0c916806ac in PostmasterMain (argc=argc@entry=5, argv=argv@entry=0x7f0c91d8e180) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/postmaster/postmaster.c:1118
#12 0x00007f0c914d392f in main (argc=5, argv=0x7f0c91d8e180) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/main/main.c:209

And if I set:
fsync = off

And run the bt again:
(gdb) bt
#0  0x00007f3d99ab7160 in write () from /lib/x86_64-linux-gnu/libc.so.6
#1  0x00007f3d9b6be0c6 in SlruPhysicalWritePage (ctl=ctl@entry=0x7f3d9bd2a6c0, pageno=pageno@entry=123, slotno=slotno@entry=3, fdata=fdata@entry=0x0) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/slru.c:783
#2  0x00007f3d9b6be925 in SlruInternalWritePage (ctl=ctl@entry=0x7f3d9bd2a6c0, slotno=3, fdata=fdata@entry=0x0) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/slru.c:528
#3  0x00007f3d9b6bf1c7 in SimpleLruWritePage (ctl=ctl@entry=0x7f3d9bd2a6c0, slotno=<optimized out>) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/slru.c:565
#4  0x00007f3d9b6a68e3 in clog_redo (lsn=..., record=<optimized out>) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/clog.c:720
#5  0x00007f3d9b6baf08 in StartupXLOG () at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/xlog.c:6664
#6  0x00007f3d9b6bd537 in StartupProcessMain () at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/access/transam/xlog.c:10179
#7  0x00007f3d9b6d41ba in AuxiliaryProcessMain (argc=<optimized out>, argc@entry=2, argv=<optimized out>, argv@entry=0x7fff99d477a0) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/bootstrap/bootstrap.c:409
#8  0x00007f3d9b822deb in StartChildProcess (type=StartupProcess) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/postmaster/postmaster.c:4512
#9  0x00007f3d9b8256ac in PostmasterMain (argc=argc@entry=5, argv=argv@entry=0x7f3d9d614180) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/postmaster/postmaster.c:1118
#10 0x00007f3d9b67892f in main (argc=5, argv=0x7f3d9d614180) at /home/cbe/projects/postgresql/9.1/postgresql-9.1-9.1.12/build/../src/backend/main/main.c:209

A: After googling for hours, I stumbled across a thread that wasn't really related to my issue, best I could tell, but it seemed harmless enough to try, and voilà!
I looked at /var/lib/postgresql/9.1/main/pg_clog, and saw:
drwx------  2 postgres postgres   4096 Mar 15 15:20 .
drwx------ 13 postgres postgres   4096 Mar 25 12:15 ..
-rw-------  1 postgres postgres 262144 Feb  4 19:39 0000
-rw-------  1 postgres postgres 262144 Feb 13 11:10 0001
-rw-------  1 postgres postgres 262144 Mar 15 15:20 0002
-rw-------  1 postgres postgres 229376 Mar 25 14:51 0003

Noticing that /var/lib/postgresql/9.1/main/pg_clog/0003 was the file being opened/seeked in the strace output, and that this was the file in question in the forum post, I tried the suggested action in the forum:
dd if=/dev/zero bs=8k count=1 >> /var/lib/postgresql/9.1/main/pg_clog/0003

And now postgres starts again.