text:
Q: How to change the extension name of a file before downloading? I have a video file hosted which looks like this:

https://cdn.shopify.com/s/files/1/0664/3037/0044/files/video

Right now, the video file has no extension at all. Using Javascript, how can I download the file with .mp4 extension. I need a way to change its filename to [filename].mp4 and then download.
I tried the following but it downloads the file without the extension.

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}

downloadURI("https://cdn.shopify.com/s/files/1/0664/3037/0044/files/video", "video.mp4");

A: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download

download only works for same-origin URLs, or the blob: and data:
schemes. If the Content-Disposition header has different information
from the download attribute, resulting behavior may differ:
If the header specifies a filename, it takes priority over a filename
specified in the download attribute. If the header specifies a
disposition of inline, Chrome and Firefox prioritize the attribute
and treat it as a download. Old Firefox versions (before 82)
prioritize the header and will display the content inline.

I tried your code on a different origin and it wouldn't download but simply redirect to the URL, also it doesn't send Content-Disposition, so it looks like since you're testing this on a different origin, it just redirects to the file link, discarding download because it's on a different origin, and your browser is configured to download it. My browser is configured to autoplay videos.
However, I see the URL you provided has CORS *, meaning any origin can access it. So, an alternative you can do is, download the file, and create a blob, then send download to browser.
function downloadURI(uri, name) {
   fetch(uri).then((response) => response.blob())
   .then((blobresp) => {
       var blob = new Blob([blobresp], {type: "octet/stream"});
       var url = window.URL.createObjectURL(blob);

       var link = document.createElement("a");
       link.download = name;
       link.href = url;
       document.body.appendChild(link);
       link.click();
       document.body.removeChild(link);
       delete link;
   })
}

downloadURI("https://cdn.shopify.com/s/files/1/0664/3037/0044/files/video", "video.mp4");

A: const myRenamedFile = new File([myFile], 'my-file-final-1-really.txt');
Taken from this website which may be a better at explaining than me:
https://pqina.nl/blog/rename-a-file-with-javascript/
alternatively, there seems to be lots of APIs or Node JS that can manage this. This will allow you to rename the file after it's been downloaded and is now a local file.


text:
Q: JMeter correct location to input a web url? - (Response time required) JMeter correct location to input a web url?

*

*Im new to Jmeter and need to get the reponse of a given url

*I need to use the URL address and not the IP address

*Is the following setup correct?

A: Your setup is fine, if hostname is blank it will be populated from the HTTP Request Defaults (same for the other fields). You can override the "defaults" on HTTP Request level if required.
Few more recommendations:

*

*In the "Advanced" tab of the HTTP Request Defaults tick "Retrieve All Embedded Resources" and "Parallel Downloads" boxes, this way JMeter will request extra resources which are referenced in the HTML like images, scripts and styles (this is what real browsers do when rendering the pages)

*Add HTTP Cache Manager to your Test Plan. Real browsers download aforementioned resources, but they do it only once, on subsequent requests images and so on are being returned form browser cache. HTTP Cache manager represents this cache and respects the relevant control headers

*Add HTTP Cookie Manager which handles user sessions and deals with cookie-based authentication

*Add HTTP Header Manager to send browser-like headers like Content-Type, User-Agent, etc.

See How To Make JMeter Behave More Like A Real Browser for above configurations explained in details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make toast when user tries to insert text longer than maximum limit? How to make a Toast to pop up when the user tries to insert text longer than maximum limit?
<EditText
    android:maxLength="28"
    ...
 />

I tried to use TextWatcher but it doesn't work properly:
public class MyActivity extends Activity implements TextWatcher
{

    // ...

    @Override
    public void afterTextChanged(Editable arg0){}

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3){}

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
    {
        if(etUsername.isFocused() && etUsername.getText().length() == 28)
            Toast.makeText(MyActivity.this, "The username must be at most 28 characters!" , Toast.LENGTH_SHORT).show();
        else if(etPassword.isFocused() && etPassword.getText().length() == 10)
            Toast.makeText(MyActivity.this, "The password must be at most 10 characters!" , Toast.LENGTH_SHORT).show();
    }
}

EDIT:
I also tried to put the code inside afterTextChanged and beforeTextChanged but it doesn't solve the problem.
EDIT2:
What I want is that the Toast only can be popped up when there are 28 characters in the EditText and the user is trying to add a 29th character. The Toast in my code above will pop up only if there are 27 characters in the TextEdit and the user inserts a 28th character.

A: The only way to achieve desired functionality is to change android:maxLength to desiredMaxLength + 1 and to check for the length in afterTextChanged(). You will have to manually delete the last character when length == desiredMaxLength + 1 (i.e. manipulate the s parameter in afterTextChanged(Editable s)). Please be careful not to put yourself in infinite loop because after changing s afterTextChanged() will be called again.

A: This solution work for my case:
    @Override
    public void afterTextChanged(Editable s) {
        if(etUsername.isFocused() && etUsername.getText().toString().trim().length() > MAX_CHARS){
        etUsername.setText(s.toString().substring(0, MAX_CHARS));
        etUsername.setSelection(s.length()-1);
            Toast.makeText(getActivity(), "Maximum number of characters reached.", Toast.LENGTH_SHORT).show();
        }
    }

Hope it helps.

A: Instead of:
if(etUsername.isFocused() && etUsername.getText().length() == 28)

Use this:
 if(arg0.length() > 28)
      {
String temp=arg0.subString(0,27)
etUsername.setText(temp);
 //Toast come's here
       }

A: Complete code is below. it is working perfectly.
String tempReview;
EditText et_userReview;
TextView tv_charactersRemaining;

Public void afterTextChanged(Editable s){

if(s.toString().length() <= 200) {
                 tv_charactersRemaining.setText(200 -   s.toString().length()+ " characters remaining");
                 tempReview = s.toString();
                 } else {
                 et_userReview.setText(tempReview);
                 Editable etext = et_userReview.getText();
                 Selection.setSelection(etext, 200);
Toast.makeText(getApplicationContext(),  "No more characters You have reached the limit.", Toast.LENGTH_SHORT).show();
                 }

}


text:
Q: Error with \DeclareRobustCommand, \usepackage{hyperref,xcolor} and \usepackage{graphicx} In order to tie capital letters with a capital hyphen, I created a command
\DeclareRobustCommand{\capitalhyphen}{\raisebox{0.24ex}{\resizebox{0.4em}{\height}{-}}\kern-0.07em}

which uses graphicx package. I'd like to use this command in \chapter and similar 'moving arguments'. This code:
\documentclass[11pt]{report}
\usepackage[utf8]{inputenc}
\usepackage[english,ukrainian]{babel}
\usepackage{graphicx}
\DeclareRobustCommand{\capitalhyphen}{\raisebox{0.24ex}{\resizebox{0.4em}{\height}{-}}\kern-0.07em}
\begin{document}
\chapter{ФІЗИКО\capitalhyphen МАТЕМАТИЧНИЙ}
\end{document}

works fine and does the job. However, adding
\usepackage[unicode]{hyperref,xcolor}
\hypersetup{citebordercolor=green,linkbordercolor=white}

to the preamble, results in an error. Ho to fix it?
UPDATE: I figured out that if we add bookmarks=false option the problem disappears. Is there any chance to use this \DeclareRobustCommand and still have bookmarks??

A: For the bookmarks macro \capitalhyphen can be redefined using \pdfstringdefDisableCommands:
\usepackage[unicode]{hyperref}
\pdfstringdefDisableCommands{%
  \def\capitalhyphen{-}%
}

A: You need to define the command in the preamble and also load graphicx package.
\documentclass[11pt]{report}
\usepackage[utf8]{inputenc}
\usepackage[english,ukrainian]{babel}
\usepackage{graphicx}
\DeclareRobustCommand{\capitalhyphen}{\raisebox{0.24ex}{\resizebox{0.4em}{\height}{-}}\kern-0.07em}
\begin{document}

\chapter{ФІЗИКО\capitalhyphen МАТЕМАТИЧНИЙ}
\end{document}

 *File List*
  report.cls    2007/10/19 v1.4h Standard LaTeX document class
  size11.clo    2007/10/19 v1.4h Standard LaTeX file (size option)
inputenc.sty    2008/03/30 v1.1d Input encoding file
    utf8.def    2008/04/05 v1.1m UTF-8 support for inputenc
   t1enc.dfu    2008/04/05 v1.1m UTF-8 support for inputenc
  ot1enc.dfu    2008/04/05 v1.1m UTF-8 support for inputenc
  omsenc.dfu    2008/04/05 v1.1m UTF-8 support for inputenc
   babel.sty    2008/07/08 v3.8m The Babel package
 english.ldf    2005/03/30 v3.3o English support from the babel system
ukraineb.ldf    2008/03/21 v1.1l Ukrainian support from the babel system
  t2aenc.dfu    2008/04/05 v1.1m UTF-8 support for inputenc
graphicx.sty    1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR)
  keyval.sty    1999/03/16 v1.13 key=value parser (DPC)
graphics.sty    2009/02/05 v1.0o Standard LaTeX Graphics (DPC,SPQR)
    trig.sty    1999/03/16 v1.09 sin cos tan (DPC)
graphics.cfg    2010/04/23 v1.9 graphics configuration of TeX Live
  pdftex.def    2011/05/27 v0.06d Graphics/color for pdfTeX
infwarerr.sty    2010/04/08 v1.3 Providing info/warning/error messages (HO)
 ltxcmds.sty    2011/11/09 v1.22 LaTeX kernel commands for general use (HO)
  t2acmr.fd    2001/08/11 v1.0a Computer Modern Cyrillic font definitions
supp-pdf.mkii
pdftexcmds.sty    2011/11/29 v0.20 Utility functions of pdfTeX for LuaTeX (HO)
ifluatex.sty    2010/03/01 v1.3 Provides the ifluatex switch (HO)
   ifpdf.sty    2011/01/30 v2.3 Provides the ifpdf switch (HO)
epstopdf-base.sty    2010/02/09 v2.5 Base part for package epstopdf
  grfext.sty    2010/08/19 v1.1 Manage graphics extensions (HO)
kvdefinekeys.sty    2011/04/07 v1.3 Define keys (HO)
kvoptions.sty    2011/06/30 v3.11 Key value format for package options (HO)
kvsetkeys.sty    2012/04/25 v1.16 Key value parser (HO)
etexcmds.sty    2011/02/16 v1.5 Avoid name clashes with e-TeX commands (HO)
epstopdf-sys.cfg    2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Live
 ***********

