text:
Q: Creating Named Pipe Error I am creating a named pipe and using a function to do so. Here is the code:
HANDLE              tProviderPipe(INVALID_HANDLE_VALUE);
SECURITY_ATTRIBUTES tSecurityAttributes;

tSecurityAttributes.nLength = sizeof(tSecurityAttributes);
tSecurityAttributes.bInheritHandle = FALSE;
tSecurityAttributes.lpSecurityDescriptor = NULL;
while (1)
{
    tProviderPipe = ::CreateNamedPipe(L"\\\\.\\pipe\\MyPipe",
                                      PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                                      PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
                                      1,
                                      128,
                                      128,
                                      5000,
                                      &tSecurityAttributes);

    if (INVALID_HANDLE_VALUE != tProviderPipe)
    {
        DWORD lLastStatus(GetLastError());
        OHTRACE(Trace::eTAlways, L"Pipe Status: " << (unsigned int)lLastStatus);
        break;
    }
    if (ERROR_PIPE_BUSY != GetLastError())
    {
        DWORD lLastStatus(GetLastError());
        OHTRACE(Trace::eTAlways, L"Pipe Status: " << (unsigned int)lLastStatus);
        break;
    }
    if (!WaitNamedPipe(L"MyPipe", 20000))
    {
        DWORD lLastStatus(GetLastError());
        OHTRACE(Trace::eTAlways, L"WPipe Status: " << (unsigned int)lLastStatus);
    }

When this function is called the pipe creation fails with error code 231 (i.e Pipe busy). I don't understand why the pipe is busy and what is the correct way to create pipe? What should be the post checks and pre-checks before going forward to creating a pipe?

A: The code you showed is all wrong.
This check:
if (INVALID_HANDLE_VALUE != tProviderPipe)

Needs to use == instead of !=. Your code is failing if CreateNamedPipe() succeeds.
This check:
if (ERROR_PIPE_BUSY != GetLastError())

Needs to be removed. First, it is in the wrong place. GetLastError() is only valid if CreateNamedPipe() fails. After making the == fix above, then GetLastError() will never be ERROR_PIPE_BUSY (or any other meaningful value) after CreateNamedPipe() succeeds. Second, if you move it into the if that is checking tProviderPipe then it becomes redundant since it is logging the same info that is already being logged there.
This check:
if (!WaitNamedPipe(L"MyPipe", 20000))

Also needs to be removed. First, you are passing it the wrong pipe name format. Second, it is intended for a named pipe client to call before calling CreateFile() (or if CreateFile() fails with ERROR_PIPE_BUSY). Do not call it in your named pipe server.  You meant to call ConnectNamedPipe() instead, which waits for a client to connect to the server pipe you are creating.
Please look at the named pipe server examples on MSDN.
Try something more like this instead:
HANDLE tProviderPipe = INVALID_HANDLE_VALUE;
SECURITY_ATTRIBUTES tSecurityAttributes;
OVERLAPPED ov = {};
DWORD lLastStatus;

ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!ov.hEvent) {
    lLastStatus = GetLastError();
    OHTRACE(Trace::eTAlways, L"Pipe Event Create Error: " << (UINT)lLastStatus);
    return;
}

tSecurityAttributes.nLength = sizeof(tSecurityAttributes);
tSecurityAttributes.bInheritHandle = FALSE;
tSecurityAttributes.lpSecurityDescriptor = NULL;

while (1) {
    if (INVALID_HANDLE_VALUE == tProviderPipe) {
        tProviderPipe = ::CreateNamedPipe(L"\\\\.\\pipe\\MyPipe", PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 128, 128, 5000, &tSecurityAttributes);
        if (INVALID_HANDLE_VALUE == tProviderPipe) {
            lLastStatus = GetLastError();
            OHTRACE(Trace::eTAlways, L"Pipe Create Error: " << (UINT)lLastStatus);
            break;
        }
    }

    if (!ConnectNamedPipe(tProviderPipe, &ov)) {
        lLastStatus = GetLastError();
        if (ERROR_IO_PENDING == lLastStatus) {
            if (WaitForSingleObject(ov.hEvent, 20000) != WAIT_OBJECT_0) {
                OHTRACE(Trace::eTAlways, L"Pipe not connected in 20 seconds");
                break;
            }
        }
        else if (ERROR_PIPE_CONNECTED != lLastStatus) {
            OHTRACE(Trace::eTAlways, L"Pipe Connect Error: " << (UINT)lLastStatus);
            continue;
        }
    }

    // use tProviderPipe as needed ...

    DisconnectNamedPipe(tProviderPipe);
}

if (INVALID_HANDLE_VALUE != tProviderPipe) {
    CloseHandle(tProviderPipe);
}

CloseHandle(ov.hEvent);


text:
Q: How to use PowerShell to remove spaces after ID's listed in a .csv using Powershell I have a CSV that is manually updated occasionally with ID's of users here at work. I have code that does a compare on the list but some of the ID's have spaces after them so they aren't matching.
How do I do a data integrity check on this CSV to make sure only the ID names are listed? In other words remove all the spaces.

A: The .trim() string method will remove starting or trailing spaces. There is also a .trimend() method for only trailing.
$TrimmedCSV = Import-CSV C:\example.csv | ForEach-Object {$_.ID = $_.ID.Trim(); $_}
$TrimmedCSV | Export-CSV C:\example.csv -NoTypeInformation

Likewise as Matt mentions, there is also .trimstart(). You can also trim characters besides space. For example, .trim('a').

A: You can compare after stripping the spaces very easily:
(" SAM 500 " -replace ' ', '') -eq "SAM500"

Or, without seeing your code probably closer to:
($User -replace ' ','') -eq $oldId

Alternatively, (as mentioned) if you need to preserve some spaces, but ensure leading and trailing spaces are removed, use .Trim()
$NewName.Trim() -eq $prviousName

Or if you want to get a little creative, you could also use -Match and regex:
$newName -match "\s+(\b$oldName\b)+\s+"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery change and control color on load and scroll I need to check the background-color of the menu (#main-header) that must be equal to the color of the section (.section)when the page is loaded and when  scrolled, for now I only manage the scroll event.
When the page has been loaded the background-color of the menu is different from the background-color of the section.
JSFiddle: https://jsfiddle.net/stellac/w8xbzmne/3/
This is my code:
    <script type="text/javascript">
    jQuery(function($)
    {
        $(window).scroll(function ()
        {
            if ($('.section').css('background-color') === '#fff') {
                $('#main-header').css('background-color','#fff');
            } else {
                $('#main-header').css('background-color','#001a22');
            }
        });
    });
</script>

A: You can create a function which takes care of changing the color and call that function on page load and in scroll event. So try something like this
jQuery
jQuery(function($) {
  changeColor();      //calling on page load
  $(window).scroll(function() {
    changeColor();    // calling in scroll event
  });
});

function changeColor() {
  if ($(".section").css("background-color") === "#fff") {
    $("#main-header").css("background-color", "#fff");
  } else {
    $("#main-header").css("background-color", "#001a22");
  }
}


text:
Q: Retrieve SQL Server database from old Windows I have just changed my Windows. In the old SQL Server, I had some important databases and I want to find and copy them to new installed windows and SQL Server.
How can I find and copy old databases from old windows and copy them to new SQL Server?

P.S: Actually, my I have changed my hard disk and all of the old files
  is located on my old hard drive and I want to find and copy the old
  server from old hard drive to new drive.

A: Make sure your database engine is running. Connect to your old server using SSMS (SQL Server Management Studio) and backup the database. Then transfer the backup file to the new system and restore the backup using SSMS again.

A: You can either backup the prior database or detach the database .mdf (data) and .ldf (log) file and reattach via http://blog.sqlauthority.com/2007/08/24/sql-server-2005-t-sql-script-to-attach-and-detach-database/
or
Backup your database and restore. Six of one, half dozen of the other.

-- Step 1 : Detach Database using following script
USE [master]
 GO
EXEC MASTER.dbo.sp_detach_db @dbname = N'AdventureWorks',
@keepfulltextindexfile = N'true'
GO
-- Step 2 : Move Data files and Log files to new location
 -- Do this step and move to Step 3
 --  Step 3 : Attach Database using following script
USE [master]
 GO
CREATE DATABASE [AdventureWorks] ON
( FILENAME = N'C:\Data\AdventureWorks_Data.mdf' ),
 ( FILENAME = N'C:\Data\AdventureWorks_Log.ldf' )
FOR ATTACH
 GO
IF EXISTS ( SELECT name
FROM MASTER.sys.databases sd
WHERE name = N'AdventureWorks'
AND SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() )
EXEC [AdventureWorks].dbo.sp_changedbowner @loginame=N'sa',
@map=false
 GO

Create a Full Database Backup
There are other options as well (Red Gate tools, Visual Studio Tools, etc)


text:
Q: Unbounded convex real functions Let $f$ be a real function defined on $[1, +\infty)$ and convex from a number on.
Is it true that the sequence $f_n:=f(n)$ is unbounded?

A: The answer is no. Indeed, choose a constant function $f(x)=1$ for all $x\in[1,+\infty]$. It is convex and bounded.


text:
Q: AJAX returns Error (ASP.NET MVC) I try to pass data to controller via AJAX
Here is script
 <script>
    $('.click').on('click', function () {
        $('.content').toggle();
    });
    var counter = 0;
  $(document).ready(function () {
        $('#save').click(function () {
            save();
        });
    });
    function save()
    {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: { question1: $('#question1').val(),
                    question2: $('#question2').val(),
                    question3: $('#question3').val(),
                    question4: $('#question4').val(),
                    question5: $('#question5').val(),
                    question6: $('#question6').val(),
                    question7: $('#question7').val(),
                    question8: $('#question8').val(),
                    question9: $('#question9').val(),
                    question10: $('#question10').val()
            },
            url: '@Url.Action("Index", "Questions")',
            success: function (da) {
                if (da.Result === "Success") {
                    alert('saved sucessfully');

                } else {

                    alert( 'Error'+ da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
}

</script>

Here is controller
  [HttpPost]
    public ActionResult Index(string question1, string question2, string question3, string question4, string question5, string question6, string question7, string question8, string question9, string question10)
    {
        QuestionBlock question = new QuestionBlock
        {
            Question1 = question1,
            Question2 = question2,
            Question3 = question3,
            Question4 = question4,
            Question5 = question5,
            Question6 = question6,
            Question7 = question7,
            Question8 = question8,
            Question9 = question9,
            Question19 = question10,

        };
        db.QuestionBlocks.Add(question);
        db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
    }

But when I run function on button click I have this error in console
Failed to load resource: the server responded with a status of 500 (Internal Server Error) and Controller name. Also alert says Error

Where is may be trouble?
I think I pass data correctly to controller


text:
Q: Oracle: Select Milliseconds from Timestamp Type that Defaults with SYSTIMESTAMP I have a column with TIMESTAMP type in my Oracle Database. The default column value is SYSTIMESTAMP.
I want to SELECT milliseconds FROM the TIMESTAMP column. I use the query below without success:
SELECT TO_CHAR (MY_TIMESTAMP, 'dd-mm-yyyy hh24:mi:ss.FF') AS MY_TIMESTAMP
FROM MY_TABLE

-- Result: 20-12-2015 15:23:28.

As you see the result does not have any milliseconds and it is empty. If I change the query with .FF4 then it results .0000.
How can I SELECT the column with milliseconds?

A: The precision for timestamp columns can be set up by
TIMESTAMP [(fractional_seconds_precision)].
In your case for 4 it's:
create table my_table
(id number,
  my_TIMESTAMP timestamp(4) default SYSTIMESTAMP);

You can check your current precision by:
select column_name, data_scale from user_tab_columns
where table_name = 'MY_TABLE' and column_name = 'MY_TIMESTAMP';

Here is sample in SQL Fiddle
The display can be change by:
 alter session set NLS_TIMESTAMP_FORMAT = 'DD-MON-RRRR HH:MI:SS.FF9';


text:
Q: How to add a picture on video using movie15 package or media9 or multimedia package(s) on LinuxOS I have been experimenting with the sample of code from LaTeX beamer presentation. At this point let me clarify that I know that this is a deprecated module and that I should be using media9 and not movie15, but I have spend 2 days trying to make it work with all these configurations but none of the sample of codes that I found online worked for me e.g. How to include multimedia files in beamer or Embedding Videos in LaTeX Beamer or Using media9 to include videos files or Video in a Presentation etc...etc...so I gave up on the idea and switched to the deprecated module.
Sample of working code from LaTeX beamer presentation slightly modified:
\documentclass{beamer}
\usepackage[3D]{movie15}
\usepackage[UKenglish]{babel}
\usepackage{lmodern}
% \usepackage{hyperref} % update based on comments
\usepackage{graphicx}

%% See: http://en.wikibooks.org/wiki/LaTeX/Presentations
%% See: http://www.hartwork.org/beamer-theme-matrix/
\usetheme{Copenhagen}
\usecolortheme{beaver}

\hypersetup{
  pdfauthor={Thanos},
  pdftitle={Simple Beamer Class},
  pdfsubject={Subject},
  pdfkeywords={Key} {Words} {List},
  urlcolor=blue,
}
\author{Thanos} % updating based on comments

\begin{document}
\title{Simple Beamer Class}
% \author{Thanos}
\date{\today}
\frame{\titlepage}
\frame{\frametitle{Table of contents}\tableofcontents}

\section{Movie}
\frame{\frametitle{Pymol Movie object}

\begin{figure}[!htb]
\centering
\includemovie[
poster,
toolbar, %same as `controls'
text={\includegraphics[width=0.8\textwidth]{samplePicture.eps}}
% text={\phantom{\includegraphics[width=0.8\textwidth]{samplePicture.eps}}} % update based on comments
]{10cm}{6cm}{SampleVideo.mp4}
\caption{A PyMOL movie object embedded in PDF, using mpg format.}
\label{mov:ex3d}
\end{figure}
}

\section{Lists}
\subsection{Lists I}
\frame{\frametitle{Unnumbered lists}
\begin{block}{My bloc}
test of bloc
\end{block}

\begin{itemize}
\item Introduction to  \LaTeX
\item Beamer class
\end{itemize}
}
\end{document}

My question is how to add a picture on the video. Based on the documentation of the package The movie15 Package page 6 shows that we can add a picture with the following part text={\phantom{\includegraphics[scale=2]{path/to/poster}}}.
After compiling the code is working and the video is playing but the picture is not displayed is there any workaround this problem?
A minor note to make here, I am also getting this error:
hyperref: Option 'pdfauthor' has already been used,
I searched online and I found this thread The \titlepage problem in beamer, the proposed solution did not work for me, or How to get rid of those beamer warnings, or Errors with Beamer not understandable. This is not something important I know this is only a warning but since I am asking the question why not trying to resolve all of my questions.
Update:
I forgot to include my Latex version:
$ pdflatex --version
pdfTeX 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian)
kpathsea version 6.2.3
Copyright 2017 Han The Thanh (pdfTeX) et al.
There is NO warranty.  Redistribution of this software is
covered by the terms of both the pdfTeX copyright and
the Lesser GNU General Public License.
For more information about these matters, see the file
named COPYING and the pdfTeX source.
Primary author of pdfTeX: Han The Thanh (pdfTeX) et al.
Compiled with libpng 1.6.29; using libpng 1.6.29
Compiled with zlib 1.2.8; using zlib 1.2.8
Compiled with poppler version 0.41.0

Update2
Adding video.log file, download here (video.log).
Update3
Sample of output based on comment (removing \phantom).

Update4
Sample of code for package media9:
\listfiles
\documentclass{beamer}
\usepackage{media9}
\usepackage[UKenglish]{babel}
\usepackage{lmodern}
\usepackage{graphicx}

%% See: http://en.wikibooks.org/wiki/LaTeX/Presentations
%% See: http://www.hartwork.org/beamer-theme-matrix/
\usetheme{Copenhagen}
\usecolortheme{beaver}

\hypersetup{
  pdfauthor={Thanos},
  pdftitle={This is the title},
  pdfsubject={Pdf Subject},
  pdfkeywords={Key} {Words} {List},
  urlcolor=blue,
}

\begin{document}

\title{Sample of media9 attempt}
\date{\today}
\frame{\titlepage}
\frame{\frametitle{Table of contents}\tableofcontents}

\section{Movie}
\frame{\frametitle{Movie using media9}

\begin{figure}[!htb]
\includemedia[
  %activate=onclick, % default
  addresource=sampleVideo.mp4,
  flashvars={
    source=sampleVideo.mp4
    &autoPlay=true % start playing on activation
    &loop=true
  },
  passcontext %show player's right-click menu
]{\includegraphics[height=0.45\linewidth]{samplePicture.eps}}{VPlayer9.swf}
\caption{A media9 package movie embedded in PDF, using mp4 format.}
\label{mov:ex3d}
\end{figure}
}
\end{document}

Adding video.log file, download here (videoMedia9.log).

A: Based on AlexG guidance and expertise he helped me to understand that okular is not enough to play multimedia from media9. Proposed solution with Adobe Reader unix 9.4.1 unfortunately for me is not working.
Output of not loading the video from sample of code provided above with media9 package:

So the only solution that worked for my simple requirements is to use \usepackage{multimedia}.
Sample of working code:
\documentclass{beamer}
\usepackage{graphicx}
\usepackage{multimedia}
\usepackage{lmodern}
% \usepackage[UKenglish]{babel}
% \usepackage{graphicx}

%% See: http://en.wikibooks.org/wiki/LaTeX/Presentations
%% See: http://www.hartwork.org/beamer-theme-matrix/
\usetheme{Copenhagen}
\usecolortheme{beaver}

\hypersetup{
  pdfauthor={Thanos},
  pdftitle={This is the title},
  pdfsubject={Pdf Subject},
  pdfkeywords={Key} {Words} {List},
  urlcolor=blue,
}

\begin{document}
  \title{Sample of multimedia attempt}
  \date{\today}
  \frame{\titlepage}
  \frame{\frametitle{Table of contents}\tableofcontents}

  \section{Movie}
    \begin{frame}{Movie using media9}
      \begin{figure}[!htb]
        \movie[label=show3,%
               width=1.0\textwidth,%
               poster,%
               % autostart,%
               showcontrols,%
               % loop,%
              ]{\includegraphics[width=1.0\textwidth]
               {samplePicture.eps}}
               {sampleVideo.mp4}
        \caption{A media9 package movie embedded in PDF, using mp4 format.}
      \end{figure}
    \end{frame}
    \label{mov:show3}
\end{document}

Similar question that the solution has been accepted with media9 package Did anyone succeed in playing embedded movies inside Acrobat in Linux? maybe for someone else the sample of code might work.


text:
Q: How to save JSON string into CSV or TXT in Python? In Python how to save the following JSON string into CSV file?
{
'1.txt': [],
'2.txt': [],
'5.txt': [],
'4.txt': ['3.txt','6.txt'],
'7.txt': ['8.txt']
}

The important thing is that I want to save only numbers of those entries that have children, i.e. for the above example the result would be:
4
3
6
7
8

This is what I prepared so far, but I don't know how to check for nested elements:
    x = json.loads(data)

    f = csv.writer(open("test.csv", "wb+"))

    # Write CSV Header
    f.writerow(["number"])

    for x in x:
            f.writerow([x[...]])

A: Just check if the list is empty or not iterating of the items in the dict:
for k, v in d.items():
    if v: # will be False for any empty list
        print(k.split(".")[0])
        print([s.split(".")[0] for s in v])
7
['8']
4
['3', '6']

Depending on what output you want:
f = csv.writer(open("test.csv", "w"))

# Write CSV Header
f.writerow(["name", "qty"])

for k, v in d.items(): # iteritems python2
    if v:
        f.writerow([k.split(".")[0]]+[s.split(".")[0] for s in v])

Which outputs:
name,qty
7,8
4,3,6

If you want all on separate lines:
with open("test.csv","w") as f:
    f.write("name\n")
    for k, v in d.items():
        if v:
            f.write("{}\n".format(k.split(".")[0]))
            f.write("\n".join([s.split(".")[0] for s in v])+"\n"

Output:
name
7
8
4
3
6

To use the csv module you would need to wrap the subelements in lists or some container:
with open("test.csv","w") as f:
    wr = csv.writer(f)
    wr.writerow(["name"])
    for k, v in d.items():
        if v:
            wr.writerow([k.split(".")[0]])
            wr.writerows([[s.split(".")[0]] for s in v])

A: This should be working:
data = {
    '1.txt': [],
    '2.txt': [],
    '5.txt': [],
    '4.txt': ['3.txt','6.txt'],
    '7.txt': ['8.txt']
}
f = csv.writer(open("test.csv", "wb+"))
f.writerow(["name", "qty"])
for key, value in data.iteritems():
    if len(value) > 0:
        f.writerow([key, len(value)])


text:
Q: Converse of Schur complement positive definiteness Let $$A=\begin{bmatrix}A_{11}&A_{12}\\A_{21}&A_{22}\end{bmatrix} \text{be hermitian}$$
Given: $A_{11} $ and $A_{22}-A_{21}A_{11}^{-1}A_{12}$ are both positive definite, then show that $A$ is positive definite.
Since $A$ is hermitian $A_{11}^*=A_{11}, \; A_{22}^*=A_{22}, \;A_{12}^*=A_{21}\;\; ->>(1)$
Let $$B=\begin{bmatrix}A_{11}&0\\0&A_{22}-A_{21}A_{11}^{-1}A_{12}\end{bmatrix}$$
Let $U^*=\begin{bmatrix}I&0\\-A_{21}A_{11}^{-1}&I\end{bmatrix}$
Then, using $(1)$, please verify that
$U^*AU=B$
How can I make use of this to prove that $A$ is also positive definite?

A: Let us first check that $S$ has hermitian symmetry :
$$S^*=A_{22}^*-(A_{21}A_{11}^{-1}A_{12})^*=A_{22}-(A_{12}^*(A_{11}^{-1})^*A_{21}^*)=$$
$$=A_{22}-(A_{21}(\underbrace{A_{11}^{*}}_{A_{11}})^{-1}A_{12})=S.\tag{1}$$
(please note that we have used the fact that the inverse of a transpose-conjugate is the transpose-conj. of the inverse).
$B$ is positive definite because its eigenvalues are the union of

*

*those of $A_{11}$ which are real positive, because  $A_{11}$ is symmetric definite positive with hermitian symmetry, and

*those of $S:=A_{22}-A_{21}A_{11}^{-1}A_{12}$, all of them being as well $>0$ for the same reason ($S$ is assumed positive definite and we just verified in (1) that it has hermitian symmetry).
Besides, a consequence of conjugation relationship $U^*AU=B$ is that $A$ and $B$ have the same (positive !) eigenvalues.
Therefore, $A$, having all its eigenvalues $>0$ is (symmetric) positive definite.


text:
Q: How to make a standalone program in ChucK audio programming language? How do I make a standalone executable application (desktop, on server or mobile apps) in Chuck?

A: I'm not sure what you are trying to do but two things ...

*

*If you need ChucK to run on another system, just load it.

*I you are looking to share your composition, there is a function to write the output to an external file in some audio format such as .wav. That file can be replayed on any other system of you choice. Of course, it'll also play from a web site.
Basically there is no "standalone" ChucK system other than the entire system.

A: You can't make a runnable app/patch like you can with MaxMSP at the moment. The simplest solution is to just download the MiniAudicle IDE. It comes bundled with a version of ChucK so you can skip over all the command-line stuff.

A: If you want to make an app for PureData for example, you will need to use libPd to use PureData objects inside your app.
For Chuck you can try to use libChuck, or use Chuck sources in your C++ app.


text:
Q: strategy for syncing Android app database with a remote API I'm developing an Android app that is a client to a remote JSON webservice API (I built the server so I have maximum flexibility).
I'm trying to decide what is a good strategy (in terms of battery life, bandwidth and wait times) to keep a local SQLite database synced with the remote API.
what I'm currently thinking is that the server will notify the Android app via GCM about any action (either new data that should be fetched or old data that should be updated),
also, the user will have a refresh button to manually do the sync.
cons of this approach is that if the GCM message is "lost" there is no way to know about any updates or new data.
I can add timestamps and check for new data whenever the user asks to view something but this doesn't solve the way to determine when older data that's already in the SQLite database need to be refreshed.
any suggestions for improving this syncing strategy or any other approaches I should look into ?

A: You could have the app send a received acknowledgement to the server when it gets the GCM push.  Then, if the server doesn't see an acknowledgement in X timeframe, it could resend the GCM push.


text:
Q: Mi lista desplegable se cierra una vez hago click en ella Recientemente cree una función que se encarga de eliminar un elemento de mi lista desplegable (de notificaciones), pero cuando hago click dentro de la ventana esta se cierra, agradecería algún tipo de ayuda o información para evitarlo. A continuación el código de JS:
clearNotification(idx) {
    this._notificationsService.markNotificationsAsReaded(this.notification)
       .then(res=>{
            this._notificationsService.deleteNotific(res)
       })
}

y este es el codigo HTML:

Agradezco cualquier tipo de ayuda.


text:
Q: Dedekind ring in the complete discrete valued field Let $ K $ be a complete discrete valued field and $ A \neq K $ be a subring of $ K $. When $ A $ is a Dedekind ring, is $ A $ a DVR?
For the integral domain $ R $, the following are equivalent:
(1) $ R $ is a Dedekind ring.
(2) $ R $ is a field or a one-dimensional noetherian normal ring.
(Here, the ring in which the localization by each prime ideal becomes the integral domain is called the normal ring.)
Therefore, $ A $ in my question is a one-dimensional noetherian normal ring.
For the ring $ R $, the following are equivalent:
(1) $ R $ is a DVR.
(2) $ R $ is a one-dimensional noetherian normal ring and a local ring.
From the above, I would like to show that $ A $ in my question is a local ring.


text:
Q: MATLAB: Printing comparative columns for elements from different vectors I´m trying to printing comparative columns to compare elements with the same index of two or three differents vector.
I will illustrate my question with the next example
>> a = [5.47758 7.46578 3.45323]
a =

5.4776    7.4658    3.4532

>> b = [5.65432 4.45678 2.34789]

b =

5.6543    4.4568    2.3479

Now if I write
>> sprintf('%.2f %.2f\n',a, b)

I get the following response from Matlab
ans =
5.48 7.47
3.45 5.65
4.46 2.35`

But what the way I would like to see this presentation of values is this
ans =
5.48 5.65
7.47 4.46
3.45 2.35

How can I use the function sprintf (or other function or way) to get the above representation?
Thank you.

A: You can fix this problem by concatenating a and b into one 2-by-3 matrix input argument:
>> sprintf('%.2f %.2f\n',[a; b])

ans =

5.48 5.65
7.47 4.46
3.45 2.35

The SPRINTF function works by reusing the formatting string over and over as it traverses (in column order) the elements of each of the input arguments in the order they are entered. That's why in your example all the values of a get printed, then all the values of b, instead of interleaving the values of a and b.

A: If you are just "printing" it on the screen, you could type on the MATLAB Console (or "Command Window"):

a = [5.47758 7.46578 3.45323];
b = [5.65432 4.45678 2.34789];

c = [a',b']; % Transposing each row vector into a column vector before forming a matrix

c =

    5.4776    5.6543
    7.4658    4.4568
    3.4532    2.3479

This will make it easier when you sort the matrix by rows, for example, using the command 'sortrows' (See the doc on 'sortrows' for its usage: "help sortrows" or "doc sortrows").


text:
Q: The performance of the HashMap in JAVA8 I had a question when I learned the HashMap source code in java8。
Source code is so complicated, how much efficiency?
So I wrote a code about the hash conflict。
public class Test {
    final int i;

    public Test(int i) {
        this.i = i;
    }

    public static void main(String[] args) {
        java.util.HashMap<Test, Test> set = new java.util.HashMap<Test, Test>();
        long time;
        Test last;
        Random random = new Random(0);
        int i = 0;
        for (int max = 1; max < 200000; max <<= 1) {
            long c1 = 0, c2 = 0;
            int t = 0;
            for (; i < max; i++, t++) {
                last = new Test(random.nextInt());
                time = System.nanoTime();
                set.put(last, last);
                c1 += (System.nanoTime() - time);
                last = new Test(random.nextInt());
                time = System.nanoTime();
                set.get(last);
                c2 += (System.nanoTime() - time);
            }
            System.out.format("%d\t%d\t%d\n", max, (c1 / t), (c2 / t));
        }
    }

    public int hashCode() {
        return 0;
    }

    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (!(obj instanceof Test))
            return false;
        Test t = (Test) obj;
        return t.i == this.i;
    }
}

I show the results in Excel。
enter image description here
I am using java6u45 java7u80 java8u131。
I do not understand why the performance of java8 will be so bad
I'm trying to write my own HashMap.
I would like to learn HashMap in java8 which is better, but I did not find it.

A: Your test scenario is non-optimal for Java 8 HashMap.  HashMap in Java 8 optimizes collisions by using binary trees for any hash chains longer than a given threshold.  However, this only works if the key type is comparable.  If it isn't then the overhead of testing to see if the optimization is possible actually makes Java 8 HashMap slower.  (The slow-down is more than I expected ... but that's another topic.)
Change your Test class to implement Comparable<Test> ... and you should see that Java 8 performs better than the others when the proportion of hash collisions is large enough.

Note that the tree optimization should be considered as a defensive measure for the case where the hash function doesn't perform.  The optimization turns O(N) worst-case performance to O(logN) worst-case.
If you want your HashMap instances to have O(1) lookup, you should make sure that you use a good hash function for the key type.  If the probability of collision is minimized, the optimization is moot.

Source code is so complicated, how much efficiency?

It is explained in the comments in the source code.  And probably other places that Google can find for you :-)


text:
Q: Null Pointer exception in Processing in Array. Tried everything I am  making a 2d side scrolling game and I'm stuck. Im writing the class for the objects which will spawn increasingly and which the Player has to avoid. But sadly I am getting a Nullpointerexception and I cannot figure out why.Before I cleaned up the code in the main and transformed it to a class, the whole thing was working. I think I'm initializing the Array correctly and no variables are left undefined. I've only been using processing for the past months so I might have overseen something.
Thanks a lot for your help
 public class Blockfield {
    private int Blockcount;
    private PImage Blockpic;
    private Block block[];

  //Constructor
  public Blockfield (int Blockcount) {
    this.Blockcount = Blockcount;
    //new array
    block = new Block [Blockcount];
    for ( int i=0; i < Blockcount; i++) {
      block[i] = new Block( width+Blockpic.width, random (height));
    }
  }

  //Draw method for this class
  public void draw () {
    for (int i =frameCount/100; i >0; i--) {
      image ( Blockpic, block[i].x, block[i].y);
      //moves blocks right to left
      block[i].x -=7 ;
      //spawns block when they leave the screen
      if (block[i].x < 0) {
        block[i] = new Block( width+Blockpic.width, random (height));
      }
    }
  }
}

class Block {
float x, y;

Block ( float x, float y) {
this.x= x;
this.y= y;
}
}

Main:
Blockfield blockfield;
PImage Blockpic;

void setup () {
  size (1291, 900);
  blockfield = new Blockfield(100);

  Blockpic = loadImage("block2.png");
}

void draw () {
  background ( 10);

}

A: The problem was that I was trying access Blockpic.width in your Blockfield constructor before Blockpic had been assigned. The solution was to load the Image within the constructor of the class.
Working code:
public class Blockfield {
    private int Blockcount;
    private PImage Blockpic;
    private Block block[];

  //Constructor
  public Blockfield (int Blockcount) {
    this.Blockcount = Blockcount;
    Blockpic = loadImage("block2.png");
    //new array
    block = new Block [Blockcount];
    for ( int i=0; i < Blockcount; i++) {
      block[i] = new Block( width+Blockpic.width, random (height));
    }
  }

  //Draw method for this class
  public void draw () {
    for (int i =frameCount/100; i >0; i--) {
      image ( Blockpic, block[i].x, block[i].y);
      //moves blocks right to left
      block[i].x -=7 ;
      //spawns block when they leave the screen
      if (block[i].x < 0) {
        block[i] = new Block( width+Blockpic.width, random (height));
      }
    }
  }
}

class Block {
float x, y;

Block ( float x, float y) {
this.x= x;
this.y= y;
}
}

Thanks to everyone for the help!!!


text:
Q: sed removing text after character not always working So I have been using the following general syntax to be able to remove text on a line within a configuration file after the '=' sign:
sed -i 's|\(.*\txt_to_remove=\).*|\1|g' file.txt

Let's say I have a text file:
$ cat tmp.txt
datee='10'
alter='purple'
hr='green'
new_val='100'

and if I consecutively use the command I provided above to try and delete everything after '=':
sed -i 's|\(.*\datee=\).*|\1|g' tmp.txt
sed -i 's|\(.*\alter=\).*|\1|g' tmp.txt
sed -i 's|\(.*\hr=\).*|\1|g' tmp.txt
sed -i 's|\(.*\new_val=\).*|\1|g' tmp.txt

The results will be:
$ cat tmp.txt
datee=
alter='purple'
hr=
new_val='100'

The question is, why did the commands not work for the 'alter' or 'new_val', and what can be done to make sure that it always works for each individual instance of using the command?

A: Do them all at once with:
sed -i 's/^\(\(datee\|alter\|hr\|new_val\)=\).*/\1/g' tmp.txt

A: try this sed expression sed 's/=.*//'
I tried and got the desired results
cat tmp.txt | sed 's/=.*//'
datee
alter
hr
new_val

A: You have a backslash before the keyword that you want to replace. Backslash is the escape prefix, and \a and \n are escape sequences, so they don't match what's in the file.
Get rid of these backslashes.
sed -i 's|\(.*datee=\).*|\1|g' tmp.txt
sed -i 's|\(.*alter=\).*|\1|g' tmp.txt
sed -i 's|\(.*hr=\).*|\1|g' tmp.txt
sed -i 's|\(.*new_val=\).*|\1|g' tmp.txt


text:
Q: How to run Say "something" in background in AppleScript I would like to have AppleScript code like this:
row 1
say "some long text here"
row 3

When it starts to speak text, it same time continues to row 3.
I create my scripts in AppleScript Editor and i don't know enough about process control on OS X to understand backgrounding yet.

A: Like this
say "some long text here" without waiting until completion

A: You can do this by getting Terminal to run the line of AppleScript:
set myscript to "say \"some long text here\""
ignoring application responses
  tell application "Terminal"
    do script "osascript -e " & quoted form of myscript
  end tell
end ignoring


text:
Q: Facebook manual authentication flow with Nodejs I'm trying to manually implement an authentication flow via FB oauth.
Here I call the authorization dialog:
Login FB

Then it redirects back to my app server:
http://localhost:3000/login/callback?code=XXXXXXXXXXXXXXXXX

That calls the FB API graph to exchange the code for an access token
function exchangeCodeForAccessToken(code) {
    const options = {
      hostname: 'graph.facebook.com',
      path: 'v2.11/oauth/access_token?client_id=XXXXXXXXXXXXXXXXX&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Flogin%2Fcallback&client_secret=YYYYYYYYYYYYYYYYYYYY&code=' + code,
      method: 'GET'
    };
    const req = https.request(options, (res2) => {
      console.log(`STATUS: ${res2.statusCode}`);
      res2.on('data', (d) => {
        console.log(d);
      });
    });
    req.end();
  }

But here I always get a 400 with no other indication. No matter what I change. Any advice?
Thank you
edit. As suggested by CBroe I tried to execute the very same request from browser right after the node request (same url, same querystring, same code):
node -> 400
browser -> 200 + AccessToken

A: I found the solution. Simply put protocol 'https' in the host property.


text:
Q: SQL How to display highest value of counter of x by distinct y Let's say I have the following table:

customer
country
city

John
UK
London

Jeremy
UK
London

Steven
UK
Manchester

Paul
USA
Detroit

Jorge
Brazil
Sao Paolo

Antonio
Brazil
Sao Paolo

I want the table to show me all customers from the city with the most orders in a given country, so for example for the chart above I wouldn't get Steven's value because London has more orders than Manchester within U.K
I would also like the table to show me how many customers are from that given city
and so I would like to get...

customer
country
city
ctr

John
UK
London
2

Jeremy
UK
London
2

Paul
USA
Detroit
1

Jorge
Brazil
Sao Paolo
2

Antonio
Brazil
Sao Paolo
2

thx for the help

A: Three steps are needed:

*

*count the number of rows per country and city

*get the maximum count for each country

*only keep rows the count of which matches their country's maximum count

The query:
select
  customer, country, city, cnt
from
(
  select
   customer, country, city, cnt,
   max(cnt) over (partition by country) as max_cnt
  from
  (
    select
      customer, country, city,
      count(*) over (partition by country, city) as cnt
    from mytable
  ) counted
) counted_with_max
where cnt = max_cnt;


text:
Q: Rails click event not working What I am trying to accomplish is that the user can select one of the items in the list group and ill be able to get returned which one it is along with making the item active in the group. I can't seem to get it working with jquery, or I am not doing this correctly.
Any feedback/help is appreciated.
Here is the HAML Code
= form_for @editor do |f|
  %body
   .container
    .list-group
      %a.list-group-item.active Hello
      %a.list-group-item Hey
      %a.list-group-item Greetings

I made a js file called editors.js
$(document).ready(function() {
 $(".list-group-item").live('click', function(){
  $('.active').removeClass('active');
  $(this).addClass('active');
 });
});

A:

$(document).on("click", ".list-group-item", function(){
  $(this).addClass('active')
    .siblings('.active')
    .removeClass('active');
});
.active {
  color: red;
}

  Hello
  Hey
  Greetings

  Bye
  Adios
  Auf Wiedersehen

This also makes it idempotent and turbolinks compatible by delegating from the document instead of attaching the handler to a DOM node.


text:
Q: Display error using google maps tile server and Google Maps utility in PHP I have a question regarding Map tile server and coordinates conversion in Google Maps using the Google Maps Utility library.
My tile server accesses a database with thousands of gps coordinates (lat,lng), and for every (lat,lng) point, checks if the point is inside the geographical bounds of the tile; if it does, coordinates conversion (WGS84 -> Mercator -> X,Y offset inside the tile) and paints the corresponding pixel inside the tile, using the GoogleMapsUtility Library.
In terms of code, I do the following:
$point = GoogleMapUtility::getOffsetPixelCoords((float)$row['lat'], (float)$row['lng'], $zoom, $X, $Y);

which calls the getOffsetPixelCoords function (and in turn the functions below) from the library:
public static function getOffsetPixelCoords($lat,$lng,$zoom, $X, $Y)
    {
        $pixelCoords = GoogleMapUtility::getPixelCoords($lat, $lng, $zoom);
        return new Point(
            $pixelCoords->x - $X * GoogleMapUtility::TILE_SIZE,
            $pixelCoords->y - $Y * GoogleMapUtility::TILE_SIZE
        );
    }

public static function getPixelCoords($lat, $lng, $zoom)
    {
        $normalised = GoogleMapUtility::_toNormalisedMercatorCoords(GoogleMapUtility::_toMercatorCoords($lat, $lng));
        $scale = (1 << ($zoom)) * GoogleMapUtility::TILE_SIZE;
        return new Point(
            (int)($normalised->x * $scale),
            (int)($normalised->y * $scale)
        );
    }

private static function _toNormalisedMercatorCoords($point)
    {
        $point->x += 0.5;
        $point->y = abs($point->y-0.5);
        return $point;
    }

Ok, now the results. For a zoom level<13 it works great, below is an example of a tile in Zoom level 11:
Image1
However, for a tile in zoom level >13, the following happens:
Image2
Which is so strange... the pixels seem to be perfectly aligned ? At first I thought it is a decimal resolution problem, but the resolution of the data is quite good (stored as double in a mysql database, for example, 35.6185989379883, 139.731994628906, and in php floats and doubles are the same thing...)
Could someone help me on how to fix this problem?
Thanks in advance...

A: Why do you use type casting on the result of the database query? In the example of the book googlemapsutility it's not there?


text:
Q: Can do unit test without TDD? I'm in a project where we don't do TDD, because our bosses and the cliente are very "old styled" people. Because I can't do design through TDD but I feel fear to changes, I would like to write unit tests for my own safety. But, how those unit test would be? Do I have to write a test for each method specification for test that they do what it's supposed they do? Do I have to test for each new functionality like TDD but without design? I have a mess in my mind.
Thanks in advance.

A: You probably can't hurt anything by doing unit tests - regardless of how well they're done - except for one possible side-effect, and that is false confidence.
We tend not to do hardcore TDD, nevertheless the unit test coverage ranges from non-existent to moderate depending on project, and is becoming increasingly valuable as the idea settles in.
For general pointers, I'd say the following are key priorities for you right now:

*

*Test what you know to be important

*Test what you know to be fragile

*Write tests to expose any new bugs, then solve the bug by making modifications that pass the test

*Apply TDD where possible to any new features

*Acknowledge that you can't TDD an existing project. By its nature, TDD only applies to new ground, whether that's a new product, or a new feature for a legacy product. Don't let this fact dishearten you.

A: Yes. TDD is yet another software development technique which happens to utilize unit testing heavily. Unit testing as a process is fine on its own without TDD behind. Not to mention, sometimes it's not even possible to do TDD yet you do write tests (think legacy systems/existing untested code testing).
But as for what you should test. Depending how deep with testing you want (can) go, you can start with end user oriented functionality, through system components testing (ie. class contracts) up to simply assuring your code does what you claim it does - that's pretty much the final, most fine-grained unit test which you'll most likely have a lot of.
In general, what to test is not an easy question, I've happened to answer several variants of that question already, to give you few tips:

*

*test what your code does, not what it does not

*if you got certain requirement, have a test covering it

*test single feature at time

*focus on public contract, skip private bits

Also, reading few of the top voted unit testing questions might give you some ideas on why you will benefit from testing, regardless of using TDD or not.

A: When you say "we don't do TDD", do you mean that others don't practise TDD or that your bosses forbid you from practising TDD? If it's the first one, then you can practise TDD as much as you want, as long as you don't try to force other people to do it. If it's the other one, then tell your bosses that they pay you to write code the best way you know how, and TDD is part of how you do that.
You can certainly write tests without practising TDD. People do it all the time. Use the old saying, "Test until fear turns to boredom". Write tests for whatever you fear might not work correctly.


text:
Q: iText7 PDF with multiple Page in Custom Size I have used iText5 in a Software for generating ID-Cards (Name, Barcode etc.).
It Produces a PDF-File with every ID-Card as a Page.
Now is iText5 not running anymore and I switched to 7. But the old Logic in new Syntax is producing not the same.
internal static string erzeugeAusweisdruck(List<int> schlüsselSammlung, String connectionString, string druck_id)
    {
        string rückgabe = "";

        try
        {
            // einmaligen Dateinamen erzeugen
            string dateiendungPdf = ".pdf";
            string stempel = DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second;
            string pdfDateinameKomplett = "AUSGABE/Ausweisdruck_" + stempel + dateiendungPdf;
            rückgabe = pdfDateinameKomplett;
            // Ausweisgrößen von Millimeter in Pixel umrechnen
            float ausweishöhe = 153;
            float ausweisbreite = 251;
            // Viereck für die Ausweisgröße
            iText.Kernel.Geom.Rectangle ausweisgröße = new iText.Kernel.Geom.Rectangle(0, 0, ausweisbreite, ausweishöhe);
            using (PdfWriter writer = new PdfWriter(pdfDateinameKomplett))
            {
                using (PdfDocument pdfDoc = new PdfDocument(writer))
                {
                    using (Document doc = new Document(pdfDoc, new iText.Kernel.Geom.PageSize(ausweisgröße)))
                    {
                        PdfDocumentInfo info = pdfDoc.GetDocumentInfo();
                        info.SetTitle("Ausweisdruck");

                        // Ausweise generieren (schlüsselSammlung durchlaufen)
                        foreach (int schlüssel in schlüsselSammlung)
                        {
                            // Antrag generieren und prüfen ob Ausweis-Nummer existiert
                            ausweisantrag tempAntrag = new ausweisantrag(schlüssel.ToString(), connectionString);
                            string ausweisnummer = "";
                            // Person erzeugen
                            string personid = tempAntrag.personID;
                            // kein so komplexes Objekt nötig !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                            // person personObjekt = new person(tempAntrag.personID);
                            person personObjekt = person.erzeugePersonObjektNurNameUndGeburtsdatum(tempAntrag.personID, connectionString);
                            // Ausweisnummer = Verbandsnummer
                            ausweisnummer = person.holeVerbandsnummer(tempAntrag.personID, connectionString);
                            // AB HIER EINZELNE AUSWEISE bzw. SEITEN
                            // itext Barcode (Code 39)
                            // BARCODE ERZEUGEN
                            Barcode39 barcode39 = new Barcode39(pdfDoc);
                            barcode39.SetCode(ausweisnummer);
                            barcode39.SetBarHeight(25);
                            // GDI+
                            iText.Layout.Element.Image bcImage = new iText.Layout.Element.Image(barcode39.CreateFormXObject(pdfDoc));
                            barcode39 = null;

                            // SCHRIFTEN
                            iText.Kernel.Colors.Color schwarz = ColorConstants.BLACK;
                            string schriftart = iText.IO.Font.Constants.StandardFonts.HELVETICA;
                            PdfFont schriftGrossFett = PdfFontFactory.CreateFont(schriftart);
                            Style grossFett = new Style().SetFontSize(10).SetBold().SetFontColor(schwarz).SetFont(schriftGrossFett);
                            PdfFont schriftGrossDünn = PdfFontFactory.CreateFont(schriftart);
                            Style grossDünn = new Style().SetFontSize(8).SetFontColor(schwarz).SetFont(schriftGrossDünn);
                            PdfFont schriftKlein = PdfFontFactory.CreateFont(schriftart);
                            Style klein = new Style().SetFontSize(6).SetFont(schriftKlein).SetFontColor(schwarz);
                            // Name und Geburtsdatum in einer Zeile (Tabelle)
                            // Paragraph hat im gegensatz zu Paragraph die Option ALIGNMENT
                            Paragraph labelGeburtsdatum = new Paragraph(personObjekt.geburtsdatum.Value.ToShortDateString()).AddStyle(grossDünn);
                            labelGeburtsdatum.SetTextAlignment(TextAlignment.RIGHT);
                            Paragraph labelMitgliedName = new Paragraph(personObjekt.vorname + " " + personObjekt.nachname).AddStyle(grossFett);
                            // LEADING ist Zeilenhöhe
                            labelMitgliedName.SetFixedLeading(8);
                            // Tabelle mit 2 Spalten (75% und 25% Breite)
                            Table tabelleNameGeburtsdatum = new Table(new float[] { 3, 1 });
                            tabelleNameGeburtsdatum.SetWidth(ausweisbreite);
                            //tabelleNameGeburtsdatum.LockedWidth = true;
                            tabelleNameGeburtsdatum.SetMargin(0);
                            Cell zelleName = new Cell();
                            zelleName.SetPaddingLeft(8);
                            zelleName.SetPaddingTop(65);
                            // JEDE ZELLE MUSS BORDER ENTFERNT WERDEN
                            Border keinRahmen = Border.NO_BORDER;
                            zelleName.SetBorder(keinRahmen);
                            zelleName.SetHorizontalAlignment(HorizontalAlignment.LEFT);
                            zelleName.Add(labelMitgliedName);
                            tabelleNameGeburtsdatum.AddCell(zelleName);
                            Cell zelleGeburtsdatum = new Cell();
                            zelleGeburtsdatum.SetPaddingTop(65);
                            zelleGeburtsdatum.SetPaddingRight(8);
                            zelleGeburtsdatum.SetBorder(keinRahmen);
                            zelleGeburtsdatum.SetHorizontalAlignment(HorizontalAlignment.RIGHT);
                            zelleGeburtsdatum.Add(labelGeburtsdatum);
                            tabelleNameGeburtsdatum.AddCell(zelleGeburtsdatum);
                            doc.Add(tabelleNameGeburtsdatum);
                            // STAMMVEREIN - Name und Nummer in einer Zeile
                            verein stammverein = person.holeStammverein(personid, connectionString);
                            string nameStammverein = institution.gebeNameVonInstitutionAngepasstAnDtype(stammverein.verein_id, connectionString);
                            string nummerStammverein = verein.holeVereinsnummerMitVereinID(stammverein.verein_id, connectionString);
                            Paragraph labelStammvereinName = new Paragraph(nameStammverein).AddStyle(grossDünn);
                            Paragraph labelStammvereinNummer = new Paragraph(nummerStammverein).AddStyle(grossDünn);
                            labelStammvereinNummer.SetTextAlignment(TextAlignment.RIGHT);
                            Table tabelleStammverein = new Table(new float[] { 3, 1 });
                            tabelleStammverein.SetWidth(ausweisbreite);
                            //tabelleStammverein.LockedWidth = true;
                            tabelleStammverein.SetMargin(0);
                            Cell zelleNameSV = new Cell();
                            // zelleNameSV.SetPaddingTop = Utilities.MillimetersToPoints(1);
                            zelleNameSV.SetPaddingLeft(8);
                            zelleNameSV.SetBorder(keinRahmen);
                            zelleNameSV.SetHorizontalAlignment(HorizontalAlignment.RIGHT);
                            zelleNameSV.Add(labelStammvereinName);
                            tabelleStammverein.AddCell(zelleNameSV);
                            Cell zelleNummerSV = new Cell();
                            zelleNummerSV.SetBorder(keinRahmen);
                            zelleNummerSV.SetHorizontalAlignment(HorizontalAlignment.RIGHT);
                            // zelleNummerSV.SetPaddingTop = Utilities.MillimetersToPoints(1);
                            zelleNummerSV.SetPaddingRight(8);
                            zelleNummerSV.Add(labelStammvereinNummer);
                            tabelleStammverein.AddCell(zelleNummerSV);
                            doc.Add(tabelleStammverein);
                            // Tabelle für Mitgliedsnummer, Barcode und Nested-Table für Disziplinen
                            Table tabelleBarcodeDisziplinen = new Table(new float[] { 1, 1 });
                            tabelleBarcodeDisziplinen.SetWidth(ausweisbreite);
                            //tabelleBarcodeDisziplinen.LockedWidth = true;
                            tabelleBarcodeDisziplinen.SetMargin(0);
                            // linke Spalte (DISZIPLINEN)
                            Cell zelleDisziplinen = new Cell();
                            zelleDisziplinen.SetHorizontalAlignment(HorizontalAlignment.LEFT);
                            zelleDisziplinen.SetBorder(keinRahmen);
                            zelleDisziplinen.SetPaddingLeft(8);
                            // zelleDisziplinen.SetHorizontalAlignment(HorizontalAlignment.LEFT);
                            // NESTED-Tabelle Disziplinen
                            // 3 Spalten
                            Table tableDisziplinen = new Table(new float[] { 1, 1, 1 });
                            tableDisziplinen.SetWidth(UnitValue.CreatePercentValue(100)).UseAllAvailableWidth();
                            // GÜLTIGE DISZIPLINEN HOLEN UND DRUCHLAUFEN
                            List<string> gültigeDisziplinen = disziplin.holeGueltigeDisziplinenFürAusweisZuEinerPerson(personid, connectionString);
                            // Zähler für anzahl verarbeiteter Spalten in der Tabelle um ggf. mit leeren Zellen auffüllen zu können

                            // NEU: Nur wenn auch Disziplinen vorhanden, SONST leer einfügen
                            if (gültigeDisziplinen.Count > 0)
                            {
                                int zählerSpalte = 1;
                                foreach (string disziplinVerein in gültigeDisziplinen)
                                {

                                    Cell zelle = new Cell();
                                    zelle.SetBorder(keinRahmen);
                                    zelle.SetHorizontalAlignment(HorizontalAlignment.LEFT);
                                    Paragraph inhalt = new Paragraph(disziplinVerein).AddStyle(klein); ;
                                    inhalt.SetTextAlignment(TextAlignment.CENTER);
                                    zelle.Add(inhalt);
                                    tableDisziplinen.AddCell(zelle);
                                    zählerSpalte++;
                                    // Wenn Spalte 3 erreicht den Spaltenzähler wieder auf 1 setzen
                                    if (zählerSpalte == 3)
                                    {
                                        zählerSpalte = 1;
                                    }
                                }
                                // leere Zelle zum Auffüllen wenn Anzahl != 3 der Spalten in Tabelle
                                Cell zelleLeer = new Cell();
                                zelleLeer.SetBorder(keinRahmen);
                                zelleLeer.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                                Paragraph inhaltLeer = new Paragraph(" ").AddStyle(klein);
                                zelleLeer.Add(inhaltLeer);
                                // prüfen bei welcher Spalte die Befüllung gestoppt hat
                                if (zählerSpalte == 1)
                                {
                                    // zwei leere Zellen auffüllen
                                    tableDisziplinen.AddCell(zelleLeer);
                                    tableDisziplinen.AddCell(zelleLeer);
                                }
                                if (zählerSpalte == 2)
                                {
                                    // eine leere Zelle auffüllen
                                    tableDisziplinen.AddCell(zelleLeer);
                                }
                                zelleDisziplinen.Add(tableDisziplinen);
                                tabelleBarcodeDisziplinen.AddCell(zelleDisziplinen);
                            }
                            else
                            {
                                int zählerSpalte = 1;
                                Cell zelle = new Cell();
                                zelle.SetBorder(keinRahmen);
                                zelle.SetHorizontalAlignment(HorizontalAlignment.LEFT);
                                Paragraph inhalt = new Paragraph(" ").AddStyle(klein);
                                inhalt.SetTextAlignment(TextAlignment.CENTER);
                                zelle.Add(inhalt);
                                tableDisziplinen.AddCell(zelle);
                                // leere Zelle zum Auffüllen wenn Anzahl != 3 der Spalten in Tabelle
                                Cell zelleLeer = new Cell();
                                zelleLeer.SetBorder(keinRahmen);
                                zelleLeer.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                                Paragraph inhaltLeer = new Paragraph(" ").AddStyle(klein);
                                zelleLeer.Add(inhaltLeer);
                                // prüfen bei welcher Spalte die Befüllung gestoppt hat
                                if (zählerSpalte == 1)
                                {
                                    // zwei leere Zellen auffüllen
                                    tableDisziplinen.AddCell(zelleLeer);
                                    tableDisziplinen.AddCell(zelleLeer);
                                }
                                if (zählerSpalte == 2)
                                {
                                    // eine leere Zelle auffüllen
                                    tableDisziplinen.AddCell(zelleLeer);
                                }
                                zelleDisziplinen.Add(tableDisziplinen);
                                tabelleBarcodeDisziplinen.AddCell(zelleDisziplinen);
                            }

                            // rechte Spalte (AUSWEISNUMMER, BARCODE)
                            Paragraph labelAusweisnummer = new Paragraph(ausweisnummer).AddStyle(grossFett);
                            labelAusweisnummer.SetTextAlignment(TextAlignment.RIGHT);
                            Cell zelleBarcodeNummer = new Cell();
                            zelleBarcodeNummer.SetPaddingRight(8);
                            //zelleBarcodeNummer.SetPaddingTop = Utilities.MillimetersToPoints(5);
                            zelleBarcodeNummer.SetBorder(keinRahmen);
                            zelleBarcodeNummer.SetHorizontalAlignment(HorizontalAlignment.RIGHT);
                            zelleBarcodeNummer.Add(labelAusweisnummer);

                            // ÄNDERUNGEN GDI+ Fehler HIER:
                            // VORHER: iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(barcodeDateinameKomplett);
                            // iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(new MemoryStream(File.ReadAllBytes(barcodeDateinameKomplett)));
                            iText.Layout.Element.Image img = bcImage;
                            if (bcImage != null)
                            {
                                bcImage = null;
                            }
                            // Barcode-Image etwas verkleinern
                            img.ScaleAbsolute(Convert.ToSingle(double.Parse(img.GetImageWidth().ToString()) * 0.85), Convert.ToSingle(double.Parse(img.GetImageHeight().ToString()) * 0.85));
                            img.SetHorizontalAlignment(HorizontalAlignment.RIGHT);
                            img.SetPaddingTop(3);
                            zelleBarcodeNummer.Add(img);
                            // GDI+
                            if (img != null)
                            {
                                img = null;
                            }
                            // Druckdatum
                            Paragraph labelDruckdatum = new Paragraph(DateTime.Now.ToShortDateString()).AddStyle(klein);
                            labelDruckdatum.SetHorizontalAlignment(HorizontalAlignment.RIGHT);
                            zelleBarcodeNummer.Add(labelDruckdatum);
                            tabelleBarcodeDisziplinen.AddCell(zelleBarcodeNummer);
                            doc.Add(tabelleBarcodeDisziplinen);
                        }
                    }
                }
            }

        }
        catch (Exception ex)
        {
            rückgabe = "FEHLER: " + ex.Message;
            mySQL.speichereFehlermeldung(druck_id, ex.Message, connectionString);
        }

        //mySQL.erzeugeSofortDownloadFürEineDatei("Ausweisdruck", "ausweise/" + pdfDateiname + ".pdf", mySession.Current.benutzer.benutzerID.ToString(), "Ausweisdruck");

        return rückgabe;
    }

In Itext5 I used
Document.NewPage();

for every ID-Card inside the Loop.
How can I realise that in iText7? PDF-File with multiple Pages, each with a Size of 5 * 8 centimetres.
Hope someone can give some Impulses. Thanks

A: Added a counter and at the End of the loop checking if counter is smaller then count of job:
doc.Add(new AreaBreak(iText.Layout.Properties.AreaBreakType.NEXT_PAGE));


text:
Q: jQuery DatePicker add year to yearRange I am trying to add the year '9999' to my datepicker yearRange but nothing seems to work.  I want to do something like this:
$("#effective_date").datepicker({
  dateFormat: 'yy-mm-dd',
  changeMonth: true,
  changeYear: true,
  yearRange: "2002:2012,9999"
})

Any help would be greatly appreciated, thanks!

A: You can simply use this command :
<script type="text/javascript">
$(function() {
  $("#datepicker").datepicker({changeMonth: true, changeYear: true, yearRange:'1950:2013'}).val();
});
</script>

A: if you are trying to add year 9999 and with yearRange option then you have to increase the range from 2002 to 9999  like  yearRange: "2002:9999"

A: Your comment:

It might not be possible using the jQuery api, but I'm sure there are ways of overriding the javascript.

You can create your own plugin, if you want to use an existing plugin you need to use it's API, and this is impossible with the jQuery UI datepicker widget.

A: Similar to other answers, there is probably a more elegant UI way to capture this non-date value but this can modify a year.  I'm not sure but I'd guess there are unintended consequences.
  var yearAdded = false;

  $(".ui-datepicker").on("mouseenter", function() {

    if (!yearAdded) {
      yearAdded = true;
      var dropYear = $("select.ui-datepicker-year");
      dropYear.append("<option value='9999'>9999</option>");

    }

  });

Hope this helps.


text:
Q: Minimum Xcode Dev Tools packages required for installing gems? I'm running 10.5.8 and did not have the developer tools installed (I run mostly on my Linux partition)... but I was trying to dry run the installation of a ruby app, timetrap, for a friend so that I could walk him through installation when we get together in a few weeks.
In any case, I kept getting failures of:
sudo gem install sqlite3
Building native extensions.  This could take a while...
ERROR:  Error installing sqlite3:
    ERROR: Failed to build gem native extension.

/usr/local/bin/ruby extconf.rb
checking for sqlite3.h... no
sqlite3.h is missing. Try 'port install sqlite3 +universal'
or 'yum install sqlite3-devel' and check your shared library search path (the
location where your sqlite3 shared library is located).
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/local/bin/ruby
    --with-sqlite3-dir
    --without-sqlite3-dir
    --with-sqlite3-include
    --without-sqlite3-include=${sqlite3-dir}/include
    --with-sqlite3-lib
    --without-sqlite3-lib=${sqlite3-dir}/lib

Gem files will remain installed in /usr/local/lib/ruby/gems/1.8/gems/sqlite3-1.3.3 for inspection.
Results logged to /usr/local/lib/ruby/gems/1.8/gems/sqlite3-1.3.3/ext/sqlite3/gem_make.out

I actually had sqlite3.h in /usr/local/include but could not get anything different even when trying sudo gem install timetrap -- --with-sqlite3-include=/usr/local/include. I tried installing BitNami RubyStack to see if that helped and no dice.
In any case, I ran into some posts (several here) saying that c libraries were required for some gems, so I decided to install XCode and everything worked.
XCode is a space hog and I'll hardly ever use it, but I'd like to be able to do what I need to with this. I tried installing only the gcc-4.2 package alone and got failures. I found that the package MacOSX10.5.pkg also did not sole the problem. Installing all of XCode (Build Tools Essentials and Unix Development options) takes 2+ GB.
It seems that just the gcc package should give me what I want, but something is awry.
Would someone suggest:
- if all of XCode really is required for some other thing included in that package?
- if installing XCode is setting a path/include variable somewhere such that it works when XCode gets installed but not when I try to do my a la carte install of gcc along?
I have several sqlite3.h's scattered around with these individual packages as well as the ones that were already there. What's my issue? Is it not really sqlite3.h but something else?
Goal: Install some basic package that lets me do this without needing various other tools I'll never use. I dual boot on an older MacBook and only have 10GB left on my drive. Without XCode I had closer to 13! I realize I could install and then just trash XCode, but it seems like while I'm at it, gcc isn't bad to have around.

A: XCode's installer has some options to let you strip out some things you won't use, but it's not going to let you strip everything and only keep gcc.
Remember their saying "It just works", well, they're not going to make it easy to break it.


text:
Q: Consume REST API with only access of TSL1.2 in C# We are doing integration with one third party to send and receive data. Third Party have created one REST API with SSL and deployed on their server. In server, for security reason they have disabled all the Weak protocols like TSL1.0,TSL1.1,SSL3.0 and only enabled protocol is TSL1.2.
We want to consume it in our .net application developed in .net framework 3.5.
We have tried to bypass the SSL Validation  like below
ServicePointManager.ServerCertificateValidationCallback = delegate(object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
But service is hitting. Then we have tried to do POC with .net framework 4.5 application and have added one more line
System.Net.ServicePointManager.SecurityProtocol =  SecurityProtocolType.Tls12;
Still I am not able to Consume the Web Service
Any help would be great appreciated.


text:
Q: Pyredis cannot connect to Digital Ocean hosted Redis (connection lost ConnectionError exception) In [16]: r
Out[16]: Redis<ConnectionPool<Connection<host=****,port=*****,db=3>>>

In [17]: r.set('zaza', 'king')
---------------------------------------------------------------------------
ConnectionError                           Traceback (most recent call last)
<ipython-input-17-8126d1846970> in <module>
----> 1 r.set('zaza', 'king')

/usr/local/lib/python3.7/site-packages/redis/client.py in set(self, name, value, ex, px, nx, xx)
   1517         if xx:
   1518             pieces.append('XX')
-> 1519         return self.execute_command('SET', *pieces)
   1520
   1521     def __setitem__(self, name, value):

/usr/local/lib/python3.7/site-packages/redis/client.py in execute_command(self, *args, **options)
    834         pool = self.connection_pool
    835         command_name = args[0]
--> 836         conn = self.connection or pool.get_connection(command_name, **options)
    837         try:
    838             conn.send_command(*args)

/usr/local/lib/python3.7/site-packages/redis/connection.py in get_connection(self, command_name, *keys, **options)
   1069         try:
   1070             # ensure this connection is connected to Redis
-> 1071             connection.connect()
   1072             # connections that the pool provides should be ready to send
   1073             # a command. if not, the connection was either returned to the

/usr/local/lib/python3.7/site-packages/redis/connection.py in connect(self)
    545         self._sock = sock
    546         try:
--> 547             self.on_connect()
    548         except RedisError:
    549             # clean up after any error in on_connect

/usr/local/lib/python3.7/site-packages/redis/connection.py in on_connect(self)
    615             # to check the health prior to the AUTH
    616             self.send_command('AUTH', self.password, check_health=False)
--> 617             if nativestr(self.read_response()) != 'OK':
    618                 raise AuthenticationError('Invalid Password')
    619

/usr/local/lib/python3.7/site-packages/redis/connection.py in read_response(self)
    697         "Read the response from a previously sent command"
    698         try:
--> 699             response = self._parser.read_response()
    700         except socket.timeout:
    701             self.disconnect()

/usr/local/lib/python3.7/site-packages/redis/connection.py in read_response(self)
    307
    308     def read_response(self):
--> 309         response = self._buffer.readline()
    310         if not response:
    311             raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)

/usr/local/lib/python3.7/site-packages/redis/connection.py in readline(self)
    239         while not data.endswith(SYM_CRLF):
    240             # there's more data in the socket that we need
--> 241             self._read_from_socket()
    242             buf.seek(self.bytes_read)
    243             data = buf.readline()

/usr/local/lib/python3.7/site-packages/redis/connection.py in _read_from_socket(self, length, timeout, raise_on_timeout)
    184                 # an empty string indicates the server shutdown the socket
    185                 if isinstance(data, bytes) and len(data) == 0:
--> 186                     raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
    187                 buf.write(data)
    188                 data_length = len(data)

This started happening after a move to hosted redis from a local instance

A: So, the problem is that the Redis connection string on those hosted solutions has to start with rediss:// as in redis + SSL as per the official documentation:
https://redislabs.com/lp/python-redis/
If you use hosted Redis from AWS or Digital Ocean this might as well happen to you :)
if you are using Celery you would also need to modify your app config in app.py as per
https://github.com/celery/celery/issues/5371


text:
Q: I want to show a multi floor indoor map in ios using swift I would like to create an indoor navigation app. But I have some trouble with a floor plan. I have location beacons to identify and detect user's position. I don't want to do estimate like a 3rd party tool it will be costly. Now I have troubles with.

*

*Drawing floor plans

*Showing routes a to b.

*Scaling of map like zooming.

*I have lengthy or big floor, plan how to manage.

*Tagging info on clicking on of the part of map show up the info box.

Can you please suggest how to keep floor plan and routes and distances coordinate position.

A: I recently worked on the indoor navigation project based on beacons. These are the things you have to keep in mind for the questions you asked.

*

*You need the floor plan image or layout image for each of the floors.

*For showing route, you have to know some algorithms to achieve the expected result. I used Dijikstra algorithm to plot the route between two points.

*For scaling and zooming you have delegate methods in UIScrollViewDelegate

*Based on the resolution of the image you have to present it.

*Customize the info view on click.
You have to dig deep to make your project work. Need a deep understanding of the swift or objective - c. The answers to your question can't be given in a word. These are some of the understanding based on my experience.
All the best!


text:
Q: Creating memory space for multi-dimensional array I am studying c++ and found this in the book
array_ptr = new int[3][5][4];

This is used to allocate memory to a multi dimensional array using new. It also states while first dimension can be a variable whose value is supplied at runtime, others must be constant.
I tried to run this code
int *p = new int[3][5][6];

But it is showing an error.
Can someone elaborate.

A: Here is what you want:
int (*p)[5][6] = new int[3][5][6];

Since C++11 you can ask the compiler to decuce the type of p for you:
auto p = new int[3][5][6];

You don't need anything special to delete such array:
delete [] p;

Logic behind the choice of the type is simple:
In this line: int *p = new int[10] you're creating an array of 10 ints and you use pointer to int to store the address.
In general case, if you're allocating an array of N Ts (where N is the size and T is the type), you use pointer to T to store the address.
Same rule can be applied to multidimensional arrays, because they are in fact nested 1D arrays.
When you try to allocate multidimensional array: p = new int[4][5][6], you're creating an array of 4 arrays of 5 arrays of 6 ints. Thus you need a pointer to array of 5 arrays of 6 ints, which is int (*p)[5][6].
In other words, int [3][4][5] can be viewed as 1D array of size 3. It consists of other arrays of type int [4][5]. Each of these arrays has size 4 and consists of other arrays of type int [5], which in turn contain 5 ints.

P.S. Authors of other answers seem to favor using int *** and allocating memory for each nested array separately. Doing so may seem smart, but in fact it's much slower and dangerous (if you mess up your memory management). The only advantage of that trick is that it provides the convenient interface we all used to (p[z][y][x]).
But there is a much better solution: int *p = new int[x_sz * y_sz * z_sz];. You would need to convert 3D indices to 1D index (p[x + x_sz * (y + z * y_sz)] instead of p[z][y][x]) for it to work, but in my opinion it's still more convenient (and definitely faster).
Of course, in real code, you should use std::vector to store such array and write your own wrapper class, which would compute the index automatically.

A: A 3d array is not the same as a pointer to int, and you can't make them the same.
If you need dynamic allocation, you can use special class std::vector (best choose), std::array, or write next code:
int ***p = new int**[3];
for (int i = 0; i < 3; ++i) {
  p[i] = new int*[5];
  for (int j = 0; j < 5; ++j) {
    p[i][j] = new int[6];
  }
}

A: In order to create dynamic 3d array you have to use pointer to pointer to pointer)
const int xSize = 3;
const int ySize = 5;
const int zSize = 4;

int*** p = nullptr;

// creating array of pointers to pointers
p = new int** [xSize]

// for each pointer to pointers, create array of pointers
for( int i = 0; i < xSize; ++i )
  p[ i ] = new int* [ySize];

// now we have 2d array of pointers, for each of them allocate array
for( int i = 0; i < xSize; ++i )
  for( int j = 0; j < ySize; ++j )
    p[ i ][ j ] = new int [zSize];

But is much more better to use vectors
vector<vector<vector<int> > > v3d;

v3d.resize( 3 );

for( int i = 0; i < xSize; ++i )
  v3d[ i ].resize( ySize );

for( int i = 0; i < xSize; ++i )
  for( int j = 0; j < ySize; ++j )
    v3d[ i ][ j ].resize( zSize );


text:
Q: Conditional Expectation of a normal random variable. I have been asked to derive the expression for $E[X\mid X>a]$ where $X$ is a normal random variable with mean $\mu$ and variance $\sigma^2$ and $a$ is some constant belonging to $R$. It is my understanding that I need to integrate the product of $X$ and pdf of normal from $a<x<\infty$. But I am unable to figure out this integral. Can anyone help with that?
If possible, kindly also guide how we can solve it using the MGF of normal random variable.

A: The conditional distribution $f(x|x>a)$ is given by
$$f_{X|X>a}(x)=\frac{1}{1-F_X(a)}f_X(x)\mathbb{1}_{(a;\infty)}(x)$$
The integral involved to calculate the expectation can be easy solved as it is in the form
$$\int x e^{-\frac{x^2}{2}}dx$$
and as you note, $x$ is something like the exponent derivative...

Example:
$X\sim N(1;1)$
Calculate $\mathbb{E}(X|X>1)$
$$\mathbb{E}(X|X>1)=\frac{1}{1-F(1)}\int_1^{\infty}\frac{1}{\sqrt{2\pi}}x e^{-\frac{(x-1)^2}{2}}dx=$$
Set $x-1=y$
$$2\Bigg[\int_0^{\infty}\frac{1}{\sqrt{2\pi}}ye^{-\frac{y^2}{2}}dy+\underbrace{\int_0^{\infty}\frac{1}{\sqrt{2\pi}}e^{-\frac{y^2}{2}}dy}_{=\frac{1}{2}}\Bigg]$$
$$=2\Bigg\{-\frac{1}{\sqrt{2\pi}}\Bigg[e^{-\frac{y^2}{2}}\Bigg]_0^{\infty}+\frac{1}{2}\Bigg\}=\frac{2}{\sqrt{2\pi}}+1\approx1.797885$$

General example
$X\sim N(\mu;\sigma^2)$; Calculate $\mathbb{E}(X|X>a)$
$$\mathbb{E}(X|X>a)=\frac{1}{1-\Phi\Big(\frac{a-\mu}{\sigma}\Big)}\int_a^{\infty}\frac{1}{\sigma\sqrt{2\pi}}x e^{-\frac{1}{2}\Big(\frac{x-\mu}{\sigma}\Big)^2}$$
Set $\frac{x-\mu}{\sigma}=y$
$$\frac{1}{1-\Phi\Big(\frac{a-\mu}{\sigma}\Big)}\int_{\frac{a-\mu}{\sigma}}^{\infty}\frac{1}{\sqrt{2\pi}}(\sigma y+\mu) e^{-\frac{1}{2}y^2}dy$$
$$\frac{1}{1-\Phi\Big(\frac{a-\mu}{\sigma}\Big)}\Bigg\{\int_{\frac{a-\mu}{\sigma}}^{\infty}\frac{\sigma y}{\sqrt{2\pi}} e^{-\frac{1}{2}y^2}dy+\mu\int_{\frac{a-\mu}{\sigma}}^{\infty}\frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}y^2}dy\Bigg\}$$
$$\frac{1}{1-\Phi\Big(\frac{a-\mu}{\sigma}\Big)}\Bigg\{\frac{\sigma}{\sqrt{2\pi}}\Big[ -e^{-\frac{1}{2}y^2}\Big]_{\frac{a-\mu}{\sigma}}^{\infty}+\mu\Big[1-\Phi\Big(\frac{a-\mu}{\sigma}\Big] \Bigg\}$$
$$ \bbox[5px,border:2px solid red]
{
\mathbb{E}(X|X>a)=\frac{1}{1-\Phi\Big(\frac{a-\mu}{\sigma}\Big)}\Bigg\{\frac{\sigma}{\sqrt{2\pi}}e^{-\frac{1}{2}\Big(\frac{a-\mu}{\sigma}\Big)^2}+\mu\Big[1-\Phi\Big(\frac{a-\mu}{\sigma}\Big] \Bigg\}
\
}
$$


text:
Q: How to pass content to a slot in render function (functional component) - Vue Functional Button component:
const Button = createElement('button', {}, [slots().icon ? createElement('span', slots().icon[0].text) : null])

Another functional component that uses Button above:
createElement(Button, {}, ['this goes to children'])

But this renders text this goes to children not inside the span as i wrapped it above.
How can i put contents inside a slot in a Button component from another createElement()?
With templates it's easy enough:
<template>
  <Button>
    <template #icon>This would be wrapped inside span</template>
  </Button>
</template>

UPDATE 1
I've to utilize slot: 'name-of-the-slot' key in the data properties:
const icon = createElement('span', { slot: 'icon' }, 'text inside span')
createElement(Button, {}, [icon])

No success. Does it even work? Created a bug report in a Vue repo: https://github.com/vuejs/vue/issues/11519
SEMI-SOLUTION
With the Posva's help:
export default {
  name: "Wrapper",
  functional: true,
  render(h) {
    return h(Button, { scopedSlots: {
      icon: () => h('span', {}, 'its from wrapper')
    } });
  }
};

export default {
  name: "Button",
  functional: true,
  render(createElement, { scopedSlots }) {
    return createElement("button", {}, scopedSlots.icon(null));
  }
};

ScopedSlots was the key.
Also don't forget to add check, if this slot exists, like:
return createElement("button", {}, scopedSlots.icon ? scopedSlots.icon(null) : null)

A: A component using template:
MyButton.vue
<template>

    <slot name="left"></slot>
    <button>
      <slot v-bind:person="person">
        按钮
      </slot>
    </button>
    <slot name="right" v-bind:age="person.age"></slot>

</template>

use MyButton in template:
 <MyButton>
   <template #right="{age}">
     button rigt side. I am  {{ age }} years
   </template>
   <template v-slot="{ person }">this is a button,{{ person }}</template>
   <template #left>
     button left side
   </template>
</MyButton>

use it in render function:
import MyButton from './MyButton.vue'
export default {
  name: 'UseButton',
  render(h) {
    const slotLeft = h('template', { slot: 'left' }, 'in the left of button')
    const slotRight = h('template', { slot: 'right' }, 'right')
    const slotDefault = h('template', { slot: 'default' }, 'default slot')
    const children = [slotRight, slotLeft, slotDefault]
    // normal slots in third parms, any order work well
    return h(MyButton, {}, children)
  },
}

get data from scoped slot in render function:
import MyButton from './MyButton.vue'
export default {
  name: 'UseButton',
  render(h) {
    const slotLeft = h('template', { slot: 'left' }, 'normal slot with name left')
    const children = [slotLeft]
    return h(
      MyButton,
      {
       // scopedSlot in the second param
        scopedSlots: {
          // props come from MyButton inside
          default: props => {
            console.log(props)
            const { person } = props
            const text = `defaul scopedSlot,${JSON.stringify(person)}`
            // use h
            return h('span', {}, text)
          },
          right: props => {
            console.log(props)
            const { age } = props
            // use jsx
            return in the right,I am {age} years
          },
        },
      },
      // normal slot
      children
    )
  },
}

implement of MyButton.vue with jsx or js.
MyButton.jsx
export default {
  name: 'MyButton',
  data() {
    return {
      person: {
        name: 'jack',
        age: 23,
      },
    }
  },
  render(h) {
    const { left, right, default: _defaultSlot } = this.$scopedSlots
    // checek the default exist or not
    const defaultSlot = (_defaultSlot && _defaultSlot({ person: this.person })) || 按钮
    const leftSlot = (left && left()) || ''
    const rightSlot = right(this.person)
    const button = h('button', {}, [defaultSlot])
    //  jsx make structure more clear
    return (

        {leftSlot}
        {button}
        {rightSlot}

    )
  },
}

use functional component with jsx:
FunctionalButton.jsx
export default {
  name: 'FunctionalButton',
  functional: true,
  props: {
    person: {
      type: Object,
      default: () => ({ name: 'jack', age: 23 }),
    },
  },
  // NO DATA in functional component
  // data() {
  //   return {
  //     person: {
  //       name: 'jack',
  //       age: 23,
  //     },
  //   }
  // },
  render(h, { props, scopedSlots }) {
    const { left, right, default: _defaultSlot } = scopedSlots
    const defaultSlot = (_defaultSlot && _defaultSlot({ person: props.person })) || 按钮
    const leftSlot = (left && left()) || ''
    const rightSlot = right(props.person)
    const button = h('button', {}, [defaultSlot])
    return (

        {leftSlot}
        {button}
        {rightSlot}

    )
  },
}

A: Using dynamic component resolved a problem for me, you can simply pass render function into "is" attribute like this

<component :is="slot.renderFn"></component>


text:
Q: Changing the arguments to Open() using python Mock I am trying to change the arguments to open() so that my test code will open the files in the test/ directory instead of the original one.
file.py
def testing_opening():
    f = open( 'file', 'r' )
    return f.read()

Now, in my test file, I want to read files from 'test/file'.
How do I do that?
I can mock patch open(), but I don't know how to change it's arguments.
Please help
EDIT:
test_file.py
@patch( '__builtin__.open', new_callable=mock_open )
def test_open( m_file ):
    m_file.side_effect = open( os.curdir + '/test/'+ m_file.call_args[0][0], m_file.call_args[1] )
    f = testing_opening()
    print f


text:
Q: Data Extract Tar and 7z I have a single .tar file with many folders and subfolders in it. Inside these many folders there are .7z files among other files. I'd like to search through these folders/subfolder and locate .7z files, (assign them to an array?) and extract them to their respective location.
I'm using Apache Commons:
1) org.apache.commons.compress.archivers.sevenz
Provides classes for reading and writing archives using the 7z format.
2) org.apache.commons.compress.archivers.tar
Provides stream classes for reading and writing archives using the TAR format.