If you add
\usepackage[unicode]{hyperref,xcolor}
\hypersetup{citebordercolor=green,linkbordercolor=white}

You get an error that \height is undefined. hyperref needs to do a lot of normalising of characters to meet the restricted encoding allowed in pdf bookmarks. It apparently disables the latex protection mechanism to do that.
You can add \let\height\relax then you get no error but the bookmark list isn't right.  however
\usepackage{hyperref,xcolor}
\hypersetup{citebordercolor=green,linkbordercolor=white}

seems to work


text:
Q: Image doesn't show up in the edit form in symfony I have entity, edit form and a controller. The entity include a string holding the path to an image. When I render the Edit form the image file upload is always empty, even if the article have image. How can I fix this?
/**
* @var string
* @ORM\Column(name="image", type="string", length=500)
*/
private $image;

--
/**
     * @param Request $request
     *
     * @param int $id
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     *
     * @Route("admin/article/edit/{id}", name="admin_article_edit", requirements={"id": "\d+"})
     */
    public function editArticleAction(Request $request, int $id)
    {

        $article = $this->getDoctrine()
            ->getRepository(Article::class)->find($id);

        $form = $this->createForm(ArticleType::class, $article);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // Upload picture logic
            $oldPicture = $article->getImage();
            $imagePath = 'images/articles/';
            $uploadService = $this->get('picture_upload');
            $uploadService->uploadPicture($article, $oldPicture, $imagePath);

            $em = $this->getDoctrine()->getManager();
            $em->persist($article);
            $em->flush();

            return $this->redirectToRoute('article_view', array('id' => $article->getId()));
        }

        return $this->render('article/add.html.twig', array(
            'form' => $form->createView()
        ));
    }

--
$builder
->add("Title", TextType::class)
->add('Content', TextareaType::class)
->add("Image", FileType::class, array('data_class' => null));

A: I'm pretty sure this is normal behavior
If you want to show the picture have a look at How to Create a Form Type Extension
The example there is what you want!

A: Just go through this code. This may give you an idea.
public function editArticleAction(Request $request, int $id)
    {
    $article = $this->getDoctrine()
        ->getRepository(Article::class)->find($id);

    $form = $this->createForm(ArticleType::class, $article);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        // Upload picture logic

        $oldPicture = $article->getImage();
        $imagefile = $form['image']->getData();
        $imagePath = 'images/articles/';

        if(!empty($imagefile)) {

            // code for uploading new image
           ..............
           ..............

        }
        else {
              if(!empty($oldPicture)) {

                  // keep the existing one
                  ..............
                  ..............
                 // $article->setImage($oldPicture);
                  ..............
                }
        }

        $em = $this->getDoctrine()->getManager();
        $em->persist($article);
        $em->flush();

        .........
        .........


text:
Q: Set max number of messages in the queue I'm wondering is it possible to set the max number of messages in the queue?
Let's say I want to have no more than 100 msgs in queue Foo, is it possible to do?

A: Yes, it is possible.
From official documentation

The maximum length of a queue can be limited to a set number of
  messages by supplying the x-max-length queue declaration argument with
  a non-negative integer value.

AFAIK, pika's channel.queue_declare has queue_declare has arguments argument which is definitely what you want.

A: Do it like this and be happy!
import pika

QUEUE_SIZE = 5

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.queue_declare(
    queue='ids_queue',
    arguments={'x-max-length': QUEUE_SIZE}
)

Here in arguments you will also need to track queue overflow behaviour for your queue.


text:
Q: simple but not obvious identity in calculus I'm having a little difficulty understanding this identity while studying for my calculus of variation exam.
\begin{equation}
y'\delta y' = -y''\delta y
\end{equation}
Can someone please explain this?

A: These sorts of statements have to be considered within the context of integrals. In the calculus of variations the variation itself is usually taken to vanish at the end points of the integration.
Consider the following expression,
$$ \int_{a}^b y' \delta y' \ dt ,$$
we will perform integration by parts. Recall that the formula is $\int_a^b u \ dv = (uv)_a^b - \int_a^b v du$. We will choose $u=y'$ and $dv=\delta y'\ dt$.
$$ \int_{a}^b y' \delta y' \ dt = (y' \delta y)_a^b - \int_a^b y'' \delta y \ dt$$
since the variation vanishes at $t=a$ and $t=b$ the boundary term vanishes leaving us with,
$$ \int_{a}^b y' \delta y' \ dt = \int_a^b \Big( -y'' \delta y \Big) \ dt,$$
from this we can see that in the appropriate context $y'\delta y'$ is equivalent to  $-y'' \delta y$. As a short hand we say $y' \delta y' = -y'' \delta y$.


text:
Q: C S-function to read data from serial After issues I met, trying to read from COM port with Simulink, as I wrote in this discussion, I would like to follow Phil Goddard's suggestion on writing a C S-function for that. My problem is that I am not able to write C-code, so I hope in some help from you.
I have found this two scripts on the net about C S-function for serial communication:
1)
#define S_FUNCTION_NAME sfun_comport

#define S_FUNCTION_LEVEL 2

#include "simstruc.h"

#include "windows.h"

#include "Strsafe.h"

#define MDL_START

#if defined(MDL_START)

/* Function: mdlStart =================================================*/
static void mdlStart(SimStruct *S)
{
    HANDLE hCom;
    DCB dcb;
    COMMTIMEOUTS uCtm;
    char pcCommPort[10];
    uint8_T comport = 4;
      //-------------------------------------------------------------------
      StringCbPrintfA((STRSAFE_LPSTR)&pcCommPort,
                      sizeof(pcCommPort),
                      "COM%d",
                      comport);
      //-------------------------------------------------------------------
      hCom = CreateFileA (pcCommPort,
                          GENERIC_READ | GENERIC_WRITE,
                          0,
                          NULL,
                          OPEN_EXISTING,
                          0,
                          NULL);
      if (hCom == INVALID_HANDLE_VALUE)
      {
          ssSetErrorStatus(S,"COM-Port konnte nicht geoeffnet werden!");
          return;
      }
      //-------------------------------------------------------------------
      SecureZeroMemory(&dcb, sizeof(dcb));
      memset(&dcb, 0, sizeof(dcb));
      dcb.DCBlength = sizeof(dcb);
      dcb.BaudRate  = (uint16_T)9600;
      dcb.ByteSize  = 8;
      dcb.Parity    = NOPARITY;
      dcb.StopBits  = ONESTOPBIT;
      //-------------------------------------------------------------------
      uCtm.ReadIntervalTimeout         = MAXDWORD;
      uCtm.ReadTotalTimeoutMultiplier  = 0;
      uCtm.ReadTotalTimeoutConstant    = 0;
      uCtm.WriteTotalTimeoutMultiplier = 0;
      uCtm.WriteTotalTimeoutConstant   = 0;
      //-------------------------------------------------------------------
      if ((!SetCommState(hCom, &dcb)) | (!SetCommTimeouts(hCom, &uCtm)))
      {
          CloseHandle(hCom);
          ssSetErrorStatus(S,"Konfigurationsfehler des COM-Ports!");
          return;
      }
      //-------------------------------------------------------------------
      ssSetPWorkValue(S, 0, hCom);
  }
#endif
/* Function: mdlOutputs =================================================*/

static void mdlOutputs(SimStruct *S, int_T tid) {

    const real_T *u0 = (const real_T*) ssGetInputPortSignal(S,0);
    real_T       *y0 = ssGetOutputPortSignal(S,0);
    HANDLE hCom = (HANDLE*)ssGetPWorkValue(S, 0);
    uint32_T read_cnt;
    uint32_T write_cnt;
    char getbuffer[] = "test";
    char putbuffer[] = "Dies ist ein Test\r";
    //int i;
    //---------------------------------------------------------------------
    read_cnt = sizeof(putbuffer)-1;
    ReadFile(hCom, putbuffer, read_cnt, &read_cnt, NULL);
    //---------------------------------------------------------------------
    write_cnt = sizeof(putbuffer)-1;
    WriteFile(hCom, putbuffer, write_cnt, &write_cnt, NULL);
    //---------------------------------------------------------------------
    Sleep(3000);
}
#define MDL_UPDATE

#if defined(MDL_UPDATE)

/* Function: mdlUpdate ================================================*/
static void mdlUpdate(SimStruct *S, int_T tid)
{
}
#endif
/* Function: mdlTerminate ===============================================*/

static void mdlTerminate(SimStruct *S) {

    CloseHandle((HANDLE*)ssGetPWorkValue(S, 0));
}

#ifdef  MATLAB_MEX_FILE    /* Is this file being compiled as a MEX-file? */
#include "simulink.c"      /* MEX-file interface mechanism */
#else
#include "cg_sfun.h"       /* Code generation registration function */
#endif

But when I try to compile it by mex sfun_comport.c it returns following errors:
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(449) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(1692) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(1701) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(1724) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2373) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2380) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2393) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2402) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2408) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2448) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2459) : error C2065: 'mdlInitializeSizes' : undeclared identifier
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2459) : warning C4047: '=' : 'mdlInitializeSizesFcn' differs in levels of indirection from 'int'
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2548) : error C2065: 'mdlInitializeSampleTimes' : undeclared identifier
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2548) : warning C4047: '=' : 'mdlInitializeSampleTimesFcn' differs in levels of indirection from 'int'
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2679) : warning C4013: 'mdlInitializeSizes' undefined; assuming extern returning int
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2948) : warning C4013: 'mdlInitializeSampleTimes' undefined; assuming extern returning int

  C:\PROGRA~1\MATLAB\R2013B\BIN\MEX.PL: Error: Compile of 'sfun_comport.c' failed.

2)
#define S_FUNCTION_NAME  sfun_tryserial
#define S_FUNCTION_LEVEL 2

#include "simstruc.h"
#include "windows.h"
#include "strsafe.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"

static void mdlStart(SimStruct *S)
{
    HANDLE hCom;
    DCB dcb;
    COMMTIMEOUTS uCtm;
    char pcCommPort[12];
    //char pcCommPort[10]="COM4";
    uint8_T comport = mxGetScalar(ssGetSFcnParam(S, 0));

    StringCbPrintfA((STRSAFE_LPSTR)&pcCommPort, sizeof(pcCommPort), "COM%d:", comport);
    //---------------------------------------------------------------
    hCom = CreateFileA (pcCommPort,
               GENERIC_READ | GENERIC_WRITE,
               0,
               NULL,
               OPEN_EXISTING,
               0,
               NULL);

    if (hCom == INVALID_HANDLE_VALUE)
    {
   ssSetErrorStatus(S,"COM-Port konnte nicht geoeffnet werden!");
        return;
    }
    //---------------------------------------------------------------
    SecureZeroMemory(&dcb, sizeof(dcb));
    memset(&dcb, 0, sizeof(dcb));
    dcb.DCBlength = sizeof(dcb);
    dcb.BaudRate = (uint16_T)9600;
    dcb.ByteSize = 8;
    dcb.Parity = NOPARITY;
    dcb.StopBits = ONESTOPBIT;
    //dcb.fDtrControl = 0X01; //ENABLE
    //dcb.fRtsControl = 0x01; //ENABLE
    //---------------------------------------------------------------
    uCtm.ReadIntervalTimeout = MAXDWORD;
    uCtm.ReadTotalTimeoutMultiplier = 0;
    uCtm.ReadTotalTimeoutConstant = 0;
    uCtm.WriteTotalTimeoutMultiplier = 0;
    uCtm.WriteTotalTimeoutConstant = 0;
    //---------------------------------------------------------------
    if ((!SetCommState(hCom, &dcb)) | (!SetCommTimeouts(hCom, &uCtm)))
    {
        CloseHandle(hCom);
        ssSetErrorStatus(S,"Konfigurationsfehler des COM-Ports!");
        return;
    }
    //---------------------------------------------------------------
    ssSetErrorStatus(S,"Konfigurationsfehler des COM-Ports!");
    ssSetPWorkValue(S, 0, &hCom);
}

static void mdlOutputs(SimStruct *S, int_T tid)
{
    const real_T   *u0 = (const real_T*)ssGetInputPortSignal(S, 0);
    real_T           *y0 = (real_T *)ssGetOutputPortRealSignal(S, 0);

    uint32_T read_cnt;
    uint32_T write_cnt;
    char getbuffer[255] = {0};
    char putbuffer[255] = {0};

    HANDLE hCom = (HANDLE*)ssGetPWorkValue(S, 0);

    //++++++++++++++++++++++++++++++++++++++++++++++
    if (ReadFile(hCom, getbuffer, sizeof(getbuffer), &read_cnt, NULL))
    {
        // Daten auswerten, read_cnt enthält die Anzahl gelesener Bytes
    }
    else
    {
        // keine Daten empfangen
        // z.B. Fehlermeldung oder nix machen
    }
     //++++++++++++++++++++++++++++++++++++++++++++++
    if (!WriteFile(hCom, putbuffer, write_cnt, &read_cnt, NULL));
    {
        // Fehlermeldung, weil die Daten nicht verschickt werden konnten
    }
    //++++++++++++++++++++++++++++++++++++++++++++++
}

static void mdlTerminate(SimStruct *S)
{
    CloseHandle((HANDLE*)ssGetPWorkValue(S, 0));
}

#ifdef  MATLAB_MEX_FILE    /* Is this file being compiled as a MEX-file? */
#include "simulink.c"      /* MEX-file interface mechanism */
#else
#include "cg_sfun.h"       /* Code generation registration function */
#endif

This produces:
sfun_tryserial.c(20) : warning C4244: 'initializing' : conversion from 'double' to 'uint8_T', possible loss of data
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(449) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(1692) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(1701) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(1724) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2373) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2380) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2393) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2402) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2408) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2448) : warning C4995: 'sprintf': name was marked as #pragma deprecated
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2459) : error C2065: 'mdlInitializeSizes' : undeclared identifier
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2459) : warning C4047: '=' : 'mdlInitializeSizesFcn' differs in levels of indirection from 'int'
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2548) : error C2065: 'mdlInitializeSampleTimes' : undeclared identifier
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2548) : warning C4047: '=' : 'mdlInitializeSampleTimesFcn' differs in levels of indirection from 'int'
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2679) : warning C4013: 'mdlInitializeSizes' undefined; assuming extern returning int
C:\Program Files\MATLAB\R2013b\simulink\include\simulink.c(2948) : warning C4013: 'mdlInitializeSampleTimes' undefined; assuming extern returning int

  C:\PROGRA~1\MATLAB\R2013B\BIN\MEX.PL: Error: Compile of 'sfun_provaseriale2.c' failed.

As you can notice common errors between two S-function are about:
'mdlInitializeSizes'
'mdlInitializeSizesFcn'
'mdlInitializeSampleTimes'
'mdlInitializeSampleTimesFcn'
'mdlInitializeSizes'

Do you have some suggestion to fix those errors ?
PS: I have MATLAB 2013b 64-bit, 64-bit Windows 7, Microsoft Visual C++ 2010 (32-bit) as compiler (it has worked fine in 64-bit matlab to produce mex files)

A: You still have to write those functions by yourself. As you can see from their names, they define the sizes and sample time of the S-Function. They are required components of a complete and functional S-Function.
For example:
static void mdlInitializeSizes(SimStruct *S) describes the sizes information that is used by Simulink to determine the S-function block's characteristics (number of inputs, outputs, states, etc.).
static void mdlInitializeSampleTimes(SimStruct *S) is used to specify the sample time(s) for your S-function.
See also:
http://de.mathworks.com/help/simulink/sfg/mdlinitializesizes.html
http://de.mathworks.com/help/simulink/sfg/mdlinitializesampletimes.html


text:
Q: Caliburn Micro - Text in TextBox wont display I am working my way through an old Caliburn Micro tutorial (here). I am up to part 2 (here). I've managed to update the App.xaml and AppBootstrapper.cs to be compatible with 3.0.3 and WPF (as outlined under the section 'WPF' on the 'Documentation' page here). I am using VS 2013.
The tutorial shows the app having the value '50' appearing after initialization. My app just shows this:

Here is the code so far:
App.xaml
<Application
xmlns:local="clr-namespace:CaliburnMicroApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class=" CaliburnMicroApp.App">
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary>
                <local:AppBootstrapper x:Key="bootstrapper" />
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

AppViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;

namespace CaliburnMicroApp.ViewModels
{
    class AppViewModel : PropertyChangedBase
    {
        private int _count = 50;

        private int Count
        {
            get { return _count; }
            set
            {
                _count = value;
                NotifyOfPropertyChange(() => Count);
                NotifyOfPropertyChange(() => CanIncrementCount);
            }
        }

        public void IncrementCount()
        {
            Count++;
        }

        public bool CanIncrementCount
        {
            get { return Count < 100; }
        }
    }
}

AppView.xaml
<UserControl x:Class="CaliburnMicroApp.Views.AppView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
    <Grid Width="300" Height="300" Background="LightBlue">
        <RepeatButton Name="IncrementCount" Content="Up" Margin="15" VerticalAlignment="Top" />
        <TextBlock Name="Count" Margin="20" FontSize="150" VerticalAlignment="Center" HorizontalAlignment="Center" />
    </Grid>
</UserControl>

AppBootstrapper.cs
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using CaliburnMicroApp.ViewModels;
using System.Windows;

namespace CaliburnMicroApp
{
    public class AppBootstrapper : Caliburn.Micro.BootstrapperBase
    {
        public AppBootstrapper()
        {
            Initialize();
        }

        protected override void OnStartup(object sender, StartupEventArgs e)
        {
            DisplayRootViewFor<AppViewModel>();
        }
    }
}

A: Change your Count property in your AppViewModel to public.


text:
Q: A question about continuous functions Let $f:B \longrightarrow \mathbb{R}^n$ a continuous and injective function from closed ball in $\mathbb{R^n}$ to $\mathbb{R}^{n}$. I'd like to know $f$ has to maps the boundary $\partial B$ in the boundary $\partial f(B)$?
Thank you.

A: Note that $f(B)^{\circ}$, the interior of $f(B)$, is open so $f^{-1}(f(B)^{\circ})$ is an open subset of $B$. Furthermore, $f^{-1}(f(B)^{\circ}) \subseteq f^{-1}(f(B))$ and $f^{-1}(f(B)) = B$ as $f$ is injective, so $f^{-1}(f(B)^{\circ}) \subseteq B^{\circ}$.
Now let $x \in \partial B =\overline{B}\setminus B^{\circ}$, then $x \notin f^{-1}(f(B)^{\circ})$ so $f(x) \notin f(B)^{\circ}$. However $f(x) \in f(B)$ and hence $f(x) \in \overline{f(B)}$, so $f(x) \in \overline{f(B)}\setminus f(B)^{\circ} = \partial f(B)$.


text:
Q: What should be there in the variable REGISTRY_AUTH_TOKEN_REALM, if you use an external docker? I try configure Gitlab to use an Docker registry
Read article:

How to setup omnibus installation to use an external Docker registry?
But this articles about native docker registry.
Does anyone have an article on setting configure Gitlab to use an Nexus Docker registry?
docker run --rm -it -p 443:5000 --name registry \
  -v /var/docker-registry-data:/var/lib/registry \
  -v /var/docker-registry-certs:/certs \
  -v /etc/gitlab/registry-certs:/etc/gitlab/registry-certs \
  -e REGISTRY_AUTH_TOKEN_REALM="what's supposed to be here?" \
  -e REGISTRY_AUTH_TOKEN_SERVICE=container_registry \
  -e REGISTRY_AUTH_TOKEN_ISSUER=gitlab-issuer \
  -e REGISTRY_AUTH_TOKEN_ROOTCERTBUNDLE=/etc/gitlab/registry-certs/registry-auth.crt \
  -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/fullchain.pem \
  -e REGISTRY_HTTP_TLS_KEY=/certs/privkey.pem \
  --name docker-registry \
  registry:2

What should be there in the variable REGISTRY_AUTH_TOKEN_REALM?