*

*step I wanna extract the .tar file

*step I wanna go through the extracted .tar file folder and its subfolders recursively and locate .7z files.

*In the 3. step I wanna feed the array the array of .7z files I found and extract them 1 by 1 to their respective locations.

I'm having problems in the 3. step with array call/assignment :/ Could you please help? Thank you very much :)
    /**
     * uncompresses .tar file
     * @param in
     * @param out
     * @throws IOException
     */
    public static void decompressTar(String in, File out) throws IOException {
        try (TarArchiveInputStream tin = new TarArchiveInputStream(new FileInputStream(in))){
            TarArchiveEntry entry;
            while ((entry = tin.getNextTarEntry()) != null) {
                if (entry.isDirectory()) {
                    continue;
                }
                File curfile = new File(out, entry.getName());
                File parent = curfile.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                IOUtils.copy(tin, new FileOutputStream(curfile));
            }
        }
    }

    /**
     * uncompresses .7z file
     * @param in
     * @param destination
     * @throws IOException
     */
    public static void decompressSevenz(String in, File destination) throws IOException {
        //@SuppressWarnings("resource")
        SevenZFile sevenZFile = new SevenZFile(new File(in));
        SevenZArchiveEntry entry;
        while ((entry = sevenZFile.getNextEntry()) != null){
            if (entry.isDirectory()){
                continue;
            }
            File curfile = new File(destination, entry.getName());
            File parent = curfile.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(curfile);
            byte[] content = new byte[(int) entry.getSize()];
            sevenZFile.read(content, 0, content.length);
            out.write(content);
            out.close();
        }
        sevenZFile.close();
    }

    public void run()
    {
        //1) uncompress .tar
        try {
            JThreadTar.decompressTar(RECURSIVE_DIRECTORY_PATH, new File(RECURSIVE_DIRECTORY));
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //2) go through the extracted .tar file directory and look for .7z (recursively?)
        File[] files = new File(RECURSIVE_DIRECTORY).listFiles();

        for (File file : files) {
                if (file.isDirectory()) {

                    File[] matches = file.listFiles(new FilenameFilter()
                    {
                      public boolean accept(File dir, String name)
                      {
                         return name.endsWith(".7z");
                      }
                    });

                    for (File element: matches) {
                        System.out.println(element);
                        }
                }
                else {
                    continue;
                }
        }

        //3) Feed the array above to decompressSevenz method

        for (int i = 0; i < matches.length; i++)
        {
            if (matches[i].isFile())
            {
                try {
                JThreadTar.decompressSevenz(matches[i].toString(), new File(RECURSIVE_DIRECTORY));
                }
                catch (IOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
                }
            }
        }

My problem is: I can't refer to []matches in step 3. I'm not using this correctly. I just want to create an array []matches for .7z file matches. Every time a .7z is found, I'd like to add it to this array. and in the 3. step I wanna extract each .7z to its relative location.
I came a bit further:
    //1) uncompress .tar
        try {
            JThreadTar.decompressTar(RECURSIVE_DIRECTORY_PATH, new File(RECURSIVE_DIRECTORY));
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //2) go through the extracted .tar file directory and look for .7z (recursively?)
        File dir = new File(RECURSIVE_DIRECTORY);
        File[] dirFiles = dir.listFiles();
        ArrayList<File> matches2 = new ArrayList<File>();

        for (File file : dirFiles) {
                if (file.isDirectory()) {
                    File[] matches = dir.listFiles(new FilenameFilter()
                    {
                      public boolean accept(File dir, String name)
                      {
                         return name.endsWith(".7z");
                      }
                    });
                    matches2.addAll(Arrays.asList(matches));
                }
                else if (file.isFile()) {
                    if (file.getName().endsWith(".7z")){
                    matches2.add(file);
                    };
                    }
                };

            //3) Feed the arraylist above to decompressSevenz method
            for (int counter = 0; counter < matches2.size(); counter++) {
            if (matches2.get(counter).isFile())
            {
                try {
                JThreadTar.decompressSevenz(matches2.get(counter).toString(), new File(RECURSIVE_DIRECTORY));
                }
                catch (IOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
                }
            }
            }

Here is after the final form of step 2 and step 3 from @Joop Eggen
        Path topDir = Paths.get(RECURSIVE_DIRECTORY);
        try {
            Files.walk(topDir)
                .filter(path -> path.getFileName().toString().endsWith(".7z"))
                .forEach(path -> {
                    try {
                        JThreadTar.decompressSevenz(path.toString(), topDir.toFile());
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }
            });
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

*

*step recursively:

        Path toptopDir = Paths.get(RECURSIVE_DIRECTORY_PATH);
        try {
            Files.walk(toptopDir)
                .filter(path -> path.getFileName().toString().endsWith(".tar"))
                .forEach(path -> {
                    try {
                        JThreadTar.decompressTar(RECURSIVE_DIRECTORY_PATH, new File(RECURSIVE_DIRECTORY));
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }
            });
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

A: I took the opportunity to use the newer Path and Files. Files.listFiles() may return null. And the usage of Arrays.asList and such will cause heavy data.
All that would be simplified to:
    Path topDir = Paths.get(RECURSIVE_DIRECTORY);
    Files.walk(topDir)
        .filter(path -> path.getFileName().toString().endsWith(".7z"))
        .forEach(path -> {
            try {
                JThreadTar.decompressSevenz(path.toString(), topDir.toFile());
            } catch (IOException e2) {
                e2.printStackTrace();
            }
    });


text:
Q: How to pass a result from my java code to nodeJs? I am writing an algo to analyze market data in Java, to visualize my data i'd like to make use of an existing charting library from tradingview. This free charting library runs on nodeJS.
I'm having a lot of trouble understanding how to populate it with my data resulting from my algorithm.
For example my Java code returns a "List< Candlestick >" object, how do i send this to the Javascript code running on the nodeJs ?
if someone would be so kind to give some global directions in how to approach this it would be very much appreciated.

A: My assumption here is that you have java code and the result you want to display is on nodejs.
While at this moment calling data from the API is suggested, also there is one more option we can use to solve your problem. This is a good case of polyglot programming. I have used graalvm.
Installation via sdkman
GraalVM
sdk install java 21.1.0.r11-grl

NodeJS
gu install nodejs

Both Main Projects are located here https://gitlab.com/graalvm-java-to-nodejs

*

*Java Project (has method which return a list)

*NodeJS Project(loads Java Class in NodeJS and call method on class reference to get the list)

Add any code to java library in my case I have a class which just return list of Point as given below:
public class GraphData {
    public List<Point> getPoints() {
        return List.of(new Point(1, 1), new Point(3, 5));
    }
}

where Point is a POJO class to hold (x, y) value.
Clone this java project https://gitlab.com/graalvm-java-to-nodejs/graalvm-simple-java and execute ./gradlew clean build this should give you a executable jar which can be executed java -jar file.jar command.
Now, clone https://gitlab.com/graalvm-java-to-nodejs and install dependencies npm install then execute
node --jvm --vm.cp=/home/ashish/IdeaProjects/graavlvm/java-lib-gvm/build/libs/java-lib-gvm-1.0-SNAPSHOT.jar bin/www
Relevant code which interacts with java is as below:
var GraphDataJavaRef = Java.type('in.silentsudo.GraphData');
var graphData = new GraphDataJavaRef();
var data = graphData.getPoints();

in.silentsudo.GraphData class is loaded from the jar file which is provided to node program with argument named --jvm --vm.cp path/to/file.jar
Once you navigate to localhost:3000, you should see
Express Tutorial
Welcome to Express Tutorial

Response from Java class
[Point{x=1, y=1}, Point{x=3, y=5}]


text:
Q: RuntimeException AndroidInjection.inject in Dagger2 service I have a service and I'm using dagger2 v2.27, In the google play store consolo y have the following crash (I don't have this crash in Firebase console tho)

Caused by: java.lang.RuntimeException:    at
dagger.android.AndroidInjection.inject (AndroidInjection.java:124)
at app.ui.main.ServiceNotificationListener.onCreate
(ServiceNotificationListener.java:34)   at
android.app.ActivityThread.handleCreateService
(ActivityThread.java:3758)

I'm using a Service that extends Android NotificationListenerService , in onCreate I have the following
 override fun onCreate() {
        AndroidInjection.inject(this) // line 34
}

MainApplication:
    class MainApplication : Application(), HasAndroidInjector {

     override fun onCreate() {
            super.onCreate()
     DaggerAppComponent
                .builder()
                .application(this)
                .build()
                .inject(this)
    }
}

In AndroidManifest.xml
   <application
        android:hardwareAccelerated = "true"
        android:name=".ui.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar.NoStatusBar">

I can't reproduce the bug, I reaad about the application is null, but not sure how I can solve the issue for my service (relies on NotificationListener) Thanks a lot

A: I wrote an article about this bug. Unless you know the actual problem, it's difficult to track or reproduce, and even harder to debug. It's an evil bug, and it is known to have driven at least one engineer to the brink of insanity. The article goes into detail about the actual issue.
TL;DR - Just set android:allowBackup=false, and that should fix your crashes.
....
I need another beer to drown out the memory of this bug now.

A: If possible share the code used in the NotificationListenerService. Since its a service i would prefer inject it inside the dagger module class.


text:
Q: URL Rewriting - htaccess web.config I have imported in IIS these rewrite rules :
RewriteRule ^search/(.+)/([0-9]+)?$ search.html?name=$1&page=$2 [QSA,L]
RewriteRule ^search/(.+)?$ search.html?name=$1&page=1 [QSA,L]

Translation is :
match url="^search/(.+)/([0-9]+)?$" ignoreCase="false"
action type="Rewrite" url="search.html?name={R:1}&page={R:2}" appendQueryString="true"

match url="^search/(.+)?$" ignoreCase="false"
action type="Rewrite" url="search.html?name={R:1}&page=1" appendQueryString="true"

but when i'm testing doesn't work
HTTP Error 404.0 - Not Found -this is the error

A: Try with a condition,
conditions logicalGrouping="MatchAll" trackAllCaptures="false"
(did not include opening and closing tags.)


text:
Q: Finding the main content of Webpage using Javascript I've a sting htmlSrc containing the entire html content of the webpage?
Is there any way to find the main content of the webpage?
What is the page all about using JavaScript?

A: If you're asking about finding content such that you can differentiate what two websites are about I would suggest finding text within HTML tags and comparing them. You can maybe search for different tags like  and parse the text between the tags. Or maybe  tags to find the headings.