A: To configure the registry to use the token mechanism, you should configure the following options:
auth:
token:
realm: The authentication end point.
service: The service name.
issuer: The issuer of the request, must match the issuer in the authentication service configuration.
rootcertbundle: The certificate bundle which its public key used to sign the token.
So now if we want to run the registry container:
-e REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY=/var/lib/registry \
-e REGISTRY_AUTH=token \
-e REGISTRY_AUTH_TOKEN_REALM=https://registry.example.com:5001/auth \
-e REGISTRY_AUTH_TOKEN_SERVICE="Docker registry" \
-e REGISTRY_AUTH_TOKEN_ISSUER="Auth Service" \
-e REGISTRY_AUTH_TOKEN_ROOTCERTBUNDLE=/ssl/server.pem \
-v /root/auth_server/ssl:/ssl \
-v /root/docker_registry/data:/var/lib/registry \
--restart=always \
--name registry registry:2```


text:
Q: export records from gridview to excel in asp.net? I want to export the records from my gridview to excel by only using vb.net as the programming language. I've seen a lot of codes using C# but I am not a C# practitioner, I only use vb.net.
here it is sir ZedBee

<form id="form1" runat="server">

    <asp:GridView ID="tblreport" runat="server" CellPadding="4" ForeColor="#333333"

        style="z-index: 1; left: -1px; top: 0px; position: absolute; height: 1px; width: 880px"
        BorderColor="Black">
        <AlternatingRowStyle BackColor="White" />
        <EditRowStyle BackColor="#7C6F57" />
        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#E3EAEB" />
        <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F8FAFA" />
        <SortedAscendingHeaderStyle BackColor="#246B61" />
        <SortedDescendingCellStyle BackColor="#D4DFE1" />
        <SortedDescendingHeaderStyle BackColor="#15524A" />
    </asp:GridView>

    <asp:Button ID="Button1" runat="server"
        style="z-index: 1; left: 410px; top: 396px; position: absolute; height: 26px;"
        Text="Generate" />
    <asp:Button ID="Button2" runat="server"
        style="z-index: 1; left: 511px; top: 395px; position: absolute; width: 70px"
        Text="Cancel" />
    <asp:TextBox ID="TextBox1" runat="server"
        style="z-index: 1; left: 182px; top: 65px; position: absolute"></asp:TextBox>
    <asp:DropDownList ID="dditem" runat="server"
        DataSourceID="SqlDataSource1" DataTextField="TABLE_NAME"
        DataValueField="TABLE_NAME"
        style="z-index: 1; left: 83px; top: 32px; position: absolute">
    </asp:DropDownList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:dbapproveditemConnectionString %>"
        ProviderName="<%$ ConnectionStrings:dbapproveditemConnectionString.ProviderName %>"
        SelectCommand="SELECT TABLE_NAME FROM information_schema.COLUMNS WHERE (TABLE_SCHEMA = 'dbitem') AND (ORDINAL_POSITION = 1)">
    </asp:SqlDataSource>
    <asp:Button ID="Button3" runat="server"
        style="z-index: 1; left: 330px; top: 62px; position: absolute; width: 62px"
        Text="OK" />
    <asp:DropDownList ID="DropDownList2" runat="server"

        style="z-index: 1; left: 82px; top: 65px; position: absolute; height: 16px; width: 79px;">
        <asp:ListItem>Status</asp:ListItem>
    </asp:DropDownList>

</form>

A: Try this
     response.ClearHeaders()
    'first let's clean up the response.object
    response.Clear()
    response.Charset = ""
    'set the response mime type for excel
    response.ContentType = "application/vnd.ms-excel"

     strfileName = "InActiveContactOptions"

    'response.AddHeader("Content-Disposition", "inline;filename=ContactOptions.xls")
    response.AddHeader("Content-Disposition", "inline;filename=" + strfileName + ".xls")
    'create a stringwriter
    Dim stringWrite As New System.IO.StringWriter
    'create an htmltextwriter which uses the stringwriter
    Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
    'instantiate a datagrid
    Dim dg As New DataGrid
    'set the datagrid datasource to the dataset passed in
    dg.HeaderStyle.BackColor = Drawing.Color.Gray
    dg.HeaderStyle.ForeColor = Drawing.Color.White
    dg.Caption = _Caption
    dg.CaptionAlign = TableCaptionAlign.Left
    dg.AlternatingItemStyle.BackColor = Drawing.Color.Ivory
    dg.DataSource = ds.Tables(0)
    'bind the datagrid
    dg.DataBind()
    'tell the datagrid to render itself to our htmltextwriter
    dg.RenderControl(htmlWrite)
    'all that's left is to output the html
    response.Write(stringWrite.ToString.Replace(" ", ""))
    response.End()

A: This blog post has vb.net code for exporting data to excel.
The error can be solved by overridding VerifyRenderingInServerForm in code behind. Please read the comments in the blog.

A: Did you try this code?

IT worked for me in C#, I just convert it to VB using an online conveter

Add this in your export button click event
Dim filename As String = "Test.xls"
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)

'Get the H`enter code here`TML for the control.
yourGrid.RenderControl(hw)
'Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", "attachment; filename=" & filename & "")

Response.Write(tw.ToString())

Original source: https://stackoverflow.com/a/11308445/1196411

A:     Response.Clear()
    Response.AddHeader("content-disposition", "attachment;filename=" + "Name of excel" + ".xls")
    Response.Charset = ""
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.ContentType = "application/vnd.ms-excel" ' for excel 2003
    'Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ' for excel 2007
    Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter()
    Dim htmlWrite As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(stringWrite)
    Dim gv As System.Web.UI.WebControls.GridView = New System.Web.UI.WebControls.GridView()
    gv.DataSource = dt
    gv.DataBind()

    gv.HeaderRow.Style.Add("background-color", "#FFFFFF")
    gv.HeaderRow.Style.Add("Height", "30px")

    For i As Integer = 0 To gv.HeaderRow.Cells.Count - 1 Step i + 1
        gv.HeaderRow.Cells(i).Style.Add("background-color", "#f5f5f5")
    Next

    Dim i1 As Integer = gv.HeaderRow.Cells.Count - 1
    For i As Integer = 0 To gv.Rows.Count - 1
        Dim row As GridViewRow = gv.Rows(i)
        'Change Color back to white
        row.BackColor = System.Drawing.Color.White
        'Apply text style to each Row
        row.Attributes.Add("class", "textmode")
        'Apply style to Individual Cells of Alternating Row
        If i Mod 2 <> 0 Then
            For i0 As Integer = 0 To i1
                row.Cells(i0).Style.Add("background-color", "#F2F2F2")
            Next
        End If
    Next
    gv.RenderControl(htmlWrite)
    'style to format numbers to string
    Dim style As String = ""
    Response.Write(style)
    Response.Output.Write(stringWrite.ToString())
    Response.Flush()
    Response.End()


text:
Q: How to solve Unknown package x3270.sh exit code 127 error when updating Cygwin I got this error when I updated Cygwin.

As a new Cygwin user I don't understand much. Is this a critical error? Is there any crucial problem if I can't fix it?

A: If you just want to get rid of this message remove the /etc/postinstall/x3270.sh file. If you want to clear everything, install the x3270 package, then remove the x3270 and suite3270 packages. source


text:
Q: I am Legend: does alternative ending suggest rebuilding of society? The alternate ending as well as earlier scenes show more intelligence in the Dark Seekers than Neville imagined — he seemed really stuck on the idea that they were very diminished mentally even when confronted with some counter-evidence in front of the Vanderbilt statue (the trap).
Now the alternate ending shows the alpha grudgingly forgiving or at least not killing Neville and taking back his mate; but does this imply that the Dark Seekers such as those he leads are firstly, no longer a danger to any hypothetically surviving humans (which Neville doesn't really believe in — he is certain, even after he meets the woman and the boy, that no colony of humans exists, anywhere...) and secondly, bright enough to begin rebuilding (as in Matheson's original book they were — they were just as intelligent as humans because the living ones were actually human, just infected; dead ones were animated corpses but not zombies because they retained some intelligence)?
I saw that the Dark Seekers who attacked Neville's townhouse as still very violent, and their behavior was clearly influenced by the virus. The alpha seemed to communicate with his underlings by screeching and violently throwing them around. (In the lab, this was how he "told" them not to attack Neville.) My sense is that they still live by hunting (I guess animals like deer) and are making no attempts to rebuild. And if they came across a colony of survivors, well, just too bad for the humans. It is kind of surprising then that they would spare Neville, and perhaps this is why the alternate ending was not shown — it does not quite make sense.

A: The 2007 film I Am Legend was the third adaptation of Robert Matheson's 1954 novel of the same name.  The novel practically created the whole vampire/zombie apocalypse genre of horror/SF.  The previous adaptations were The Last Man on Earth (1964) starring Vincent Price (available to watch online on the Internet Archive) and The Omega Man starring Charlton Heston.  Both of them are very loose adaptations.  Matheson worked on early iterations of the script for The Last Man on Earth, but he was unhappy with the direction that later revisions took and had his name taken off the project.  The Omega Man deviated even more from the novel's story.
I mention all this history to illustrate something significant about the 2007 film.  For the first time, the filmmakers decided to keep Matheson's original title.  The previous adaptations had used titles emphasizing their protagonists' roles as the last man left alive.  In contrast, the book title "I Am Legend"—although it is only explained at the very end of the story—is about how Robert Neville is actually, from the point of view of the new vampire society, the last legendary monster.  The name only makes sense in a context where there is a new world of vampires emerging.  So the facts that the film kept the book's title and that the original ending showed the vampires exhibiting some higher-level behavior strongly suggest that they did mean to show that the infected were beginning to rebuild their new world.


text:
Q: Remove alpha compositing knowing the watermark (revert/compensate) I have watermarked a bunch of images image with PIL (PILLOW in fact).
I have the original watermark and I know exactly how it has been resized and pasted on the image (0.75 opacity). The watermark is essentially black, white and red.
I want to restore images as close as possible as they were originally.

*

*Is there any chance I could do that automatically?

*What about quality? Is it worth it? Do you have examples of the result of such a process?

If so, how would I manage to do this?
Here is the code I used to watermark the image:
logo = Image.open(path)
red, green, blue, alpha = logo.split()
alpha = ImageEnhance.Brightness(alpha).enhance(0.75)
logo.putalpha(alpha)

img = Image.open('...')
img = Image.composite(logo, img, logo)

A: I've made a mask with of my logo and use GIMP's G'MIC plugin : http://blog.patdavid.net/2014/02/getting-around-in-gimp-gmic-inpainting.html
Here is as far as I can get, which is not really good enough:

This has been made with inpainting technic, but I am sure I could somehow exploit the fact that my watermark is somewhat transparent.

A: I've also tried to unblend the picture, given the watermark and watermarked pictures as input.
Unforunately, the watermarked picture being compressed in jpeg, I couldn't get any better than this :


text:
Q: Chart's Y-axis does not re-render properly in Billboard.js There is a chart generated in Billboard.js which has the possibility to introduce custom values as minimum and maximum for the Y-axis.
The problem that I encounter is that even the axis is changing when the values are modified, they are not very close to the introduced value.
For example this screenshot:

On the maximum value I don't think it is a great problem. But on the minimum one it is. The default value was 0, after there was introduced 300 I would expect to start from a closer value to it, not 0 as before. The Y-axis just moved few pixels after that change.
The html code:
<input type="number" ng-change="$ctrl.updateY('max')" ng-model="$ctrl.max">

The JS code:
updateY(val) {
    if(val=== 'max') {
        if(this.max || this.max === 0) {
            this.maxValue = this.max;
        }
    } else {
        if(this.min || this.min === 0) {
            this.minValue = this.min;
        }
    }
    const maxNumber = Number(this.maxValue);
    const minNumber = Number(this.minValue);
    this.lineView.chart.axis.range({max: {y: maxNumber}, min: {y: minNumber}});
    this.resetY = false;
}

This is the code for max, same one for min.
I think that maybe the problem is from range, it doesn't generate the Y-axis with the values introduced.
Any suggestions?

A: It is rendering much closer to the introduced values if it is added a padding in bb.generate:
const chart = bb.generate({
...
"axis": {
...
"y": {
...
        "padding" : {
        top: 0,
        bottom: 10
        }

...


text:
Q: c++, syntax for passing parameters This code snippet is part of an isapi redirect filter written in managed c++ that will capture url requests with prefix "http://test/. Once the url is captured it will redirect those request to a test.aspx file i have at the root of my web app.
I need some syntax help how to:
1) pass the "urlString" parameter to be displayed in my "test.aspx" page. Problem line:
urlString.Replace(urlString, "/test.aspx?urlString");
2) syntax for my aspx page to display urlString
   DWORD CRedirectorFilter::OnPreprocHeaders(CHttpFilterContext* pCtxt,
            PHTTP_FILTER_PREPROC_HEADERS pHeaderInfo)
        {
            char buffer[256];
            DWORD buffSize = sizeof(buffer);
            BOOL bHeader = pHeaderInfo->GetHeader(pCtxt->m_pFC, "url", buffer, &buffSize);
            CString urlString(buffer);
            urlString.MakeLower(); // for this exercise

            if(urlString.Find("/test/") != -1)  //insert url condition
        {

            urlString.Replace(urlString, "/test.aspx?urlString");

                char * newUrlString= urlString.GetBuffer(urlString.GetLength());
                pHeaderInfo->SetHeader(pCtxt->m_pFC, "url", newUrlString);
                return SF_STATUS_REQ_HANDLED_NOTIFICATION;
            }
        //we want to leave this alone and let IIS handle it
            return SF_STATUS_REQ_NEXT_NOTIFICATION;
        }

-------------- aspx page

<html>
<body>
<%
dim url as string = request.querystring("urlString")
response.write(url)

%>
</body>
</html>

A: The CString::Replace method takes the string-to-be-replaced and the string-to-be-put-in-place as arguments.  s.Replace( "foo", "bar" ) will convert "tadafoo" into "tadabar".
Now your code will replace "anystring" with "/test.aspx?urlString".  Literally.
My guess is that you want your url to be appended to the "/text.aspx" url as a GET argument, in which case you can do this:
CString newurl = "/text.aspx?urlString=";
newurl += urlString;

This will compose the url "/test.aspx?urlString=http://test/somethingelse.html": a GET request with a variable named "urlString" containing your original url.
Your asp should read the GET urlString variable with the request.QueryString[ "urlString" ] as to be read on this website, and looks just fine otherwise,  But I'm not really into that.

A: Your problem line of
urlString.Replace(urlString, "/test.aspx?urlString");

is trying to replace the entire urlString with "/test.aspx?urlString" .
To achieve this can't you just replace it with the following?
urlString = "/test.aspx?urlString";

A: Based on your comments in the other answers, it sounds like you want:
CString newurl = "/test.aspx?UrlString=";
newurl += urlString;


text:
Q: wp functions not being recognized in cron job Setting:
I have a wordpress site but disabled wp_cron to have the full control of cron.
define('DISABLE_WP_CRON', true);

In crontab -e, I have following cron job:
*/2 * * * * /usr/bin/php /var/www/cron/mycron.php init >> /var/log/error.log 2>&1

The mycron.php has a simple function
if (!empty($argv[1])) {
    switch ($argv[1]){
    case 'init':
        cron_test();
        break;
    }
}
function cron_test() {
    $time = date(DATE_RFC822, time());
    write_log("Start:" . $time);   //outputs debug to my own log file
};

function write_log($log){
    if ( true === WP_DEBUG ) {
        if ( is_array( $log ) || is_object( $log ) ) {
            write_log( print_r( $log, true ) );
        } else {
            write_log( $log );
        }
    }
};

Note that I declared the mycron.php in functions.php for wp:
require_once('parts/mycron.php');

Error log:
In my error.log for the cron, I have the following error:
PHP Warning:  Use of undefined constant WP_DEBUG - assumed 'WP_DEBUG'

So, I am guessing there is some sort of disconnection between cron and wp, which is my best guess.
What I am trying to do:
The mycron.php will have many wordpress functions that I would need. How do I make the cron to recognize the wp function such as WP_DEBUG?
Any help will be much appreciated.
Thanks!

A: You need to load Wordpress functions manually, to use them in a custom script.
require_once("../../../../wp-load.php");

Also answered in depth here,
How to include Wordpress functions in custom .php file?


text:
Q: Is it possible (and safe/reliable/non-damaging) to use a 20-pin ATX PSU with a 24-pin ATX motherboard? I have a reasonably-decent old 20-pin PSU which I want to use on a newer 24-pin ATX motherboard.
I see that the

ATX page on wikipedia
mentions that 24-pin ATX is backward-compatible, and I can find 20-to-24 pin adapters to buy for a couple of dollars/pounds at lots of places, but I can't find any mention of restrictions on the use of these.
Will this work on any motherboard, or is it a per-motherboard compatibility question?
Are there any other restrictions like the level of power available (and hence the additional 4 pins with +12, +5 and +3.3V lines which are already on other pins)?

A: I have no exact information to provide you here, but my gut feel would be that you should only consider trying this if you have a relatively low-power system on the motherboard. Something with not too much memory, ideally no more than 1 hard-disk, and probably not too high-end a dual-core processor... if you have any kind of modern graphics card installed I would probably not even consider going there.
Note that what the 24-pin supply does, is add one additional supply line of +3.3V, +5V and +12V each. If you use the adapter you suggest it will copy one or more of the existing lines to supply these pins... which means that they need to share the additional load.
From having a look at the Wikipedia page you reference, it looks like the standard 20 pins have a decent number of +5V and +3.3V lines already, but there is only one +12V line, which gets duplicated by the extra 4 pins. I do not know offhand what hardware uses the +12V, but that would be my main stability concern when using the splitter attachment.

A: I used a 20 pin power supply on a motherboard with a 24 pin socket for years with no problems at all.
I had forgotten all about it until this last weekend when I replaced the PSU (failing fan) and had to remove a sticker that the manufacturer had placed over the last 4 pins (with a little graphic indicating that they were needed only with a 24 pin PSU).
This was with an AMD Athlon64 X2 4800+ CPU, mobo video, 4GB RAM in 2 sticks, 3 hard disks, DVD writer and commonly running 7 USB devices, 6 of which are powered from the computer.
In retrospect, I am a little surprised.

A: It is not recommended as exceeding the current draw available will cause the PSU to either lower voltages (which could damage components) or simply shutdown in overload. My recommendation is to buy a new PSU. Really, they're not expensive.
However, if the motherboard has a Molex socket, then use that as well as the 20-pin plug and you'll be fine. There also used to be adapters from a Molex socket to the 4-pin extension, which would also be fine.

A: A motherboard could work with just a 20-pin connector plugged in. Likely failure, if it fails, is the ATX silver box will shut down. Although, you need to accept the risk as solely your own when you do this.
In order to answer the question, we need to know what the motherboard specifications are for current draw from the power connector for each voltage rail, the specifications of the power supply, and what else you have powered by the power supply.

*

*An ATX silver box power supply, PSU, will have specifications rating how much current it can supply on each power rail (12V, 5V, 3.3V, -12V, 5Vstandby). Sometimes 12V is shared or split into different rails with different ratings.

*Motherboard manufacturer's typically don't break out their requirements to the detail necessary, though. You'd need the max requirements for each power rail as well for comparison.

A: There has been (which was starting when this question was written but has become even more so in the years since) a trend in PC hardware design away from 3.3V and 5V and towards 12V. The modern low voltage (often less than 1V) electronics can only practically be supplied by point of load converters and it's more efficient to run those power converters off a 12V input than a 5V input.
Unfortunately the ATX power connector was designed in the days when 3.3V and 5V dominated. The 20 pin ATX power connector only has one 12V pin, the 24 pin connector has two.
The CPU has it's own 12V connector so we don't have to worry about that but we do have to worry about general motherboard loads and any expansion cards. IIRC a PCIe graphics card is allowed to draw up to 75W from the motherboard (beyond that they use a supplementry connnection to the power supply).
Add a PCIe graphics card to the various loads on the motherboard and you are up to arround 100W or so.
A mini fit JR is supposed to be good for 9A. The newer mini fit HCS (which is pin compatible but higher rated and is reccommended by the ATX12V 2.0 standard) is rated a little bit higher. 9A at 12V works out to 108W.  Unfortunately however PC vendors don't tend to use genuine molex connectors. They use cheap copies which often can't handle the current.
So in summary.

*

*In a machine without a graphics card a 20 pin PSU will almost certainly be fine.

*In a machine with a single graphics card it's borderline, a 20 pin PSU should be ok if all the parts are high quality and in good condition but there is a real risk of burnout.

*In a machine with SLI/Crossfire using a 20 pin PSU would be a very dumb idea.

The adaptors you mention aren't strictly needed, you can just plug the connector straight in. The advantage of using an adaptor is that if you do burn out a pin it's a pin on an adaptor rather than a pin on the motherboard which is easier to deal with.


text:
Q: What value (Cookie, SessionID, variable) best represents a WIF Session? I want to track a user's logon session from the time they login to my site, to the time they logoff.
Is there a pre-existing cookie I should use, or variable?  I thought of using ASP.NET sessionIDs but read on StackOverflow that these numbers may change.
I would save my own Session cookie, but I don't want to do something that could be done more efficiently another way.  I'm using Windows Identity Foundation (WIF) to handle my authentication layer.
The only cookie I see in fiddler is a FedAuth cookie so I assume that I might be able to derive some valuable information from it, but I don't know where / how in the WIF framework to gain access to such information.

A: WIF gives a bunch of events you can subscribe to. See these:
http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.web.wsfederationauthenticationmodule_members.aspx
http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.web.sessionauthenticationmodule_members.aspx

A: You can control some of the cookie characteristic via the config - A Hidden Gem: The WIF Config Schema. In particular, note the cookieHandler section and

hideFromScript - Boolean - default true Controls whether the
  "HttpOnly" flag is emitted for any cookies  written. Certain web
  browsers honor this flag by keeping client-side script from accessing
  the cookie value.

In terms of WIF, there is a Deserialize in Tokens.SessionSecurityTokenCookieSerializer and a CookieHandler (Delete / Read / Write) in IdentityModel.Web.


text:
Q: Unexpected Behavior of Date Parse on Azure In short, I'm parsing a passed in date to get a date to be used in an EF query.  It works as expected when testing locally, and reports it as the correct date minus one day when hosted in Azure.
The string form is 11/27/2013
To convert to dates I'm using:
var sDate = DateTime.Parse("11/27/2013").Date;
var eDate = sDate.AddDays(1);

Then in EF I'm using:
var res = from p in context.Table
          where p.PlaceholderDate >= sDate &&
          p.PlaceholderDate < eDate
          select p;

I end up with data for 11/26/2013 when hosted on Azure, and 11/27/2013 on my local machine.
If helpful, my timezone is EST.
Any help would be appreciated.

A: Could you give DateTimeOffset.Parse a try? And then pass in the expected offset (change the +1:00 to whatever offset you require) just to be safe?
Like so?
// String with date and offset
dateString = "05/01/2008 +1:00";
offsetDate = DateTimeOffset.Parse(dateString);
Console.WriteLine(offsetDate.ToString());


text:
Q: GCC capturing of `this` in lambda I have a code like:
#include <cstdio>
#include <functional>

class test {
public:
    void Do() {
        this->test_fun();
    }

    void Init() {
        this->number = 1008;
        this->test_fun = [this] {
            this->test_fun = nullptr;
            printf("number %d\n", this->number); //gcc crash here, this == nullptr
        };

    }

public:
    std::function<void()> test_fun;
    int number = 0;
};

int main() {
    test t;
    t.Init();
    t.Do();

    return 0;
}

It can run on MSVC2013, but crash on gcc on the line: printf("number %d\n", this->number);
What am I doing wrong?
GCC Version: gcc version 4.8.2 20140120 (Red Hat 4.8.2-15) (GCC)

A: Your code introduces undefined behavior, due to the the self destruction of the lambda with this->test_fun = nullptr;
This example should be equivalent:
#include <cstdio>
#include <cassert>
#include <memory>

class test {
public:
    struct Lambda {
        test* this_ptr;
        Lambda(test* this_ptr) : this_ptr(this_ptr) {}
        ~Lambda() {
            this_ptr = nullptr;
        }
        void operator () () {
            printf("this_ptr %p\n", (void*)this_ptr);
            // self destruction
            this_ptr->test_fun = nullptr;
            // undefined behavior starts here ...
            printf("this_ptr %p\n", (void*)this_ptr);
            printf("number %d\n", this_ptr->number);
        }
    };

    void Do() {
        assert(this->test_fun.get());
        (*this->test_fun)();
    }

    void Init() {
        this->number = 1008;
        this->test_fun = std::make_unique<Lambda>(this);
    }

public:
    std::unique_ptr<Lambda> test_fun;
    int number = 0;
};

int main() {
    test t;
    t.Init();
    t.Do();

    return 0;
}


text:
Q: c# DataContractJsonSerializer fails when run from windows service but succeeds when run from Visual Studio I'm trying to write a service as an exercise that will get weather data. I've got it working when run from the console, but when I start the service it fails with the following error
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Runtime.Serialization.SerializationException
Stack:
   at         System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(System.Runtime.Serialization.XmlReaderDelegator, Boolean,     System.Runtime.Serialization.DataContractResolver)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(System.Xml.XmlDictionaryReader)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(System.IO.Stream)
   at LyncWeather.WeatherGetter.ConvertStreamToWeatherData(System.IO.Stream)
   at LyncWeather.WeatherGetter.GetWeatherByCityId(Int32)
   at LyncWeather.Service1.UpdateLync(System.Object)
   at System.Threading.TimerQueueTimer.CallCallbackInContext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.TimerQueueTimer.CallCallback()
   at System.Threading.TimerQueueTimer.Fire()
   at System.Threading.TimerQueue.FireNextTimers()
   at System.Threading.TimerQueue.AppDomainTimerCallback()

Below are my data contract classes.
namespace LyncWeather
{
    [DataContract (Name = "coord")]
    public class Coord
    {
        [DataMember(Name = "lon")]
        public double Lon { get; set; }
        [DataMember(Name = "lat")]
        public double Lat { get; set; }
    }

    [DataContract(Name = "Weather")]
    public class Weather
    {
        [DataMember(Name = "id")]
        public int Id { get; set; }
        [DataMember(Name = "main")]
        public string Main { get; set; }
        [DataMember(Name = "description")]
        public string Description { get; set; }
        [DataMember(Name = "icon")]
        public string Icon { get; set; }
    }

    [DataContract (Name = "Main")]
    public class Main
    {
        [DataMember(Name = "temp")]
        public double Temp { get; set; }
        [DataMember(Name = "pressure")]
        public int Pressure { get; set; }
        [DataMember(Name = "humidity")]
        public int Humidity { get; set; }
        [DataMember(Name = "temp_min")]
        public double TempMin { get; set; }
        [DataMember(Name = "temp_max")]
        public double TempMax { get; set; }
    }

    [DataContract(Name = "Wind")]
    public class Wind
    {
        [DataMember(Name = "speed")]
        public double Speed { get; set; }
        [DataMember(Name = "deg")]
        public double Deg { get; set; }
    }

    [DataContract (Name = "Clouds")]
    public class Clouds
    {
        [DataMember(Name = "all")]
        public int All { get; set; }
    }

    [DataContract(Name = "Sys")]
    public class Sys
    {
        [DataMember(Name = "type")]
        public int Type { get; set; }
        [DataMember(Name = "id")]
        public int Id { get; set; }
        [DataMember(Name = "message")]
        public double Message { get; set; }
        [DataMember(Name = "country")]
        public string Country { get; set; }
        [DataMember(Name = "sunrise")]
        public int Sunrise { get; set; }
        [DataMember(Name = "sunset")]
        public int Sunset { get; set; }
    }

    [DataContract (Name = "WeatherData")]
    public class WeatherDataClass
    {
        [DataMember(Name = "coord")]
        public Coord CoordData { get; set; }
        [DataMember(Name = "weather")]
        public List<Weather> WeatherData { get; set; }
        [DataMember(Name = "main")]
        public Main MainData { get; set; }
        [DataMember(Name = "wind")]
        public Wind WindData { get; set; }
        [DataMember(Name = "clouds")]
        public Clouds CloudsData { get; set; }
        [DataMember(Name = "dt")]
        public int Dt { get; set; }
        [DataMember(Name = "sys")]
        public Sys SysData { get; set; }
        [DataMember(Name = "id")]
        public int Id { get; set; }
        [DataMember(Name = "name")]
        public string Name { get; set; }
    }
}

Here is where I call the DataContractSerializer
public WeatherDataClass ConvertStreamToWeatherData(Stream Json)
{
    DataContractJsonSerializer js = new     DataContractJsonSerializer(typeof(WeatherDataClass));
    return (WeatherDataClass)js.ReadObject(Json);
}

Does anyone know why this might be working in VS but not from a service? Barring that is there a way that I can get a more explicit error to find which datamember it's failing at?
Thanks for your help!


text:
Q: Importing a .csv containing list of complex numbers I exported a list (with two columns) to a .csv file with Mathematica, and the first few lines are,
-3.141592653589793,-942.4277659056601-7.514067804073956*^-12*I
-3.141592653589793,155.66354907107547-5.760593016133258*^-13*I
-3.141592653589793,-101.00525445626336-1.443383665316593*^-14*I

To export, I used the command
Export["table.csv", a]

When I import this table, Mathematica cannot interpret the complex numbers in the second column properly. How do I properly import this csv file into a table?
In[1]:= a = Import["table.csv"];

In[2]:= a[[1]]

Out[2]= {-3.14159, "-942.4277659056601-7.514067804073956*^-12*I"}

In[3]:= Re[a[[1]]]

Out[3]= {-3.14159, Re["-942.4277659056601-7.514067804073956*^-12*I"]}

A: This should interpret the complex number strings:
blist = ToExpression[#] & /@ a

{{-3.14159, -942.428 - 7.51407*10^-12 I}, {-3.14159,
  155.664 - 5.76059*10^-13 I}, {-3.14159, -101.005 -
   1.44338*10^-14 I}}


text:
Q: Match and extract href info using regex I am trying to make a regex that match and extract href link information in more than one case, for example both with double, single and no quotation mark in Swift.
A regex to match href and extract info Google.
Google
Google

I have found this regex, but it only works with double quotation:
([^<]+)<\/a>

Result:
Match 1: Google
Group 1: https://www.google.com
Group 2: Google

What I want is to detect all of the three ways that I provided with the sample text.
Note: I know that regex shouldn't be used for parsing HTML, but I am using it for a very small use case so it's fine.

A: Answer is already in comments but posting this since the approach is bit different.
In swift 5.7+ & iOS 16+  u can use regexBuilder for this.
import RegexBuilder

var link1 = "A regex to match href and extract info Google."
var link2 = "Google"
var link3 = "Google"

let regex = Regex {
    Capture {
        "https://www."
        ZeroOrMore(.word)
        "."
        ZeroOrMore(.word)
    }

}

if let result1 = try? regex.firstMatch(in: link1) {
    print("link: \(result1.output.1)")
}

if let result2 = try? regex.firstMatch(in: link2) {
    print("link: \(result2.output.1)")
}

if let result3 = try? regex.firstMatch(in: link3) {
    print("link: \(result3.output.1)")
}

This work well for the above 3 provided strings. But depend on the scenarios u might need to change the implementation.

A: assuming there is no other attribute in anchor tags in the file you wish to parse, you can use the following regex : /]+)\1>([^<]+)<\/a>/$2 $3/gm.
It first captures either single quote, double quote or nothing and then \1 recalls that capturing group, watch it live here on regex101.


text:
Q: Problemas con select option con alcargar datos con petición Ajax He realizado un servicio rest realizado con C# con petición ajax en un combo box, este objeto muestra los datos de mi servicio rest, este combo box debe llenar datos de muchas ciudad y este muestra las ciudades que realice en el servicio, pero el inconveniente esta en el objeto combo box o select option en html5, siempre que doy en el objeto, me carga los datos y no puedo seleccionar mi ciudad que quiero, volviéndolo a cargar,  como un bucle infinito cuando deseo seleccionar el dato Anexo código

                Ciudad
                <select class="form-control" data-rel="chosen"  id="Ciudad" name="Ciudad" onclick="ValidarExisteCiudad()">
                    <option></option>
                    <option></option>
                </select>

function ValidarExisteCiudad() {
    //$("[data-rel='chosen']").chosen();
    //var ddlCiudad = $("[data-rel='chosen']");
    var ddlCiudad = $("#Ciudad");
    ddlCiudad.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
        $.ajax({
            type: 'GET',
            url: "CargaCiudad",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                ddlCiudad.empty().append('<option selected="selected" value="0">Seleccione ...</option>');
                $.each(data, function () {
                   ddlCiudad.append($("<option></option>").val(this['Value']).html(this['Text']));

                });
                // After updated data from database you need to trigger chosen:updated.
                //$("[data-rel='chosen']").trigger("chosen:updated");
            },
            failure: function (data) {
                alert(data.responseText);
            },
            error: function (data) {
                alert(data.responseText);
                existeUsuario = false;
            }
        });

}

[HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> CargaCiudad()
        {
            List<Cuidad> Items = await drHelpPrueba.Cuidad.ToListAsync();
            List<SelectListItem> ciudad = new List<SelectListItem>();

            for (int i = 0; i < Items.Count; i++)
            {
                ciudad.Add(new SelectListItem
                {
                    Value = Convert.ToString(Items.ToList()[i].IdCiudad),
                    Text = Items.ToList()[i].Nombre
                });
            }

            return Json(ciudad);

        }

Imagen del Combo box

Cuando deseo seleccionar una ciudad, este vuelve a cargar

A: No veo porque esperas un resultado diferente al que mencionas si usas el evento click del mismo control que estas cargando, al desplegar se ejecuta el evento volviendose a recargar cada vez.
Sino quiere que suceda esto no usas el evento click, podria ser
<select class="form-control" data-rel="chosen"  id="Ciudad" name="Ciudad">
</select>

y defines la carga al inicio del form

al usar el $(function(){ es el equivalente a $.ready() de jquery con lo cual se ejecua cuando el DOM del Html este cargado en la pagina o sea seria el load
Es en ese momento donde debes cargar el combo, asi al seleccionar un item no se recarga en el click


text:
Q: DNS resolution failing over to secondary DNS - why? We have large number of branch offices connected via VPN, but without any kind of server infrastructure.  The client machines in each office get their network configuration from an ASA 5505, which is also used for the VPN connection.
The Windows XP client machines are configured to use one of our corporate DNS servers as the primary, with the DNS server of the ISP as the secondary.  The idea is that if the VPN connection fails for any reason, staff in the office will still be able to access the internet, and access our webmail and home access portal.   In the majority of cases this works fine.
However, for offices based in South America we are seeing DNS resolution on the client machines regularly being done against the ISP DNS server - this results in our corporate resources being effectively unavailable to staff in the offices.
The client machines are able to ping the corporate DNS server ok.  When doing an nslookup of a corporate hostname, I get a reply.
I'm thinking one of the following (or a combination) is happening:

*

*our corporate DNS server is not always replying to requests in a timely fashion (although why this would only affect clients in one geographic region I don't know)

*DNS queries from Latin America are somehow delayed, causing the client to treat it as failed (although we have offices at the end of much slower VSAT connections which do not have this issue)

*a single failure is resulting in a DNS cache entry in Windows that somehow results in the lookups not happening on subsequent tries

Has anyone else come across this issue?  Any ideas for resolutions?

A: Windows queries DNS in this order:

*

*hosts file

*local DNS cache

*Preferred DNS servers

*Other DNS servers

MS also has an article describing how the DNS server list is obtained:

The DNS Client service uses a server search list, ordered by preference. This list includes all preferred and alternate DNS servers configured for each of the active network connections on the system.
The list is arranged based on the following criteria:

*

*Preferred DNS servers are given first priority.

*If no preferred DNS servers are available, then alternate DNS servers are used.

*Unresponsive servers are removed temporarily from these lists.

Windows has an escalating timeout for DNS requests:
Value      Default value  Attempt
1st limit       1 second  Query the preferred DNS server on a preferred connection.
2nd limit      2 seconds  Query the preferred DNS server on all connections.
3rd limit      2 seconds  Query all DNS servers on all connections (1st attempt).
4th limit      4 seconds  Query all DNS servers on all connections (2nd attempt).
5th limit      8 seconds  Query all DNS servers on all connections (3rd attempt).
6th value                 (Must be 0.)

I could not find a clear answer on this exact point, but it sounds like if it doesn't get a response from your primary DNS in 1 or 2 seconds (1st or 2nd attempt, respectively), then that server will be removed from the DNS server lookup list for 15 minutes, and so it will use the secondary DNS servers. Since those servers have up to an 8 second timeout, they are much more likely to respond. (It's unclear to me if it continues to query the preferred DNS server during the 3rd+ attempt if it's already failed).
I also suspect that you do indeed have a WAN latency issue for this geographical area, as it would explain why the timeouts are working.

One solution is to change the DNS query timeouts, using the DNSQueryTimeouts registry parameter. See also http://drewthaler.blogspot.com/2005/09/changing-dns-query-timeout-in-windows.html

Another solution is to put a local caching DNS server on the network, and have the clients use that. You can use a DNS server that may be built in to a router, or install something like dnsmasq.

A: According to Technet http://blogs.technet.com/b/stdqry/archive/2011/12/15/dns-clients-and-timeouts-part-2.aspx later queries are done to multiple DNS servers in parallel.
And most people have only one network connection and a fast broadband connection and should normally expect a DNS response within 1s.
So I have set my DNSQueryTimeouts to 1 1 1 10 10 0 so that it gets to issuing parallel queries to all DNS servers as quickly as possible. Then I put my ISP's DNS servers in the list first (since they are physically closest and least likely to be subject to network packet drops, with several public DNS servers behind, and let Windows do its stuff.
And my web browsing has speeded up immensely!!!
Obviously don't give the ISP DNS servers priority in a corporate environment when you want to internally resolve internal hostnames!


text:
Q: navigator.mozGetUserMedia does not call onvideosuccess method I am trying to get an web application running with the webcam video feed and I am not having any luck getting the video feed to the firefox browser. Following is my code.
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
if(this.videoelement){
if(this.browser.hasVideoCameraSupport())
    navigator.getUserMedia({video: true, audio: true},
                      function(stream) {
               this.videoelement.src = window.URL.createObjectURL(stream);
               this.videoStream = stream;
               this.videoRunning = true;
               if (typeof callback === "function")
                                callback(this.videoStream);
            }.bind(this) ,
                      function (err) {
            alert("Unknown Error "+err.message);
           }
             );
} else{
    alert("You HTML dom Does have a video element!");
}
}

A: After all  figured that firefox has decided to change the API and do things a bit differently. I manage to sort out the issue and my code is as follows.
var videoelement = document.querySelector('video');
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
        window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
        if(videoelement){
            navigator.getUserMedia({video: true, audio: false},
                        function(stream) {
                            if (navigator.mozGetUserMedia) {
                                videoelement.mozSrcObject = stream;
                              } else {
                                var vendorURL = window.URL || window.webkitURL;
                                videoelement.src = vendorURL.createObjectURL(stream);
                              }
                            videoelement.play();
                }.bind(this) , function (err) {
                    alert("Unknown Error "+err.message);
                });
        } else{
            alert("You HTML dom Does have a video element!");
        }


text:
Q: How To Setup a SQLAlchemy Asynchronous Scoped Session In Python Behave Synchronous Hooks? I have also asked this question on behave GitHub discussions and SQLAlchemy GitHub discussions.
I am trying to hookup a SQLAlchemy 1.4 engine and global scoped asynchronous session in behave before_all and before_scenario hooks to model testing similar to that outlined in the following blog article
The approach is to have a parent transaction and each test running in a nested transaction that gets rolled back when the test completes.
Unfortunately the before_all, before_scenario hooks are synchronous.
The application under test uses an asynchronous engine and asynchronous session created using sessionmaker:
def _create_session_factory(engine) -> sessionmaker[AsyncSession]:
    factory = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    factory.configure(bind=engine)

    return factory

In the before_scenario test hook the following line raises an error when I try to create a scoped session.
"""THIS RAISES AN ERROR  RuntimeError: no running event loop"""
context.session = context.Session(bind=context.connection, loop=loop)
The full code listing for setting up the test environment is listed below.
How do I get an asynchronous scoped session created in the synchronous before_all, before_scenario test hooks of behave?
import asyncio
import logging

from behave.api.async_step import use_or_create_async_context
from behave.log_capture import capture
from behave.runner import Context
from behave.model import Scenario
from sqlalchemy import event
from sqlalchemy.ext.asyncio import AsyncSession, async_scoped_session
from sqlalchemy.ext.asyncio.engine import async_engine_from_config
from sqlalchemy.orm.session import sessionmaker

from fastapi_graphql.server.config import Settings

logger = logging.getLogger()

@capture(level=logging.INFO)
def before_all(context: Context) -> None:
    """Setup database engine and session factory."""

    logging.info("Setting up logging for behave tests...")
    context.config.setup_logging()

    logging.info("Setting up async context...")
    use_or_create_async_context(context)
    loop = context.async_context.loop
    asyncio.set_event_loop(loop)

    logging.info("Configuring db engine...")
    settings = Settings()
    config = settings.dict()
    config["sqlalchemy_url"] = settings.db_url

    engine = async_engine_from_config(config, prefix="sqlalchemy_")
    logging.info(f"Db engine configured for connecting to: {settings.db_url}")

    logging.info("Creating a global session instance")
    factory = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
    # factory.configure(bind=engine)

    Session = async_scoped_session(factory(), scopefunc=asyncio.current_task)

    context.engine = engine
    context.connection = loop.run_until_complete(engine.connect())
    context.factory = factory
    context.Session = Session

@capture(level=logging.INFO)
def after_all(context: Context) -> None:
    """Teardown database engine gracefully."""

    loop = context.async_context.loop

    logging.info("Closing connection")
    loop.run_until_complete(context.connection.close())

    logging.info("Closing database engine...")
    loop.run_until_complete(context.engine.dispose())
    logging.info("Database engine closed")

@capture(level=logging.INFO)
def before_scenario(context: Context, scenario: Scenario) -> None:
    """Create a database session."""

    loop = context.async_context.loop

    logging.info("Starting a transaction...")
    context.transaction = loop.run_until_complete(context.connection.begin())

    logging.info("Transaction started...")

    logging.info("Creating a db session...")
    breakpoint()
    # THIS RAISES AN ERROR  RuntimeError: no running event loop
    context.session = context.Session(bind=context.connection, loop=loop)
    logging.info("Db session created")

    breakpoint()
    logging.info("Starting a nested transaction...")
    context.session.begin_nested()
    logging.info("Nested transaction started...")

    @event.listens_for(context.session, "after_transaction_end")
    def restart_savepoint(db_session, transaction):
        """Support tests with rollbacks.

        This is required for tests that call some services that issue
        rollbacks in try-except blocks.

        With this event the Session always runs all operations within
        the scope of a SAVEPOINT, which is established at the start of
        each transaction, so that tests can also rollback the
        "transaction" as well while still remaining in the scope of a
        larger "transaction" that's never committed.
        """
        if context.transaction.nested and not context.transaction._parent.nested:
            # ensure that state is expired the way session.commit() at
            # the top level normally does
            context.session.expire_all()
            context.session.begin_nested()

@capture(level=logging.INFO)
def after_scenario(context: Context, scenario: Scenario) -> None:
    """Close the database session."""

    logging.info("Closing db session...")
    loop = asyncio.get_event_loop()
    loop.run_until_complete(context.Session.remove())
    logging.info("Db session closed")
    logging.info("Rolling back transaction...")
    loop.run_until_complete(context.transaction.rollback())
    logging.info("Rolled back transaction")


text:
Q: type java.lang.string cannot be converted to jsonarray I am using volley to connect the php from android, but it's show me error please some help me  here a my java & php code .php is connect to database php show -1 'success'=>false result.
public class main extends Activity{

   String i = "";
   String d = "";
   String ya = "";
   String is = "";
   String to="";

   final Response.Listener<String> responseListener = new Response.Listener<String>() {

    @Override
    public void onResponse(String response)
    {
        JSONObject jsonResponse = null;

        try {
            JSONArray array = new JSONArray(response);
            jsonResponse = array.getJSONObject(0);
            Log.w(TAG, "onResponse: jsonresponse" + response.toString());
            boolean success = jsonResponse.getBoolean("success");
            if (success) {
                i = jsonResponse.getString("i");
                d = jsonResponse.getString("d");
            } else {
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    Inp insQ = new Inp(ya,is ,to ,responseListener);
    RequestQueue queue = Volley.newRequestQueue(main.this);
    queue.add(insQ);}

// next ins class  - commented at edit by Jeff
public class Ins extends StringRequest
{
    public static final String REGISTER_REQUEST_URL = "edu.php";

    private static final String TAG = "Ins";
    private Map<String,String> params;
    public Ins(String ya, String is, String to, Response.Listener listener)
    {
        super(Request.Method.POST, REGISTER_REQUEST_URL, listener, null);
        Log.w(TAG, "Ins: " + ya + is + to );
        params = new HashMap<>();
        params.put("ya", ya);
        params.put("is",is);
        params.put("to", to + "");
        Log.w(TAG, "Ins working well  " + ya + is +to );
    }

    @Override
    public Map<String,String> getParams() {
        return params;
    }
}

php code start
<?php

$servername = "localhost";
$username = "****";
$password = "*****";
$dbname = "*****";

$em = $_POST['ya'];
$one = $_POST['is'];
$to = $_POST['to'];

$d = date('Y-m-d');
$y = date('y');
$m = date('m');
$d = date('d');
$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sqll = "SELECT * FROM jio";
$res = mysqli_query($conn,$sqll);
$rowC = mysqli_num_rows($res);

$rowC = $rowC%999 + 1;
if($rowC < 10){
    $i = $year.$mon.$day.'00'.$rowC;
}elseif (rowC < 100) {
    $i = $year.$mon.$day.'0'.$rowC;
}else {
    $i = $year.$mon.$day.$rowC;
}
$sql = "INSERT INTO jio(iu,i, d, ya, is, qs,to,ra,wto,wi,wk,)VALUES('0',".$i."','".$d."','".$em."','".$one."', '-1','".$to."','0','0','0','0')";

$r = mysqli_query($conn, $sql);
$rows=mysqli_affected_rows($conn);
$result = array();

if($rows>0) {
    array_push($result,array(
            'success'=>true,
            'i' => $i,
            'd' =>$d
    ));
}
else
array_push($result,array(
        'success'=>false
));

echo json_encode($result);

mysqli_close($conn);
?>

A: According to the "problem" you've described I guess all the syntax errors in your code came from porting the code to here.
It seems that - if I understood you correctly - your only problem is a simple missing ' in your sql:
                                                                    //  here
$sql = "INSERT INTO jio(iu,i, d, ya, is, qs,to,ra,wto,wi,wk,)VALUES('0',".$i."','".$d."','".$em."','".$one."', '-1','".$to."','0','0','0','0')";

This will cause $rows to be false (because of a mysqli error), so your if sets 'success' to false.
The corrected sql would be
$sql = "INSERT INTO jio(iu,i, d, ya, is, qs,to,ra,wto,wi,wk,)VALUES('0','".$i."','".$d."','".$em."','".$one."', '-1','".$to."','0','0','0','0')";
// this is the critical part:
// ...,'".$i."',...

NOTES
You should better switch to prepared statements, because you're open to sql-injection.
Also, better check first if your query was successful or if there were any errors.
$r = mysqli_query($conn, $sql);
if($r) {
   // work with the result
} else {
   // an error occurred. Show it, handle it, whatever.
   echo mysqli_error($conn);
}

Also, you don't need to array_push in php. It's much easier to use that syntax:
$result = array();
if($rows>0) {
    $result[] = array(
        'success'=>true,
        'i' => $i,
        'd' =>$d
        );
}
else { // don't forget these brackets here!
   $result[] = array(
        'success'=>false
        );
} // and here

And finally: You don't need to close a mysqli-connection at the end of a script, as it will be terminated at the end anyway.


text:
Q: In a Promise, what's the difference between using catch and the 2nd argument of then? What exactly is the difference between these two statements?
funcThatReturnsAPromise()
  .then(() => { /* success */ })
  .catch(() => { /* fail */ });

funcThatReturnsAPromise()
  .then(() => { /* success */ }, () => { /* fail */ });

A:
then(..) takes one or two parameters, the first for the fulfillment
  callback, and the second for the rejection callback. If either is
  omitted or is otherwise passed as a non-function value, a default
  callback is substituted respectively. The default fulfillment callback
  simply passes the message along, while the default rejection callback
  simply rethrows (propagates) the error reason it receives. catch(..)
  takes only the rejection callback as a parameter, and automatically
  substitutes the default fulfillment callback, as just discussed. In other words, it's equivalent to then(null,..) :

p . then ( fulfilled );
p . then ( fulfilled , rejected );
p . catch ( rejected ); // or `p.then( null, rejected )`

then(..) and catch(..) also create and return a new promise, which can
  be used to express Promise chain flow control. If the fulfillment or
  rejection callbacks have an exception thrown, the returned promise is
  rejected. If either callback returns an immediate, non-Promise,
  non-thenable value, that value is set as the fulfillment for the
  returned promise. If the fulfillment handler specifically returns a
  promise or thenable value, that value is unwrapped and becomes the
  resolution of the returned promise.

—from "You Don't Know JS, Kyle Simpson

A: Besides .catch(fn) being a shortcut for .then(null, fn), the difference in your examples is that
funcThatReturnsAPromise()
  .then(() => { /* success */ })
  .catch(() => { /* fail */ });

// is equivalent to

const p1 = funcThatReturnsAPromise()
const p2 = p1.then(() => { /* success */ })
const p3 = p2.catch(() => { /*
   executed if p1 is rejected
   executed if p2 is rejected
*/ })

While the second one is
funcThatReturnsAPromise()
  .then(() => { /* success */ }, () => { /* fail */ });

// equivalent to

const p1 = funcThatReturnsAPromise()
const p2 = p1.then(
  () => { /* success */ },
  () => { /*
     executed if p1 is rejected
     (p2 will be actually resolved by the result of this function only when p1 is rejected)
  */ }
);

A: .catch(foo) is equal to .then(undefined, foo)
But there is a difference between your code samples:
funcThatReturnsAPromise()
  .then(() => { /* success case of funcThatReturnsAPromise */ })
  .catch(() => { /* both fail case of funcThatReturnsAPromise
                     and fail case of "then" function */ });

funcThatReturnsAPromise()
  .then(() => { /* success case of funcThatReturnsAPromise */ },
        () => { /* fail case of funcThatReturnsAPromise */ });


text:
Q: Songs in playlist - Apple Music I have an apple music subscription and then decided to make some cool playlists.
But now, my library is FULL of albums that I never play outside of my playlists, an ugly ugly nightmare. I guess my question is:
How can I have songs in playlist but not in the library?
I don't want to see them outside of the playlist!

A: Short answer is - you can't.
The Library is your total structure, containing everything.
Playlists are made from the overall structure.
You can delete a song from a Playlist without removing it from the Library - but if you delete a song from the Library, it will also delete it from all Playlists.

A: In the newest versions of the iTunes (tested on the 12.6.2.20), you can uncheck the box in the Settings, to not add songs to your library when adding them to your playlists (see screenshot with the red arrow pointing to the checkbox).


text:
Q: Detect trends in time series I have a psql database with time series values for various stocks. I want to find, if the stock value increased by lets say 50% in last 45 days. I want to detect such sudden changes in the curve. Right now, my focus is on increasing values. Mostly quadratic curves, although it would be nice to find linear/logarithmic increases too.
I will get to sudden drops later. Any pointers into how I detect such patterns in the curve? Is it possible to do it in sql? I am also open to learning any mathematical analysis tools or languages.

A: To get that kind of information, there are many approaches that can be taken. If this report is going to be run every once in a while, then you could have a SQL query that will join the table to itself, on an older date. Assuming you have a date, stock_ticker, and price as the fields, a query could look something like this:
         SELECT base.date,
                base.stock_ticker,
                ((base.price - old.price) / old.price) as gain
           FROM stocks as base
LEFT OUTER JOIN stocks as old
             ON base.stock_ticker = old.stock_ticker
            AND base.date = old.date + cast('45 days' as interval)

This will give you a table with the date, the stock ticker, and how much the price has gone up since the price 45 days ago. With this, you can use it as a sub-query, alias it with a WITH clause, or do other work on it.
If you weren't looking for just a ratio over a time period, you can use the same technique to get daily averages, and with that data find a moving average.