text:
Q: how to set max size of a counter? I have the following code, that is a counter:

");
</script>

noscript:

I have configurated the page with width:100% to adjunt the page to the width of the browser, however, the counter is adjust too. I would like to set a max size for the counter.
How can I set that the counter does not adjust to the width of the browser?
Thanks.
I Add my css code:
/* Resets
--------------------------------------------------------------------------------*/

ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, body, html, p, blockquote, fieldset, input {
    margin: 0;
    padding: 0;
}

a img {
    border: 0;
    /*NOTA: si se utiliza el width en la imagen se modifica el tamaño de la imagen del logo.
    Se puede utilizar tanto en porcentaje como en pxels, pero en porcentaje no parece que se modifique,
    solo si se indica en pixels.
    Si se indica en % se ajusta al tamaño siempre que sea para hacerlo más pequeño pero no para hacerlo más grande.
    ESTO ES UN AÑADIDO propio, no es original de la web.
    Es necesario para que el logo del encabezado se ajuste al tamaño del browser, lo malo es que el contador del pie
    de página también se ajusta al tamaño del browser.*/
    width: 100%;
    /*@NOTA: eh height modica todas las imágenes del la página.*/
    //height: auto;
}

a {
    color: #6ca9d5;
    text-decoration: none;
}

a:hover {
    color: #90cbf5;
}

/* General Styling and Structure
--------------------------------------------------------------------------------*/

body {
    font-family: Tahoma, Geneva, sans-serif;
    font-size: 14px;
    color: #868686;
    /*NOTA: el margen es el que se deja entre el borde del navegador y el contenido. Por defecto es 0.
    El padding es parecido y por defecto también es 0. Aunque se cambia y no hace nada.
    Se tiene que poner 10px por ejemplo, px para indicar pixels. Si se pone 10% entonces es en porcentaje.
    Afecta tanto al encabezado como al body.*/
    margin: 1%;
    padding: 0;
    background: #fafafa;
}

h2 {
    font-size: 1.7em;
    margin: 0;
    padding: .3em 0;
    line-height: 1.2;
    font-family: "Actor", "Myriad Pro", Arial, Helvetica, sans-serif;
}

#content h2 {
    color: #90cbf5;
}

p {
    font-size: 1em;
    line-height: 1.5;
    margin: 0;
    padding: .5em 0;
}

#content p {
    color: #868686;
}

#content abbr {
    border-bottom: 1px dotted #8f8f8f;
}

#header-wrap,
#main-wrap {
    background: #fff;
    /*@NOTA: especifica el ancho de toda la página menos del encabezado. Por defecto width es auto
    lo que quiere decir que el navegador determinará el ancho, es lo que se quiere. Como es por defecto si se quita la
    propiedad funicona igual.*/
    //width: auto;
    /*@NOTA: si no se indica un tamaño mínimo, el contenido de toda la página se ajustan al tamaño del browser,
    tanto en agrandar como en disminuir. Lo malo es que no afecta al encabezado.*/
    //min-width: 1200px;

    vertical-align: baseline;
}

#page {
    /*@NOTA: esto no deja margen a los lados, si no se indica width, pega todo al máximo de la resolución de pantalla.
    Por defecto es 0 auto*/
    margin: 0 auto;
    /*@MODIFICACION: este es el valor original. Si se amplia a 1300px por ejemplo ocupa todo el ancho
    //de pantalla. Si no se pone nada, se pega todo a la pantalla sin márgenes.
    Se ajusta al tamaño de pantalla, no al tamaño de la ventana del navegador.*/
    /*width: 900px*/
    /*@NOTA: si se indica un ancho automático se ajusta también al tamaño de pantalla.
    Se ajusta al tamaño de pantalla, no al tamaño de la ventana del navegador.*/
    width: 100%;
}

#header {
    padding: 0;
    margin: 0;
}

.wsite-logo,
.wsite-logo a {
    color: #90cbf5;
    margin: 0;
    padding: 0;
    text-decoration: none;
}

.wsite-logo,
.wsite-logo a:hover {
    color: #90cbf5;
}

#logo,
#logo a {
    font-size: 36px;
    color: #90cbf5;
    font-weight: normal;
    padding: 0;
    font-family: "Actor", Arial, Helvetica, sans-serif;
}

#header-right a {
    color: #6ca9d5;
}

#header-right a:hover {
    color: #90cbf5;
}

/* Header Area
-------------------------------------------------------------*/

#header {
    /*El ancho parece que no se ajusta a nada, si se pone muy pequeño el logo se sigue viendo
    completo*/
    width: 100%;
    /*@NOTA: esto modifica el alto del encabezado, que es donde está el logo.*/
    height: 100px;
}

#header,
#header table {
    border-collapse: collapse;
    border-spacing: 0;
}

#header td {
    vertical-align: middle;
    /*@NOTA: la alineación modifica la posición de la imagen de la cabecera de GTS.
    Para que la imagen se reescale al tamaño del navegador se debe poner como left y en el editor
    del ecabezado hacer la imagen tan grande para que llegue hasta la derecha.*/
    text-align: left;
}

#logo {
    /*@NOTA: el padding controla la separación desde la parte superior hasta la imagen del lgo de GTS.
    El primer número indica el padding desde la parte superior y el segundo desde la izquierda.
    El padding empieza a contar desde el margen de la página, es por tanto una adición al margen.
    Se pueden indicar también porcentajes.*/
    padding: 0 0;
    /*@NOTA: la opaciodad se indica con porcetanje. 1 es 100 de opacidad. Se Cambia la opacidad de la imagen
    del logo de GTS de la cabecera.
    ESTO ES AÑADIDO, no es original de la web.*/
    //Opacity: 0.2;
}

#statcounter div.statcounter{
    max-width: 100px;
    max-height: 100px;

}

#header-right {
    padding: 0 0 0 10px;
}

#header-right table {
    width: 1px;
}

#header-right table,
#header-right .search,
#header-right .wsite-search {
    clear: right;
    float: right;
}

#header-right td {
    padding: 0;
}

/* TOP RIGHT: Phone Number
--------------------------------------------------------------------------------*/
#header-right .phone-number .wsite-text {
    color: #868686;
    font-size: 12px;
    font-weight: normal;
    font-family: Tahoma, Geneva, sans-serif;
    text-decoration: none;
    display: block;
    white-space: nowrap;
    margin: 5px 0 5px 15px;
}

/* TOP RIGHT: Social Links
--------------------------------------------------------------------------------*/
#header-right .wsite-social {
    vertical-align: middle;
    margin: 5px 0 0 10px;
}

#header-right .wsite-social-item {
    width: 12px;
    height: 12px;
    margin: 0 0 0 12px;
}

#header-right .wsite-social-rss {
    background: url(rss-h.png) no-repeat;
}

#header-right .wsite-social-linkedin {
    background: url(linkedin-h.png) no-repeat;
}

#header-right .wsite-social-facebook {
    background: url(facebook-h.png) no-repeat;
}

#header-right .wsite-social-twitter {
    background: url(twitter-h.png) no-repeat;
}

#header-right .wsite-social-mail {
    background: url(mail-h.png) no-repeat;
}

/* TOP RIGHT: Search Box
--------------------------------------------------------------------------------*/

#header-right .search {
}

#header-right .wsite-search {
    margin: 5px 0 5px 15px;
    vertical-align: middle;
}

#header-right .wsite-search-input {
    width: 137px;
    height: 13px;
    border: none;
    padding: 8px 8px 6px 8px !important;
    font-family: Arial, Helvetica, sans-serif;
    color: #848484;
    font-size: 12px;
    background: url(input-bg.png) no-repeat;
    vertical-align: middle;
    display: inline-block;
}

#header-right .wsite-search-button {
    position: relative;
    width: 30px;
    height: 27px;
    color: #010101;
    font-size: 12px;
    border: none;
    margin: 0;
    padding: 0;
    background: url(submit-bg-blue.png) no-repeat;
    vertical-align: middle;
    display: inline-block;
}

/* Navigation
--------------------------------------------------------------------------------*/

#topnav {
    clear: both;
    margin: 0;
    overflow: hidden;
}

#topnav ul {
    list-style: none;
    float: left;
}

#topnav ul li {
    list-style: none;
    float: left;
    padding: 0 2px 0 0;
}

#topnav a {
    float: left;
    display: block;
    color: #545454;
    text-decoration: none;
    font-family: "Actor", "Myriad Pro", Arial, Helvetica, sans-serif;
    padding: 10px 15px 11px;
    font-size: 13px;
    border: 0;
    outline: 0;
    margin: 0;
    list-style-type: none;
    text-transform: uppercase;
    line-height: 1;
}

#topnav li#active a,
#topnav a:hover {
    color: #545454;
    background: #e3f3ff;
    border: 0;
}

/****************************** flyout menus ******************************/

#wsite-menus .wsite-menu li a {
    font-family: Tahoma, Geneva, sans-serif;
    padding: 9px;
    color: #545454;
    background: #e3f3ff;
    border: 0;
    border-bottom: 1px solid #b6d2e6;
}

#wsite-menus .wsite-menu li a:hover {
    color: #545454;
    background: #fdfeff;
}

/* main  */

#main {
}

#content {
    min-height: 400px;
    /*@NOTA: el padding modifica la separación entre las banderas con los idiomas el menú.*/
    padding: 30px 0;
}

#container {
    /*width: 920px;*/
    width: 1200px;
    margin: 0 auto;
}

/*
#banner-wrap {
    border-bottom: 1px solid #d4d4d4;
    border-top: 1px solid #d4d4d4;
    background: #f6f6f6;
    min-width: 920px;
}
*/

/*
#banner-bot {
    background: url(banner-bot.png) left bottom no-repeat;
    padding-bottom: 14px;
}

#banner-top {
    background: url(banner-top.png) no-repeat;
    padding-top: 14px;
}

#banner-mid {
    background: url(banner-mid.png) repeat-y;
    padding: 0 10px;
    overflow: hidden;
}
*/

/*
#banner-outer {
    border: 6px solid #fff;
}
*/

/*
#banner {
    background: url(banner-top.png) no-repeat;
    padding-top: 14px;
    position: relative;
}
*/

/* PAGE TYPE: banner-tall
--------------------------------------------------------------------------------*/
/*
.tall-header-page .wsite-header {
    width: 888px;
    height: 258px;
    background: url(banner-tall.jpg) no-repeat;
}
*/

/* PAGE TYPE: banner-short
--------------------------------------------------------------------------------*/
/*
.short-header-page .wsite-header {
    width: 888px;
    height: 168px;
    background: url(banner-short.jpg) no-repeat;
}
*/

.no-header-page #banner-wrap {
    padding: 8px 0;
    border-bottom: 1px solid #d4d4d4;
    border-top: 1px solid #d4d4d4;
}

/*
.no-header-page #banner-bot {
    display: none;
}
*/

/* PAGE TYPE: banner-landing
--------------------------------------------------------------------------------*/

.landing-page #banner {
    border: none;
    background: none;
    padding: 0;
}

.landing-page #banner-detail {
    background: #66c9c1;
}

#bannerleft {
    float: left;
    width: 504px;
    padding: 0;
    position: relative;
}

/*
#banner-b {
    background: url(landing-bnr-mid-03.png) left bottom no-repeat;
    padding-bottom: 14px;
}
*/

/*
#banner-t {
    background: url(landing-bnr-top.png) no-repeat;
    padding-top: 14px;
}
*/

/*
#banner-m {
    background: url(landing-bnr-mid.png) repeat-y;
    padding: 0 10px;
    overflow: hidden;
}
*/

#banner-inner {
    border: 6px solid #fff;
}

.landing-page .wsite-header {
    /*width: 472px;*/
    width: 1200px;
    height: 318px;
    background: url(banner-landing.jpg) no-repeat;
}

#bannerright {
    float: right;
    width: 366px;
    padding: 65px 25px 0 25px;
}

#bannerright h2 {
    color: #90cbf5;
    font-size: 32px;
    padding: 0 0 12px 0;
}

#bannerright p {
    color: #868686;
    font-size: 1.1em;
    padding-bottom: 25px;
    margin: 0;
}

#bannerright .wsite-button {
    margin: 0;
}

/* PAGE TYPE: splash
--------------------------------------------------------------------------------*/

.splash-page #header {
    width: 532px;
}

.splash-page #banner {
    width: 527px;
    height: 161px;
    padding: 6px 4px 4px 6px;
    background: url(banner-splash-bg.png) no-repeat;
}

.splash-page .wsite-header {
    width: 515px;
    height: 149px;
    background: url(banner-splash.jpg) no-repeat;
}

.splash-page #content-container {
    width: 528px;
}

.splash-page #content {
    width: 528px;
}

.splash-page #footer {
    width: 524px;
}

/* Footer
--------------------------------------------------------------------------------*/

#footer-wrap {
    border-top: 1px solid #dedede;
    background: #fafafa;
    //min-width: 920px;
    /*El foot afecta a donde está el crear web con weebly.*/
    width: 100%;
}

#footer {
    padding: 40px 0 45px;
    font-size: 12px;
    color: #666;
    font-family: Arial, sans-serif;
    text-align: right;
}

#footer p {
    color: #666;
}

#footer a {
    color: #919191;
}

#footer a:hover {
    color: #6ca9d5;
}

#footer h2 {
    font-size: 16px;
    margin: 0 0 2px;
    padding: .3em 0;
    line-height: 1.5;
    color: #414141;
    font-family: "Actor", "Myriad Pro", Arial, Helvetica, sans-serif;
    border-bottom:1px solid #ddd;
}

#footer span {
    vertical-align: middle;
}

#footer .wsite-social {
    vertical-align: middle;
}

#footer .wsite-social-item {
    width: 12px;
    height: 12px;
    margin-right:6px;
}

#footer .wsite-social-rss {
    background: url(rss.png) no-repeat;
}

#footer .wsite-social-linkedin {
    background: url(linkedin.png) no-repeat;
}

#footer .wsite-social-facebook {
    background: url(facebook.png) no-repeat;
}

#footer .wsite-social-twitter {
    background: url(twitter.png) no-repeat;
}

#footer .wsite-social-mail {
    background: url(mail-h.png) no-repeat;
}

.wsite-footer {  /* make sure enough space between element footer and attribution */
    margin-bottom: 15px;
}

/* Form Customization
--------------------------------------------------------------------------------*/

.wsite-form-label {
    display: inline-block;
    color: #868686;
    font-family: Tahoma, Geneva, sans-serif;
    font-size: 1em;
    padding: 12px 0 5px 0;
}

.form-radio-container {
    color: #868686;
    font-size: 14px;
    font-family: Tahoma, Geneva, sans-serif;
}

.wsite-form-input {
    font-family: Tahoma, Geneva, sans-serif;
    font-size: 13px;
    color: #868686;
    background: #fff;
    border: 1px solid #dcdcdc;
    padding: 8px 4px 5px !important;
    width: 300px;
    line-height: 1;  /* background:#fff url(field.png) repeat-x;
            -webkit-border-radius: 3px;
            -moz-border-radius: 3px;
            border-radius: 3px;
        */
}

.form-select {
    color: #868686;
    border: 1px solid #dcdcdc;
    font-size: 13px;
    background: #fff;
    font-family: Tahoma, Geneva, sans-serif;
    padding: 3px 4px;
    width: 320px;
    height: 27px;
    line-height: 27px;  /*
            background:url#fff (field.png);
            -webkit-border-radius: 3px;
            -moz-border-radius: 3px;
            border-radius: 3px;
        */
}

/* Footer Form Customization
--------------------------------------------------------------------------------*/

.wsite-form-container {
    margin-top:0px !important;
    text-align:left;
}

.wsite-footer .wsite-form-label {
    font-size: 1em;
    padding: 5px 0 2px 0;
}

.wsite-footer .wsite-form-field {
    width:300px !important;
}

.wsite-footer .form-radio-container {
    font-size:1em;
}

.wsite-footer .wsite-form-input {
    font-size: 1em;
    width: 100% !important;
}

.wsite-footer .form-select {
    width: 100%;
}

/* Buttons
--------------------------------------------------------------------------------*/

/*
  Buttons are styled with background image sprites. There are 4 unique image files:
   - small & normal-colored  (button_small_grey.png)
   - large & normal-colored  (button_large_grey.png)
   - small & highlight-colored  (button_small_orange.png)
   - large & highlight-colored  (button_large_orange.png)

  Each of these 4 types of buttons must define a :hover state (when user's mouse is over)
  as well as an :active state (when the user presses down).

  Look at the CSS (especially the inner .wsite-button-inner wrapper), as well as the
  image files to understand how the liquid-width nature of these buttons work.
 */

/* small */

.wsite-button {
    color: #333 !important;
    font-family: Arial, Helvetica, sans-serif;
    height: 34px;
    display: inline-block;
    font-size: 12px;
    border: none;
    font-weight: normal;
    font-size: 13px;
    text-decoration: none;
    padding: 0 15px 0 0;
    background: url(button.png) no-repeat 100% -105px;
}

.wsite-button:hover {
    background-position: 100% -140px;
}

.wsite-button:active {
    background-position: 100% -175px;
}

.wsite-button-inner {
    height: 34px;
    line-height: 34px;
    display: block;
    font-size: 14px;
    font-weight: normal;
    border: none;
    text-decoration: none;
    padding: 0 10px 0 25px;
    background: url(button.png) no-repeat 0 0;
}

.wsite-button:hover .wsite-button-inner {
    background-position: 0 -35px;
}

.wsite-button:active .wsite-button-inner {
    background-position: 0 -70px;
}

/* large */

.wsite-button-large {
    height: 41px;
    background: url(button_large.png) no-repeat 100% -126px;
    padding: 0 15px 0 0;
}

.wsite-button-large:hover {
    background-position: 100% -168px;
}

.wsite-button-large:active {
    background-position: 100% -210px;
}

.wsite-button-large .wsite-button-inner {
    height: 41px;
    line-height: 41px;
    padding: 0 10px 0 25px;
    background: url(button_large.png) no-repeat 0 0;
}

.wsite-button-large:hover .wsite-button-inner {
    background-position: 0 -42px;
}

.wsite-button-large:active .wsite-button-inner {
    background-position: 0 -84px;
}

/* highlight */

/*
Making the highlighted versions of the buttons is easy because we just need
to switch out the background images. This works because the different button
states (normal, :hover, :active) have their sprite coordinates in the same places.
*/

.wsite-button-large.wsite-button-highlight {
    background-image: url(button_large_highlight_blue.png);
}

.wsite-button-large.wsite-button-highlight .wsite-button-inner {
    background-image: url(button_large_highlight_blue.png);
}

.wsite-button-highlight {
    color: #fff !important;
    background-image: url(button_highlight_blue.png);
}

.wsite-button-highlight .wsite-button-inner {
    background-image: url(button_highlight_blue.png);
}

A: Give CSS style to the div class="statcounter">
div.statcounter{
    max-width: 100px !important;
    max-height: 100px !important;

}

W3Schools example: http://www.w3schools.com/cssref/pr_dim_max-width.asp
On the website you gave in comment the problem seems to be:
 a img { border: 0; width: 100%; //height: auto; }

http://www.globaltecnicosyservicios.com/files/main_style.css?1390835994
In that css file on rule 3.
This 100% width makes all the images on the site 100%.
Edit:
Use a css class and call it "large" for example:
html :
css:    img.large { width:100% }

Change the images you want to have 100% width to the class "large". Don't touch the other images. Should work.

A: You could also try max-width,
.statcounter {
   max-width: 100px;
}


text:
Q: Collection View Controller Doesn't show content I embedded a collection view controller inside a navigation controller the set a view controllers segue to that navigation controller from a tabBar controller but when my collection view controller loads it doesn't display anything! Here is my code
class HomeVC: UICollectionViewController, UINavigationControllerDelegate{

override func viewDidLoad() {
    super.viewDidLoad()
   collectionView?.backgroundColor = UIColor.white
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: self.view.frame.size.width, height: 220)
}

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 0
}

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! HeaderView

    header.fullnameLbl.text = (PFUser.current()?.object(forKey: "name") as? String)?.capitalized
    header.webTxt.text = PFUser.current()?.object(forKey: "web") as? String
    header.webTxt.sizeToFit()
    header.bioLbl.text = PFUser.current()?.object(forKey: "bio") as? String
    header.bioLbl.sizeToFit()
    header.button.setTitle("Edit Profile", for: .normal)

    let avaQuery = PFUser.current()?.object(forKey: "ava") as! PFFile

    avaQuery.getDataInBackground { (data, error) in
        if let err = error{
            print(err.localizedDescription)
            return
        }
        if let imageData = data{
            header.avaImg.image = UIImage(data: imageData)
        }
    }

    return header
}

}

Anybody know why this is happening? I seem to always run into this issue when using collection view controllers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set variable in mySQL I have the following statement:
SELECT
    start_date,
    end_date,
    DATE(now()) BETWEEN start_date AND end_date should_be_live
FROM
    mytable
WHERE
    DATE(now()) BETWEEN start_date AND end_date should_be_live = 1

Is there a way to set a variable should_be_live = the expression DATE(now()) BETWEEN start_date AND end_date. If so, how would I do this?

A: If by "variable" you mean "column in the result set", then yes.  You are basically doing it:
SELECT start_date, end_date,
       ( DATE(now()) BETWEEN start_date AND end_date) as should_be_live
FROM mytable;

If by "variable", you mean that you want to define a column in the select and then filter on it, you cannot do that with where (unless you use a subquery).  You can use having:
SELECT start_date, end_date,
       ( DATE(now()) BETWEEN start_date AND end_date) as should_be_live
FROM mytable
HAVING should_be_live = 1;

This use of having is a MySQL extension.

A: No unfortunately, you will have to repeat the same expression DATE(now()) BETWEEN start_date AND end_date in your WHERE clause unless you are trying to access it in a outer query like
SELECT * FROM (
SELECT
    start_date,
    end_date,
    DATE(now()) BETWEEN start_date AND end_date as should_be_live
FROM mytable ) xxx
WHERE should_be_live = 1;

Column alias are accessible only to GROUP BY, HAVING and ORDER BY clause and not to WHERE clause (that to it's a MySQL extension and not  standard SQL)


text:
Q: why is my compare evaluating to false I'm new to javascript.  I am writing an function to check if a palindrome can be obtained from it by at most one swap of some pair of characters. one problem i am having is that my object seems to look correct in the alerts, but it is evaluating to false no matter what operator I use.  I attached a fiddle
http://jsfiddle.net/sQx4H/89/
What am I doing wrong?
function isOneSwapEnough() {
inputString = 'aabaa'
    var inputStringArray = inputString.split();
    if (isPalandrome(inputStringArray))
    {
        return true;
    }
    //if we made it this far then the string is not a palendrone yet.
    var newCharArray;
    for (var j =0; j<inputStringArray.length; j++)
    {
        newCharArray = inputStringArray;
        for (var k =0; k<inputStringArray.length; k++)
        {
            var tempChar =  inputStringArray[j];
            newCharArray[j] = newCharArray[k];
            newCharArray[k] = tempChar;

            if (isPalandrome(newCharArray))
            {
                return true;
            }
        }
    }
    return false;
}

function isPalandrome(testString)
{
    var firstcheck = [];
    // already a char array... var testStringArray = testString.split();
    //check if already a palendrone
    for (var i =0; i<testString.length; i++)
    {

        firstcheck[testString.length-(i+1)] = testString[i];
        //console.log(testString[i]);
        //console.log(firstcheck[testString.length-i]);
    }
    //console.log(testString);
    //console.log(firstcheck);
    //alert("1: " + typeof  testString);
    //alert("2: " + typeof  firstcheck);
    alert("condition " + firstcheck.valueOf() === testString.valueOf())
    if ( firstcheck.valueOf() == testString.valueOf())
    {
        return true;
    }
}

A: code review
Apart from the comment I left on your question, there's a lot going on with your isPalindrome procedure; my comments inline …
// `isPalindrome` is a nice function name
// `testString` is a terrible parameter name,
// especially since you're passing in an array
function isPalandrome(testString)
{
    // unclear variable name
    var firstcheck = [];

    // by the end of this loop, firstcheck will be a testString in reverse
    // ok, got it
    for (var i = 0; i<testString.length; i++)
    {
        firstcheck[testString.length-(i+1)] = testString[i];
    }
    // the short version of this code is
    var firstcheck = testString.slice(0).reverse()

    // this doesn't do what you think it does
    // `[1,2,3] === [1,2,3]` is false in javascript
    // you cannot compare arrays like that
    if ( firstcheck.valueOf() == testString.valueOf())
    {
        // `if (condition) { return true }` is bad code
        // just use `return condition`
        return true;
    }
    // don't worry, you don't have to compare arrays to check for your palindromes
}

quick & dirty solution
This doesn't work if there are spaces or special characters in the input string, but your question gives no indication of such criteria. So maybe this is all you're looking for.
You do not have to compare arrays to detect a palindrome.

function isPalindrome(str) {
  return str === str.split('').reverse().join('')
}

console.log(isPalindrome('aabaa')) // true
console.log(isPalindrome('racecar')) // true
console.log(isPalindrome('risetovotesir')) // true
console.log(isPalindrome('sorry but not a palindrome')) // false

character swapping
As for the character swapping bit, you have a bit of a problem on your hands there. What are eligible swaps? Can a character only trade places with its immediate neighbour? Or can any two characters be swapped?
input | posssibile swaps
------+------------------------------------------------------------
a     |
ab    | ba
abc   | bac cba acb
abcd  | bacd cbad dbca acbd adcb abdc
abcde | bacde cbade dbcae ebcda acbde adcbe aecdb abdce abedc abced

As you can see, possible swaps grows quickly. Total possible swaps can be computed as
((n - 1) * n / 2), where n = length of input

For example, a string length of 5 will have 10 possible swaps …
((5 - 1) * 5 / 2) = 10

A string length of 20 will have 190 possible swaps. (Relevant: in this situation, n is a triangular number)
Can you come up with a basic procedure which generates and checks each of the possible swaps?
Either way, I still don't think you need arrays for this. I would start by writing a generic charSwap procedure that returns a string with swapped chars. Something like this maybe …

function charSwap(str, x, y) {
  function slice(from,to) {
    return str.substring(from,to)
  }
  let a = str[x], b = str[y]
  return slice(0,x) + b + slice(x+1,y) + a + slice(y+1)
}

console.log(charSwap('abcde',0,1)) // bacde
console.log(charSwap('abcde',0,2)) // cbade
console.log(charSwap('abcde',0,3)) // dbcae
console.log(charSwap('abcde',0,4)) // ebcda

console.log(charSwap('abcde',1,2)) // acbde
console.log(charSwap('abcde',1,3)) // adcbe
console.log(charSwap('abcde',1,4)) // aecdb

console.log(charSwap('abcde',2,3)) // abdce
console.log(charSwap('abcde',2,4)) // abedc

console.log(charSwap('abcde',3,4)) // abced

I'm sure you're probably picking up a pattern there by the end. Then I would use charSwap in isOneSwapEnough. I'll leave it up to you to write the loop for it though. I can give you a little bit of skeleton code to get started …
function isOneSwapEnough(str) {
  // setup loop
  // let x and y be variables for character indexes to swap
  // begin loop
    if (isPalindrome(charSwap(str, x, y)))
      return true
    else
      // continue loop
  // end loop
  return false
}

A: I believe it may have to do with the fact that you are trying to do a direct array comparison. The method below will trip to true though I'm not sure if it's what your looking for.
jsfiddle
if (JSON.stringify(firstcheck) == JSON.stringify(testString)) {
    return true;
}


text:
Q: How can I read json file in local test on Android Studio? I am testing with MockWebServer.
And I need a lot of json files for request and response data.
Hard coded json values seem messy and I want to create json files instead.
So, I created json files in resources(test). And I tried to read file with these methods.
object TestHelper {
    fun read(fileName: String): String {
        val resource = javaClass.classLoader?.getResource(fileName)
        return resource?.readText() ?: ""
    }

    fun readJson(fileName: String): String {
        val byteArray = readBinaryFileFromResources(fileName)
        val sb = StringBuilder("")

        byteArray.forEach {
            println("byte: $it")
            sb.append(it as Char)
        }

        return sb.toString()
    }

    @Throws(IOException::class)
    fun readBinaryFileFromResources(fileName: String): ByteArray {
        var inputStream: InputStream? = null
        val byteStream = ByteArrayOutputStream()
        try {
            inputStream = javaClass.classLoader?.getResourceAsStream(fileName)

            var nextValue = inputStream?.read() ?: -1

            while (nextValue != -1) {
                byteStream.write(nextValue)
                nextValue = inputStream?.read() ?: -1
            }
            return byteStream.toByteArray()
        } catch (e: Exception) {
            println(e.stackTraceToString())
            return byteStream.toByteArray()
        } finally {
            inputStream?.close()
            byteStream.close()
        }
    }
}

None of them seems work. What's the problem with this code?

A: I've had trouble with this before, and I believe it has to do with getting the correct classLoader from the call site, as well as having resources in the src/test/resources not being accessible properly. I eventually got it to work by passing in the calling test class as a reified type parameter:
inline fun <reified T> loadFileText(
    caller: T,
    filePath: String
): String =
    T::class.java.getResource(filePath)?.readText() ?: throw IllegalArgumentException(
        "Could not find file $filePath. Make sure to put it in the correct resources folder for $caller's runtime."
    )

For my setup I have a separate shared module :testtools that I use testImplementation to include in my :app's gradle build so they don't get compiled into the production APK. I have my test resources in:
/testtools/src/main/resources/customfolder

And then calling this from a unit test class in :app like so:
class UnitTestClass {

    @Test
    fun myTest() {
        loadFileText(this, "/customfolder/file_name.txt")
    }
}

You might have some luck putting your resources straight into /app/src/test/resources/customfolder, I haven't tried in a while.


text:
Q: How to connect pickerviews and labels in iOS? I have two pickerView and two Label on my ViewController.
The question is how I could connect labels to pickerView's data array (string type) and show in labels chosen pickerView cell?
@IBOutlet weak var valuetype1: UILabel!

    var pickerData: [String] = [String]()

 override func viewDidLoad() {
        super.viewDidLoad()

        self.picker1.delegate = self
        self.picker1.dataSource = self
        self.picker2.delegate = self
        self.picker2.dataSource = self

        pickerData = ["Годы", "Месяцы", "Недели", "Дни", "Часы", "Минуты"]
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return pickerData.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    valuetype1.text = pickerData[row]
    valuetype2.text = pickerData[row]
}

How could you see I connected labels (valuetype(1..2)) to pickerData but it always show in both labels one String. I need to show in first label String chosen in pickerView1 and another string in second label, chosen in pickerView2.

A: UIPickerViewDelegate has a method called pickerView(_:didSelectRow:inComponent:). Add this method to your VC class. This method gets called whenever the user selects a row.
Your implementation should look somewhat similar to this.
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    valuetype1.text = pickerData[row]
}

For more information refer to the apple docs: https://developer.apple.com/documentation/uikit/uipickerviewdelegate/1614371-pickerview
EDIT:
When you are using the same controller as a delegate for multiple UIPickerViews, then you can check which picker view triggered the method call simply by comparing the pickerView argument on the pickerView(_:didSelectRow:inComponent:) method.
Try this:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == picker1 {
        valuetype1.text = pickerData[row]
    } else if pickerView == picker2 {
        valuetype2.text = pickerData[row]
    }
}


text:
Q: WPF: Use a different template depending on size and number of items I'm trying to work out how I can alter the template depending on the size and number of items. This is very similar to the ribbon which dynamically changes depending on the size, or Windows 7 thumbnail of programs.
In this case, it's an ItemTemplate of a ListBox and I want to reduce the size of the image or not display it, rather than having scroll bars.
<ListBox ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Title}" />
                <Image Source="{Binding ImageUrl}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Thanks

A: You could set a style on the ListBox, which switches ItemTemplate based on the number of items.
<ListBox ItemsSource="{Binding Items}">
    <ListBox.Resources>
        <local:SizeConverter x:Key="SizeConverter"/>
        <DataTemplate x:Key="SmallTemplate"></DataTemplate>
        <DataTemplate x:Key="MediumTemplate"></DataTemplate>
        <DataTemplate x:Key="LargeTemplate"></DataTemplate>
    </ListBox.Resources>
    <ListBox.Style>
        <Style TargetType="ListBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Items.Count, Converter={StaticResource SizeConverter}}" Value="Small">
                    <Setter Property="ItemTemplate" Value="{StaticResource SmallTemplate}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=Items.Count, Converter={StaticResource SizeConverter}}" Value="Medium">
                    <Setter Property="ItemTemplate" Value="{StaticResource MediumTemplate}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=Items.Count, Converter={StaticResource SizeConverter}}" Value="Large">
                    <Setter Property="ItemTemplate" Value="{StaticResource LargeTemplate}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListBox.Style>
</ListBox>

The SizeConverter would be an IValueConverter which returns a size category based on the incoming count, the convert method could be something like this:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    int count = (int)value;
    if (count < 4) return "Large";
    if (count < 12) return "Medium";
    return "Small";
}

A: You probably want to use the DataTemplateSelector functionality in WPF:
From the link:

Typically, you create a
  DataTemplateSelector when you have
  more than one DataTemplate for the
  same type of objects and you want to
  supply your own logic to choose a
  DataTemplate to apply based on the
  properties of each data object. Note
  that if you have objects of different
  types you can set the DataType
  property on the DataTemplate. If you
  do that then there is no need to
  create a DataTemplateSelector.
  Furthermore, if you have objects of
  the same type but with different
  properties, you can also consider
  using a DataTrigger or a data
  converter. For more information, see
  Data Templating Overview.

Or alternatively, as mentioned above, a DataTrigger may be of use.


text:
Q: VB6 Memory Limitations I'm currently supporting a VB6 application (that we are replacing, but it's a slow process!) that is running on several servers. Can anyone tell me please what the maximum amount of memory of VB6 process can address is? We are using a variety of operating systems:

*

*Windows Server 2003 32bit

*Windows Server 2008 64bit

*Windows Server 2008 R2 64bit

I've tried using resources like this:
https://blogs.msdn.microsoft.com/tom/2008/04/10/chat-question-memory-limits-for-32-bit-and-64-bit-processes/
But I'm skeptical if this is accurate due to it discussing .NET based applications, however I can't find anything more on point than this.

A: It is hard to take these "What if Superman got in a fight with God" questions too seriously.  Long before this becomes a concern you should have moved from memory-resident data structures to a disk file or a database anyway.
But even without linking with /LARGEADDRESSAWARE and booting into 3GB mode a VB6 program can address quite a bit of data on 32-bit Windows.
Option Explicit

Private Sub Main()
    Const MAX_BYTES As Long = &H63700000
    Dim Bytes() As Byte

    ReDim Bytes(MAX_BYTES)
    Bytes(MAX_BYTES) = 255
    MsgBox "Success" & vbNewLine & vbNewLine _
         & "Bytes(MAX_BYTES) = " & CStr(Bytes(MAX_BYTES)) & vbNewLine & vbNewLine _
         & "MAX_BYTES = " & Format$(MAX_BYTES, "#,##0")
End Sub

Result:
Success

Bytes(MAX_BYTES) = 255

MAX_BYTES = 1,668,284,416

The linked blog post is correct in pointing out the limitations of a .Net process and their inability to cope with using large amounts of data.  Scripting engines like .Net just are not built for these things, and don't underestimate the overhead of the gigantic libraries even the simplest .Net program drags into its address space.


text:
Q: Attaching Excel File in Email I am attempting to fix an issue with a VBA for attaching a file from Excel directly into email with a .Display before user sends. The file should save, create a new temp file, copy and paste that temp file directly into the body of the email, while attaching the actual original document to the email for reference. Once this is done, it should kill the temp file without saving it.
The issue I'm having is that it will create the new temp workbook, but not copy and paste info into email or attach the document in the email. My code is below with the stock email address. Any Help is appreciated. The error message always seems to fall on .Attachments.Add (ActiveDocument.FullName)
Sub SendEmailOutlook()
    ActiveWorkbook.Save

    'Send an email. basically just to standardize and error-proof the process
    'RangetoHTML function (below this macro) allows a range of cells to be pasted into the email body
    Dim strbody As String
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
    Dim Message As String
    Dim subject As String
    Dim UpdateTime As String

    'this line is extra for HTML formatting but it makes the text easier to read
    strbody = "
"

    subject = "2018 Safety Walk Form for " & Sheets("2018 Safety Walk").Range("H5") & " " & Sheets("2018 Safety Walk").Range("K5")

    Message = "Team

Please see the attached form for, " & Sheets("2018 Safety Walk").Range("K5")

    'Set last row based on input data
    '    Dim lastRow As String
    '    lastRow = Sheets("Email").UsedRange.Rows.Count
    'Set range for email body
    'The column is on the right, the row on the left. Change to .Range("A1:H30") if you want it to be static

    Set rng = Sheets("2018 Safety Walk").Range("B5:K43")

    'Create email
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    With OutMail
        .To = "123@123.com"
        .BCC = ""
        .subject = subject
        .HTMLBody = strbody & Message & RangetoHTML(rng) & "
"
        .Attachments.Add (ActiveDocument.FullName)
        .Display    'you can use .Send to have the macro send the email without needing to confirm it
    End With

    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)

    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False

        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close SaveChanges:=False

    'Delete the htm file we used in this function
    Kill TempFile
    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

A: From the OP's comment:

Upon running the macro, error message received is, "run-time error
  '-2147024894 (80070002)': Cannot find this file. Verify the Path and
  file name are correct."

This is because in your RangeToHTML function you are creating two temporary workbooks but only closing one. So once RangeToHTML returns, your ActiveWorkbook is referring to the remaining temporary workbook and not to your original. Since it has not been saved, its .FullName property does not yet have a value, so thus the "Cannot find this file" error.
In RangeToHTML, get rid of one of these sections where you copy/paste and your problem will be solved:
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)

With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
    .Cells(1).Select
    Application.CutCopyMode = False

    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
    .Cells(1).Select
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

You should also, in your SendEmailOutlook procedure, not use ActiveWorkbook at all, since as you can see this will trip you up if you aren't careful. It's always better to set and work with a reference directly to the workbook.
So, something like:
Dim wb as Workbook
Set wb = Workbooks("Your Workbook Name")

or:
Dim wb as Workbook
Set wb = ActiveWorkbook

at the start of SendEmailOutlook, and then use wb wherever you currently use ActiveWorkbook elsewhere in the procedure.


text:
Q: r gganimate: transition_reveal (changing title) I'd like to create a transition_reveal animation using gganimate whereby the title changes along the currently revealed iteration. So, the title at the start would be "Date: 2019-01-01" and then gradually adapt alongside the animation and finish by showing "Date: 2019-01-20".
a <- seq(1,20,1)
b <- seq(1,40,2)
c <- seq(as.Date("2019-01-01"), as.Date("2019-01-20"), by="days")
db <- cbind(a,b,c) %>% as.data.frame()

p <- ggplot(db, aes(x = a, y = b)) +
  geom_path() +
  labs(title = "Date: {frame_time}") +
  transition_reveal(c)

animate(p, renderer = gifski_renderer(loop = FALSE), nframes = 90, fps = 30, height = 600, width = 1100, start_pause = 0)

Currently, I get the following error:
50: object 'fame_time' not found


text:
Q: Passing columns to kableExtra arguments within dplyr I'm trying to use kable and kableExtra to format tables created using pipes, and I can't get the conditional formatting arguments (row_spec, column_spec) to accept variables piped from the generated code.
In the toy example below I create a variable called bg within the dataframe that I want to use to create bands of background colour, but row_spec and column_spec don't seem to recognize that as a variable. Note that creating the variable outside of the pipes isn't an option - the actual use case is much more complicated than that, and the variables used in the process don't exist before that.

library(kableExtra)
set.seed(111)

df = data.frame(var1 = sort(sample(LETTERS[1:3],10,TRUE)),
                var2 = sample(1:4,10,TRUE),
                var3 = runif(10,0,1))
df %>%
  mutate(bg = cumsum(!duplicated(var1))%%2)%>%
  kable() %>%kable_styling()%>%
  column_spec(1,color=bg)

Error in ensure_len_html(color, nrows, "color") : object 'bg' not found

EDIT: You can do it in two steps easily enough, so I'll include that here, as well as the resulting table that I'm looking for
d = df %>%
  mutate(bg = cumsum(!duplicated(var1))%%2)
kable(d) %>% kable_styling(full_width=FALSE) %>%
  row_spec(which(d$bg==1),background=grey(0.75))

A: This might work:
library(tidyverse)
library(kableExtra)

set.seed(111)
df = data.frame(var1 = sort(sample(LETTERS[1:3],10,TRUE)),
                var2 = sample(1:4,10,TRUE),
                var3 = runif(10,0,1))

df %>%
  mutate(bg = cumsum(!duplicated(var1))%%2) %>%
  mutate(bg = cell_spec(bg, color = spec_color(bg))) %>%
  kable(escape = F) %>% kable_styling()

Output:

You may find more information here (page 16): https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf
Version with background color:
df %>%
  mutate(bg = cumsum(!duplicated(var1))%%2) %>%
  mutate(bg = cell_spec(bg, color = "white", bold = T,
                        background = spec_color(bg))) %>%
  kable(escape = F) %>% kable_styling()

Output with background color:


text:
Q: Is there a standard practice for storing flat data files that are used for testing in a Django project? I'm unit testing the way that my Django application loads and processes various flat files and I'm having trouble deciding where to store the files that contain the data for these tests. Is there a standard practice or location for this?
Would it make more sense to store these files in one of the STATICFILES_DIRS or in a subdirectory of MEDIA_ROOT, or some other directory? If some other directory, how might that be configured in the settings module?
For example:
from pathlib import Path
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase

def simulate_uploaded_file(data_path: Path, filename: str)
    content_type = get_content_type(filename)
    filepath = data_path / filename
    content = open(filepath, 'rb').read()
    data_file = SimpleUploadedFile(data_file_path, content, content_type)

class TestFileHandler(TestCase):
    @classmethod
    def setUpTestData(cls):
        test_data_path: Path = settings.TEST_DATA_DIR # <- IS THERE A STANDARD LOCATION FOR THIS?
        cls.valid_csv: SimpleUploadedFile = simulate_uploaded_data(test_data_path, 'filename.csv')


text:
Q: iOS 64bit app weird behaviour for headers, test tools I have a 64bit iOS app, but various tools and functions don't seem to work on it. This app was downloaded from the App Store, so it passed all Apple's checks etc.
It is a 64bit app, as seen by the mach-o header-
Mach header
  magic      cputype cpusubtype  caps    filetype ncmds sizeofcmds   flags
MH_MAGIC_64 16777228          0  0x00     EXECUTE    47       5480       NOUNDEFS DYLDLINK TWOLEVEL WEAK_DEFINES BINDS_TO_WEAK PIE

It doesn't seem to even have the LC_ENCRYPTION_INFO_64 (as 64 bit app) in the header load commands, and is missing all info about cryptoffset, cryptid etc-
root# otool -l myApp | grep -i crypt
root#
root# otool -l myApp | grep -i LC_ENCRYPTION_INFO
root#

Using nm to get the functions, classes and methods are referenced in the application and in the dynamically loaded libraries, is met with an error.
nm myApp
nm: object: myApp malformed object (unknown load command 4)

And lastly, when I dump using class-dump-z, I get null, this is the result whether I do it on the standard binary from App Store, or if I decrypt using Clutch first.
/**
* This header is generated by class-dump-z 0.2a.
*
* Source: (null)
*/

Lipo also throws an error as well
root# lipo -info myApp
dyld: lazy symbol binding failed: Symbol not found: _map_fd
Referenced from: /usr/bin/lipo
Expected in: dyld shared cache

dyld: Symbol not found: _map_fd
Referenced from: /usr/bin/lipo
Expected in: dyld shared cache

Trace/BPT trap: 5

What's going on?

A: Turns out you need to use dylib and dumpdecrypted first - https://github.com/stefanesser/dumpdecrypted and then use the newest version of class-dump running on OSX - http://stevenygard.com/projects/class-dump/ this will let you successfully class-dump arm64 bit binaries.


text:
Q: Node js+ Error: This socket has been ended by the other party] code: 'EPIPE' I am using nodejs and postgresql
I am try to insert data through ajax call.
Trying to the following things.
1. Insert the record in conversation table.
2. get the conversation table last insert id(primary key).
3. last insert id try to insert other table multiple times.

Error:
The query was working good. after insert this data in front end side not working. When i try to refresh the page in front-end side I am getting the following error in terminal "{ [Error: This socket has been ended by the other party] code: 'EPIPE' }"
I added my following code.
var express = require('express');
var router = express.Router();
var pg = require('pg');
var client = require('../routes/database.js');
var cookieParser = require('cookie-parser');
var dateFormat = require('date-format');
var async = require('async');
var today = dateFormat(new Date());

router.post('/conversation/start', function(req, res) {
    //var partyId = sess.userId;
         var partyId = 20;
    var topic = "welcome";
    var msg = "test message";
    var to_user_details = JSON.parse([{"id":1},{"id":2},{"id":3},{"id":4},{"id":5}]);

    client.query('BEGIN', function(err, result) {
        if (err) {
            console.log(err);
            return rollback(client);
        }
        client.query('insert into conversation (party_id , topic, message, created_on) values (' + "'" + partyId + "'" + ',' + "'" + topic + "'" + ',' + "'" + msg + "'" + ',' + "'" + today + "'" + ') RETURNING id', function(err, result) {
            if (err) {
                console.log(err);
                return rollback(client);
            }
            var conversationId = result.rows[0].id;
            async.each(to_user_details, addToUsersConversation.bind(null, conversationId), function(err) {
                if (err) {
                    console.log(err);
                    return rollback(client);
                }
                client.query('COMMIT', client.end.bind(client));
                res.send("conversation added");
            });
        });

    });

});

var addToUsersConversation = function(conversationId, toUserDetails, cb) {
    client.query('insert into conversation_to (conversation_id , party_id, type) values (' + "'" + conversationId + "'" + ',' + "'" + toUserDetails.id + "'" + ',' + "'" + toUserDetails.type_flag + "'" + ')', function(err, result) {
        if (err)
            return cb(err);
        cb(null);
    });

};


text:
Q: Using a 2TB SSD on a 2016 MacBook Pro My MacBook Pro was filled up by old iPhone backups. I need to clear them up before I can use it to do backup for the 4th phone of my family. I found I had a 2 TB external SSD and tried to copy things on it but failed. The system said the SSD was read-only. Disk utilities said the 2 TB SSD was formatted in NTFS format. Was that the reason that my MacBook Pro refuses to copy things onto it? Do I need to reformat that into Mac format, but was there a 3rd solution that I can share the SSD among my computers?

A: You could try shrinking the partition containing NTFS volume and create a new FAT32 writable volume in the free space. To do this, you would need either a computer with Windows installed or your existing Mac. Do to this with your existing Mac, you would have to use the Boot Camp Assistant to make a bootable Windows 10 USB flash drive installer. Instead of installing Windows, you would boot from this installer, open a Command Prompt window and use the diskpart command to shrink the NTFS volume and create the new writable volume. If you want the new volume to be ExFAT or Mac OS Extended (Journaled) format, then you would have to erase the new FAT32 volume from macOS using either diskutil or the Disk Utility.

A: macOS is able to read NTFS by default, but it doesn't come with write support. There are third-party solutions for that, like NTFS-3G (there are multiple questions dealing with this product here on Apple.SE).
If you are using this SSD only on your Mac, using NTFS would be a poor solution (performance, feature support). Instead, just reformat the SSD with APFS.
For pure data transfer, another option would be to format the disk with exFAT which has read and write support natively on both Windows and macOS. This filesystem is lacking features you would expect on a modern system, but if all you want is transfer images, videos, ZIPs, and the like, it is sufficient.


text:
Q: Splitting Lists elements further I have a number of .txt files with varying numbers of columns (but always the same number of elements in each.
<1,1,1,1,1,>
<1,2,1,2,1,>
<2,3,2,3,2,>
<4,2,4,2,4,>

Since this is saved as a .txt file when I split by
    lines = [line.rstrip('\n') for line in f]

I get
['<1,1,1,1,1,>', '<1,2,1,2,1,>', '<2,3,2,3,2,>', '<4,2,4,2,4,>']

Is there a simple way to access each of the elements within the list (ie individual numbers so I can output them)?

A: You can do following:
lines = [line.strip('<>,\n').split(',') for line in f]

It will return a list of lists containing the numbers as strings:
[['1', '1', '1', '1', '1'],
 ['1', '2', '1', '2', '1'],
 ['2', '3', '2', '3', '2'],
 ['4', '2', '4', '2', '4']]

If you want the numbers as integers instead you can call map after splitting a line:
lines = [map(int, line.strip('<>,\n').split(',')) for line in f]

A: from ast import literal_eval
Once you have done lines = [line.rstrip('\n') for line in f] you could do this:
linelist = []
for line in lines:
    linelist.append( literal_eval( line.replace( "<", "[" ).replace( ">", "]" ) ) )

This will create a list of lists. For the example you have provided, you'll get some thing similar to:
[[1, 1, 1, 1, 1], [1, 2, 1, 2, 1], [2, 3, 2, 3, 2], [4, 2, 4, 2, 4]]

You can use this for further processing.
Or directly do:
lines = [ literal_eval( line.rstrip('\n').replace( "<", "[" ).replace( ">", "]" ) ) for line in f]

The result will be the same.


text:
Q: Django save an image asynchronous during a request I need to save an image on Amazon WS S3 using Django.
I have this code:
try:
                    img_temp = NamedTemporaryFile(delete=True)
                    img_temp.write(urllib2.urlopen(urlImageTo Download).read())
                    img_temp.flush()
                    p.image.save('image.jpg', File(img_temp))
                    p.save() //P is an ImageField

                except urllib2.HTTPError:
                    continue

I integrated django-storages to save directly the image in Amazon S3.
I have to save the image during a request (in the request I have an URL of an image that I have to download it and resave in Amazon S3) but I think that I can to have  this line:

p.image.save('image.jpg', File(img_temp))

asynchronous.
In this case I can return immediately the response of my request while I can save the image on S3
How can I have this? Is Possible?


text:
Q: How Can I Access Method to Method Inside the Same Class? using namespace std;
class Puzzle
{
public:
    void SetTable() //Is there a better way to do this? (2d array)
    {
        const int four = 4;
        char Table[four][four]=

        {
            {'f', 'k', 's','a'},
            {'l', 'u', 'o','w'},
            {'y', 'o', 'n', 'a'},
            {'x', 't', 'o', 'y'}
        };
    }

    void OutputTable()
    {
        int n=0;
        while (n < 4)
        {
            for (int x = 0; x < 4; x++)
            {
                cout << Table[x][n] << "   "; //error here
            }
            cout << endl;
            cout << endl;
            n++;
        }

    }
};

int main()
{
   Puzzle connect;
   connect.SetTable();
   connect.OutputTable();
   return 0;
}

Is there a better way to set a 2d array inside the class Puzzle?
How can I access void SetTable inside void OutputTable?
All variables must be inside the class Puzzle.
Thanks in advance!

A: I will advise you to practice more as this you are showing in your question is wrong and there are many ways to implement it and this is the wrong way because the 2D array as you said is not accessible from anywhere else, making it something like hidden and the function does not sets the contents of the 2D array just declares that there is a 2D array inside the function only.
To help you start, do this:
#include <iostream>
using namespace std;
class Puzzle
{
public:
    char Table[4][4] =
    {
        {'f', 'k', 's','a'},
        {'l', 'u', 'o','w'},
        {'y', 'o', 'n', 'a'},
        {'x', 't', 'o', 'y'}
    };
    // This function will be more useful if the `Table` is not public
    void SetTable(int row, int col, char value)
    {
        Table[row][col] = value;
    }

    void OutputTable()
    {
        int n=0;
        while (n < 4)
        {
            for (int x = 0; x < 4; x++)
            {
                cout << Table[x][n] << "   "; //error here
            }
            cout << endl;
            cout << endl;
            n++;
        }

    }
};

int main()
{
   Puzzle connect;
   connect.SetTable(2, 3, 'A');
   connect.OutputTable();
   return 0;
}

A: Use std::array as a class member variable to realize that.
Your code should look as follows:
using namespace std;
class Puzzle
{
    constexpr int four = 4;
    std::array<std::array<char>,four>four> Table;

public:
    Puzzle() : Table {
            {'f', 'k', 's','a'},
            {'l', 'u', 'o','w'},
            {'y', 'o', 'n', 'a'},
            {'x', 't', 'o', 'y'}
        } {}
    }
    // void SetTable() omit that completely

    void OutputTable()
    {
        for(const auto& row : Table) {
            for(const auto& col : row) {
            {
                cout << col << " ";
            }
            cout << endl;
        }
    }
};

int main()
{
   Puzzle connect;
   connect.OutputTable();
   return 0;
}


text:
Q: My loop won't execute? import java.util.Scanner;

public class ManySubstrings {
    public static void main(String[] args) {
        String line;
        int sub, length;
        Scanner kb = new Scanner(System.in);
        System.out.print("Enter a string: ");
        line = kb.nextLine();
        System.out.print("Enter substring length: ");
        sub = kb.nextInt();
        length = line.length();

        for(int i=0; i< length;i=+sub){
            System.out.println(line.substring(i,sub));
            sub= + sub;
        }
    }
}

Expected output
 Enter a string: anthropomorphization
 Enter substring length: 3
 "ant"
 "nth"
 "thr"
 "hro"
 "rop"
 "opo"
 "pom"
 "omo"
 "mor"
 "orp"
 "rph"
 "phi"
 "hiz"
 "iza"
 "zat"
 "ati"
 "tio"
 "ion"

I need a "for" loop to go through the length of the word with substring length defined by the user to get all substrings of the word to the end

A: public static void main(String[] args) {
    String line;
    int sub, length;
    Scanner kb = new Scanner(System.in);
    System.out.print("Enter a string: ");
    line = kb.nextLine();
    System.out.print("Enter substring length: ");
    sub = kb.nextInt();
    length = line.length();

    for (int i = 0 ; i < length - (sub - 1) ; i++) { // no need to loop it to end of string length
        if (i + sub <= length)
            System.out.println(line.substring(i, i + sub));
    }
}

Ouput
Enter a string: anthropomorphization
Enter substring length: 3
ant
nth
thr
hro
rop
opo
pom
omo
mor
orp
rph
phi
hiz
iza
zat
ati
tio
ion

A: Solution:
You almost had it correct, notice the way the loop is configured.
Your solution was trying to be overly clever with the loop and was overly complex.
Also notice how proper formatting makes the code easier to read.
Of note is the condition that we don't loop to the complete end of the string.
Important:
We stop at < line.length() -(sub - 1) because we would index past the end of the String and get an exception if we went any further.
public static void main(final String[] args)
{
    final Scanner kb = new Scanner(System.in);
    System.out.print("Enter a string: ");
    final String line = kb.nextLine();
    System.out.print("Enter substring length: ");
    final int sub = kb.nextInt();

    for (int i = 0; i < line.length() - (sub-1); i++)
    {
        System.out.println(line.substring(i,i+sub));
    }

    // abcdefghijklmnopqrstuvwxyz
}

Outputs:
Enter a string: abcdefghijklmnopqrstuvwxyz
Enter substring length: 3
abc
bcd
cde
def
efg
fgh
ghi
hij
ijk
jkl
klm
lmn
mno
nop
opq
pqr
qrs
rst
stu
tuv
uvw
vwx
wxy
xyz

And:
Enter a string: abcdefghijklmnopqrstuvwxyz
Enter substring length: 5
abcde
bcdef
cdefg
defgh
efghi
fghij
ghijk
hijkl
ijklm
jklmn
klmno
lmnop
mnopq
nopqr
opqrs
pqrst
qrstu
rstuv
stuvw
tuvwx
uvwxy
vwxyz

A: You can change your for to this:
for (int i = 0; i < length - sub + 1; i++){
    System.out.println(line.substring(i, i + sub));
}

What this does is iterating from first character to third from last and always substring-ing from index to index + sub.

A: this code is complicated and the cause why your sub double each loop
   sub= + sub;

use ++ instead in incrementing sub
for(int i=0; i< length; i = sub){
    System.out.println(line.substring(i,sub));
    sub++;
}


text:
Q: Formula for Legendre polynomials by use of Cauchy's Integral Formula (From _Visual Complex Analysis_) I decided to look through Tristan Needham's Complex Analysis book since it's usually mentioned with great praise. Just doing some exercises, I got stuck on #4 of Chapter 9).
Here $P_n(z)$ denotes the $n$-th Legendre polynomial. I've been able to derive that
$$
P_n(z)=\frac{1}{2\pi i}\int_K\frac{(Z^2-1)^n}{2^n(Z-z)^{n+1}}dZ
$$
for $K$ any simple loop around $z$.
Then the book says by taking $K$ to be a circle of radius $\sqrt{|z^2-1|}$ centered at $z$,
$$
P_n(z)=\frac{1}{\pi}\int_0^\pi(z+\sqrt{z^2-1}\cos t)^n dt.
$$
I tried to rewrite the RHS of the original equation by reparametrizing $Z=z+\sqrt{|z^2-1|}e^{it}$. However, upon rewriting in terms of the standard substitutions, the integral becomes unmanageable. I have $dZ=i\sqrt{|z^2-1|}e^{it}dt$, $Z^2-1=z^2+2z\sqrt{|z^2-1|}e^{it}+|z^2-1|e^{2it}-1$, $(Z-z)=\sqrt{|z^2-1|}e^{it}$.
Substituting in,
$$
\frac{1}{2^{n+1}\pi i}\int_0^{2\pi}\left(\frac{Z^2-1}{Z-z}\right)^2\frac{i\sqrt{|z^2-1|}e^{it}dt}{\sqrt{|z^2-1|}e^{it}}
$$
which simplifies to
$$
\frac{1}{2^{n+1}\pi}\int_0^{2\pi}\left(\frac{z^2-1}{\sqrt{|z^2-1|}e^{it}}+2z+\sqrt{|z^2-1|}e^{it}\right)^n dt.
$$
Is there a way to put this into the final desired form? Thanks.

A: Let's start with :
$$
I(z)=\frac{1}{2^{n+1}\pi}\int_0^{2\pi}\left(\frac{z^2-1}{\sqrt{|z^2-1|}e^{it}}+2z+\sqrt{|z^2-1|}e^{it}\right)^n dt
$$
If $z^2-1\ge 0$ then :
$$
I(z)=\frac{1}{2^{n+1}\pi}\int_0^{2\pi}\left(\sqrt{|z^2-1|}e^{-it}+2z+\sqrt{|z^2-1|}e^{it}\right)^n dt
$$
$$
=\frac{1}{2\pi}\int_0^{2\pi}\left(\sqrt{z^2-1}\cos(t)+z\right)^n dt
$$
If $z^2-1< 0$ then :
$$
I(z)=\frac{1}{2^{n+1}\pi}\int_0^{2\pi}\left(\frac{-(1-z^2)e^{-it}}{\sqrt{1-z^2}}+2z+\sqrt{1-z^2}e^{it}\right)^n dt
$$
$$
=\frac{1}{2^{n+1}\pi}\int_0^{2\pi}\left(-\sqrt{1-z^2}e^{-it}+2z+\sqrt{1-z^2}e^{it}\right)^n dt
$$
$$
=\frac{1}{2^{n+1}\pi}\int_0^{2\pi}\left(\sqrt{1-z^2}(-e^{-it}+e^{it})+2z\right)^n dt
$$
$$
=\frac{1}{2^{n+1}\pi}\int_0^{2\pi}\left(\sqrt{z^2-1}(e^{it}-e^{-it})i+2z\right)^n dt
$$
(using $\sqrt{-1}=i$, $\sqrt{-1}=-i$ would give the same result as we will see) (see too this)
$$
=\frac{1}{2\pi}\int_0^{2\pi}\left(\sqrt{z^2-1}(-\sin(t))+z\right)^n dt
$$
use the change of variable $t=x+3\frac{\pi}2$ to get (cutting the integral in two parts $(0, 2\pi-3\pi/2)$ and $(-3\pi/2,0)$ with the second interval replaced by $2\pi-3\pi/2,2\pi$) :
$$
=\frac{1}{2\pi}\int_0^{2\pi}\left(\sqrt{z^2-1}\cos(x)+z\right)^n dx
$$
so that for any real $z$ we have :
$$
I(z)=\frac{1}{2\pi}\int_0^{2\pi}\left(\sqrt{z^2-1}\cos(t)+z\right)^n dt
$$
Analytic continuation should allow you to extend this in the complex plane (we are searching polynomials after all!) but this is probably not the simple answer you hoped...


text:
Q: Primary constructor call expected this is example of inheritance in Kotlin.
open class Person() {
    var _name : String = ""
    var _age : Int = 0

    constructor(name: String, age : Int)  : this(){
        _name = name
        _age = age
    }
}

class Student() : Person() {
    var _university : String = ""

    constructor (name : String, age: Int, university: String) : super(name, age){
        _university = university
    }
}

fun main() {
   var person = Person("a", 10)
   var student = Student("b", 18, "MIT")
   println("${person._name} : ${person._age}")
   println("${student._university}")
}

How can I resolve error "Primary constructor call expected" in this case?

A: If a class has a primary constructor, you must delegate the secondary constructors to the primary. Which is the case for Student class which is not doing so.
First you should remove the boilerplate of Person class following Kotlin's idioms (using optional parameters rather than constructor overloading).
// This one's completely optional to do, skip if you don't want to follow idioms
open class Person(
    var name : String = ""
    var age : Int = 0
)

And then Student class should have two separate constructors, because if you take a primary constructor then other constructors must delegate to it:
class Student: Person {
    var university: String = ""

    constructor() : super()

    constructor (name: String, age: Int, university: String) : super(name, age) {
        this.university = university
    }
}


text:
Q: java.lang.NullPointerException: Attempt to invoke virtual method I am trying to create a sign in function with register and login by mysql, but my app crashes everytime. I can't find the issue!
It is a code from a tutorial, and I adjusted it to my own needs.
Here is the Logcat:
08-23 18:59:43.828    7756-7756/com.example.boss.partyradarvol4 I/art﹕ Late-enabling -Xcheck:jni
08-23 18:59:43.933    7756-7774/com.example.boss.partyradarvol4 D/OpenGLRenderer﹕ Render dirty regions requested: true
08-23 18:59:43.942    7756-7756/com.example.boss.partyradarvol4 D/﹕ HostConnection::get() New Host Connection established 0xabc785e0, tid 7756
08-23 18:59:43.974    7756-7756/com.example.boss.partyradarvol4 D/Atlas﹕ Validating map...
08-23 18:59:44.239    7756-7774/com.example.boss.partyradarvol4 D/libEGL﹕ loaded /system/lib/egl/libEGL_emulation.so
08-23 18:59:44.240    7756-7774/com.example.boss.partyradarvol4 D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_emulation.so
08-23 18:59:44.251    7756-7774/com.example.boss.partyradarvol4 D/libEGL﹕ loaded /system/lib/egl/libGLESv2_emulation.so
08-23 18:59:44.260    7756-7774/com.example.boss.partyradarvol4 D/﹕ HostConnection::get() New Host Connection established 0xa3316120, tid 7774
08-23 18:59:44.297    7756-7774/com.example.boss.partyradarvol4 I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-23 18:59:44.332    7756-7774/com.example.boss.partyradarvol4 D/OpenGLRenderer﹕ Enabling debug mode 0
08-23 18:59:44.352    7756-7774/com.example.boss.partyradarvol4 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-23 18:59:44.352    7756-7774/com.example.boss.partyradarvol4 W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa33192c0, error=EGL_SUCCESS
08-23 18:59:49.134    7756-7774/com.example.boss.partyradarvol4 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-23 18:59:49.135    7756-7774/com.example.boss.partyradarvol4 W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xabcff960, error=EGL_SUCCESS
08-23 18:59:53.490    7756-7817/com.example.boss.partyradarvol4 D/Anfrage﹕ startet
08-23 18:59:53.492    7756-7817/com.example.boss.partyradarvol4 E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
08-23 18:59:53.492    7756-7817/com.example.boss.partyradarvol4 E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
08-23 18:59:53.517    7756-7817/com.example.boss.partyradarvol4 E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #5
    Process: com.example.boss.partyradarvol4, PID: 7756
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
            at com.example.boss.partyradarvol4.Login.Register$CreatUser.doInBackground(Register.java:92)
            at com.example.boss.partyradarvol4.Login.Register$CreatUser.doInBackground(Register.java:62)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
08-23 18:59:53.576    7756-7774/com.example.boss.partyradarvol4 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-23 18:59:53.577    7756-7774/com.example.boss.partyradarvol4 W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xabcff540, error=EGL_SUCCESS
08-23 18:59:54.094    7756-7778/com.example.boss.partyradarvol4 D/Anfrage﹕ startet
08-23 18:59:54.094    7756-7778/com.example.boss.partyradarvol4 E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
08-23 18:59:54.094    7756-7778/com.example.boss.partyradarvol4 E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
08-23 18:59:54.095    7756-7778/com.example.boss.partyradarvol4 I/Process﹕ Sending signal. PID: 7756 SIG: 9

Register.java:
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.boss.partyradarvol4.R;
import com.example.boss.partyradarvol4.SupportKlassen.JSONEncorder;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Register extends Activity implements View.OnClickListener{

    private EditText eUsername, ePasswort;
    private Button  bRegestrieren;

    private ProgressDialog pDialog;

    //Encoder
    JSONEncorder jsonEncorder = new JSONEncorder();

    // Verbindung zum Server
    private static final String Reg_URL = "http://127.0.0.1:80/webservice/login.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_);

        // Editfelder
        eUsername = (EditText)findViewById(R.id.FELD_Reg_username);
        ePasswort = (EditText)findViewById(R.id.FELD_Reg_passwort);

        bRegestrieren = (Button)findViewById(R.id.BUTTON_Reg_regestrieren);
        bRegestrieren.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        new CreatUser().execute();
    }

    class CreatUser extends AsyncTask<String,String,String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            super.onPreExecute();
            pDialog = new ProgressDialog(Register.this);
            pDialog.setMessage("erstelle user...");
            //unbestimmt
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            int success;
            String username = eUsername.getText().toString();
            String passwort = ePasswort.getText().toString();

            try {
                List<NameValuePair> parameter = new ArrayList<NameValuePair>();
                parameter.add(new BasicNameValuePair("username", username));
                parameter.add(new BasicNameValuePair("password", passwort));

                Log.d("Anfrage", "startet");

                JSONObject json = jsonEncorder.makeHttpRequest(Reg_URL, null ,parameter);

                Log.d("Restrierung vorbreitet", json.toString());

                success = json.getInt(TAG_SUCCESS);
                if(success == 1){
                    Log.d("User erstellt", json.toString());
                    finish();
                    return json.getString(TAG_MESSAGE);
                } else {
                    Log.d("Registrierung fehlgeschlagen!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            if(file_url != null){
                Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
            }
        }
    }
}

A: It's failing on anything that's doing this:
JSONObject json = jsonEncorder.makeHttpRequest(Reg_URL, null ,parameter);

Log.d("Restrierung vorbreitet", json.toString());

What you need to do is provide ifnull conditions. So in case they are ever null you can decide to do nothing or give it a default value

A: Seems like your JSONObject json is null. It is happening when you call json.toString() in your log statement right under it.


text:
Q: get the object which property contains an array as the value using javascript I have an array containing some objects like this :
var lists = [{
  "id": 1,
  "status": 1,
  "inputs": [],
  "outputs": [
    ""
  ]
}, {
  "id": "",
  "status": 1,
  "inputs": [
    "test",
    ""
  ],
  "outputs": [
    ""
  ]
}, {
  "id": "",
  "status": 1,
  "inputs": [
    "",
    "test1"
  ],
  "outputs": [
    ""
  ]
}, {
  "id": "",
  "status": 1,
  "inputs": [
    "gfg",
    ""
  ],
  "outputs": [
    ""
  ]
}];

From this array I want to get all objects in which the inputs property contains at least one element.
How can I do this?

A: You almost had it:
function getObjects(lists) {
  return lists.filter(function (el) {
    return el.inputs.length;
  });
}

var arr = getObjects(lists);

DEMO

A: You just need to filter the array and return only items which has length of inputs array greater than zero . It can be achieved for example like this
var x=lists.filter(function(x){return x.inputs.length>=1});

Now x is the array that containts only objcets whose input array isnt empty.


text:
Q: retrieve only second row of the table in oracle? Can anyone help, how to retrieve exactly 2nd row from the table in oracle?

A: Since the rows in a table are inherently unordered, the concept of "first" and "second" requires that you specify some way of enforcing order (i.e. an ORDER BY clause).  The simplest way to do this is to use an analytic function
SELECT *
  FROM (SELECT a.*,
               row_number() OVER (ORDER BY some_column) rn
          FROM your_table a)
 WHERE rn = 2;

You could also use ROWNUM though that requires an additional level of nesting
SELECT *
  FROM (SELECT b.*, rownum rn
          FROM (SELECT *
                  FROM your_table a
                 ORDER BY some_column) b
         WHERE rownum <= 2)
 WHERE rn > 1

A: Thanks for your answers,now i found the solution for this,
      select * from
        (select rownum rn,column1,column2,...,columnn from tablename)
      where
         rn=2

Now you can check this and post your valuable comments.


text:
Q: Hold dynamically created divs on page refresh I am making a chat application where a user chats with multiple user. I have created multiple chat windows dynamically. i.e when a user clicks on online user a new chat window opens but I am having a problem, on page refresh the dynamically created divs are gone which i dont. I want them to be there. What should i do. Here is my jquery code.
$(document).ready(function(){

        $(".shout_msg").click(function(){

            var id = $(this).attr('id');
            var name = $(this).text();
            //var myarray = [];
            var sender = "<?php echo $user_check?>";
            var receiver = name;

            var detect = detectClick(id);   //if a online user is clicked multiple times only chat window should be opened

            if(!detect){
                $('#chatboxcontainer').append("

");
                $("#d-"+id).append("
'"+name+"'
");
                $("#h-"+id).append("

");

                $("#d-"+id).append("

");
                $("#t-"+id).append("
Clear Conversation
");
                $("#h2-"+id).append("

");
                $("#t-"+id).append("

");
                $("#t-"+id).append("

");
                $("#u-"+id).append('<input name = "shout_message" id = "s-'+id+'" type = "text" placeholder = "Type Message Hit Enter" />');

                //alert(id);

                $.ajax({

                            url: "loadmessage.php",
                            type: "POST",
                            data:{
                                'sender': sender,
                                'receiver': receiver,
                            },

                            success: function(response){
                                var result = JSON.parse(response);
                                console.log("Result is " +result);
                                console.log()

                                for(var i in result){
                                    $("#m-"+id).append('
' +result[i]+ '
');
                                    $("#m-"+id).scrollTop($("#m-"+id)[0].scrollHeight);
                                }
                            }
                        });

                }
                else{
                    $("#s-"+id).focus();
                }

            $("#s-"+id).keypress(function(evt) {
                if(evt.which == 13) {

                    var msg = $("#s-"+id).val();
                    //msg = msg.replace(":)","");

                    var dt = new Date();
                    var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();

                    $("#m-"+id).append('
'+sender+':'+msg+''+time+'
');

                    $.ajax({

                        url: "insertdatanew.php",
                        type: "POST",
                        data:{
                            'sender': sender,
                            'receiver': receiver,
                            'msg': msg,
                            'time': time
                        },

                        success: function(result){
                            if(result == 'Y')
                            alert("Successful insertion");
                        }
                    });

                    $("#m-"+id).scrollTop($("#m-"+id)[0].scrollHeight);
                    //count++;
                    $("#s-"+id).val("");

                }

            });

        });

    });

Here is html code

A: If you're using PHP to build the pages, make a session for each user, and save the user data somewhere so that when they create new windows, the PHP automatically fills out whatever extra divs should be there.


text:
Q: Create shortcut to submit form I work entering data online to a form and would like to assign a shortcut to each of two submit buttons.  I use Mac and Firefox.  Is there a way to do that in Scriptish, Applescript, or something other?
This is the source for one of them:

<<
Thanks

A: Try using jQuery Hotkeys
jQuery Hotkeys lets you watch for keyboard events anywhere in your code supporting almost any key combination.
To bind Ctrl+c to a function (f), for example:
$(document).bind('keydown', 'ctrl+c', f);


text:
Q: How to find sequence of digits in pi? I saw this project on github https://github.com/philipl/pifs, where they are trying to compress files in the pi number after the decimal. I guess this makes sense because apparently every finite sequence of digits exist in the never ending decimal numbers of pi. But I am trying to understand 1 step of their process.
So firstly from what I understand, if you want to compress a file, that is really represented in a sequence of numbers like say 471947...2846 (somehow gotten from base 16). Then, they assume that sequence is somewhere in pi.
They somehow then look up where the sequence starts in pi. This is the step I don't understand how they do. But they use a formula called Bailey–Borwein–Plouffe formula to do it.
So the compression is really two numbers $<A,B>$, where A is the index of the start number of pi, and B is the length needed.
To uncompress, its just a for loop, loop through every index from A, and repeat B times, and use that formula, to get the pi digit value, then convert it back to binary, and you have the original file again.
But it's that first step to find that initial start index using the formula I don't understand how that's done. Surely they don't brute force and try every combination in a linear fashion.
Does anyone know?
Thanks

A: The Bailey-Borwein-Plouffle formula does not allow you to find a desired sequence of digits in $\pi$.  As the Wikipedia page says, it allows you to find the hex digits starting as a desired place without calculating the preceding ones.  So if you want the digits of $\pi$ starting at the billionth, this is your friend. This would be used in the decryption step.
It is not proven that every digit sequence appears in $\pi$, but it is likely.  I am not aware of any way besides brute force to find were a given sequence occurs.  The problem with the idea is that the index for your file is likely to be as long as the file.  Yes, instead of storing your file you store the index, but it is just as large and harder to use.  Suppose you have a file that is $1000$ hex digits long. There are $16^{1000}$ sequences of $1000$ hex digits, so you would expect your string to occur somewhere around position $16^{1000}$, which takes $1000$ hex digits to store.  At this page you can search the first $200,000,000$ decimal digits of $\pi$ for a desired string. If you look for $12345678$, it reports that it occurs at position $186557266$, which is $9$ digits instead of $8$

A: The project you've found is a (deliberate!) joke.
It is true that $\pi$ is suspected to be normal in all bases, which would imply that every finite sequence of hex digits appears somewhere (indeed, many times) in the hexadecimal expansion of $\pi$.
But this cannot be used for compression -- the trouble is that the number $A$ that tells you where to find your file in $\pi$ will -- in the vast majority of cases -- be so large that storing $A$ takes up even more space than it would take to store the original file.
The BBP formula is not particularly suited for finding a particular sequence in $\pi$, except by trial and error, or by starting somewhere in $\pi$ and keep producing digits until you randomly come across the sequence you're looking for. So at first, the goal of the project would be completely impossible -- just locating a ten-byte file would take lifetimes. (That is, some multiple of the lifetime of the universe).
The kicker is in this part of the description:

Now, we all know that it can take a while to find a long sequence of digits in $\pi$ so for practical reasons, we should break the files up into smaller chunks that can be more readily found.
In this implementation, to maximise performance, we consider each individual byte of the file separately, and look it up in $\pi$.

So it doesn't actually "compress" anything -- it just stores, for each byte in the file, a position in $\pi$ where that particular byte can be found. (And finding such short a segment is certainly doable by brute force). But storing such a position takes more than a byte. So all in all it's just a simple substitution code, with a particularly inefficient implementation.
(And then there's some further joking around, claiming that the indices don't count as space used because they're "metadata".)

A:
They somehow then look up where the sequence starts in pi. This is the
  step I don't understand how they do. But they use a formula called
  [Bailey–Borwein–Plouffe][1] formula to do it.

Yes, that is a fantastic discovery, it allows to calculate the $k$-th digit behind the period without needing to know the prior digits.
This would benefit the decoding process.
That is the grain of truth behind this project.
However

They said 100% compression was impossible? You're looking at it!

and

So I've looked up my bytes in π, but how do I remember where they are?
Well, you've obviously got to write them down somewhere; you could use
  a piece of paper, but remember all that storage space we saved by
  moving our data into π? Why don't we store our file locations there!?!
  Even better, the location of our files in π is metadata and as we all
  know metadata is becoming more and more important in everything we do.
  Doesn't it feel great to have generated so much metadata? Why waste
  time with old fashioned data when you can just deal with metadata, and
  lots of it!

which is obviously a hoax.
Here it is likely that the index or the combined index and length result in a very large integer, probably much larger than your original file. Not a desirable feature for a compression scheme.


text:
Q: Bitmap.compress doesn't decrease the Byte count I need to compress an image to send it to my server. I am trying to do it this way:
private Bitmap compressImage(Bitmap bitmapImg){
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bitmapImg.compress(Bitmap.CompressFormat.JPEG, 50, out);
    Bitmap compressed = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

    return compressed;
}

But when I compare the Byte count of the original Bitmap object and the compressed one, I get the same number:
Log.e("UNCOMPRESSED", Integer.toString(mBitmapImg.getByteCount()));
E/UNCOMPRESSED: 23970816
Log.e("COMPRESSED", Integer.toString(compressedBitmapImg.getByteCount()));
E/COMPRESSED: 23970816

How can I fix this to have a smaller file?

A:
But when I compare the Byte count of the original Bitmap object and the compressed one, I get the same number:

The size of a Bitmap in memory is based only on its resolution (width and height in pixels) and bit depth (the number of bytes per pixel, for controlling how many colors can be used per pixel).

How can I fix this to have a smaller file?

You do not have a file. You have a Bitmap object in memory. An image file is usually stored in a compressed form. In particular, this is true for JPEG, PNG, WebP, and GIF, the four major image formats used in Android. So, for example, out.toByteArray() will be smaller than 23,970,816 bytes.
Moreover, you are not sending a Bitmap to the server. You are sending an image to the server. You need to read the documentation for the server, or talk to the server developers, to determine what image format(s) they support and how to send the image to the server (ideally, something efficient like an HTTP PUT).
If you want to reduce the in-memory size of the Bitmap, scale it to a lower-resolution image (e.g., via createScaledBitmap()).

A: You can change your bitmap format to RGB_565 from ARGB_8888. That'll reduce your bitmap's memory footprint to half, but, would lead to loss of quality as well. Unfortunately, that's the most you can do with Bitmap.
Having said that, the compression method that you're using should work fine for most situations. It's also the advocated method for a number of platforms. An example for Firebase is this.


text:
Q: Writing a function to call other functions without calling on the user prompts I'm trying to write a function that calls others function to produce a final answer. However, if I try to call halfNumber and squarenumber functions, I'm also going to be calling the individual prompts from those functions, and I don't want that to happen. Is there a way I can restructure my code so, I can be able to call crazyFunction without calling the prompts from the other functions?
Javascript:
var el1 = document.getElementById('squarenum');
el1.onclick = squarenumber;

var el2 = document.getElementById('halfnum');
el2.onclick = halfNumber;

function squarenumber(n){

    n = prompt("Enter a number to be squared");
    var result = n * n;

    var txt = document.getElementById('square_answer');
    txt.innerHTML = "The result of squaring the number " + n + " is " + result;
    return result;
}

function halfNumber(num){

    num = prompt("Enter a number to be halved");
    var result = num/2;
    var txt = document.getElementById('halved_answer');
    txt.innerHTML = "Half of " + num + " is " + result;
    return result;

}

function crazyFunction(num){
    result1 = squarenumber(num);
    result2 = halfNumber(result1);

    return result2;
}

HTML

squarenumber

The square is...

halfNumber

Half of the number is...

crazyfunction

This function is a surprise...

A: There are a few ways to solve your issue. Firstly, try understand why you're creating these functions and understand the requirements.
The expected output is that when squarenumber or halfNumber are called individually, you want a prompt to show, otherwise if they are called from within crazyFunction, the desired output is to not show a prompt.
So, we can see that the fluctuation in control flow lies at the moment of the function being called. Therefore, it would make the most sense for you to come up with a solution to this problem based on the passed in arguments to the sub functions of squarenumber and halfNumber.
Basic Solution
function crazyFunction(num) {
    boolean shouldShowPrompt = false;
    let result1 = squarenumber(num, shouldShowPrompt);
    let result2 = halfNumber(result1, shouldShowPrompt);

    return result2;
}

And then the halfNumber example:
function halfNumber(num, shouldShowPrompt ) {

    if (shouldShowPrompt) {
        num = prompt("Enter a number to be halved");
    }

    var result = num / 2;
    var txt = document.getElementById('halved_answer');
    txt.innerHTML = "Half of " + num + " is " + result;
    return result;

}

I hope this helps.


text:
Q: Is it possible to add kerning to a TextField in SwiftUI? To match a Styleguide I have to add kerning to a textfield, both placeholder and value itself.
With UIKit I was able to do so with:
    class MyTextField: UITextField {
    override func awakeFromNib() {
        super.awakeFromNib()

        // ...

        self.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [
            //...
            NSAttributedString.Key.kern: 0.3
        ])

        self.attributedText = NSAttributedString(string: "", attributes: [
            // ...
            NSAttributedString.Key.kern: 0.3
        ])
    }
}

In SwiftUI, I could figure out that I could apply a kerning effect to a Text element like so:
    Text("My label with kerning")
       .kerning(0.7)

Unfortunately, I could not find a way to apply a kerning style to neither a TextField's value nor placeholder. Any ideas on this one? Thanks in advance

A: There is a simple tutorial on HackingwithSwift that shows how to implement a UITextView. It can easily be adapted for UITextField.
Here is a quick example showing how to use UIViewRepresentable for you UITextField. Setting the kerning on both the text and the placeholder.
struct ContentView: View {

    @State var text = ""

    var body: some View {
        MyTextField(text: $text, placeholder: "Placeholder")
    }

}

struct MyTextField: UIViewRepresentable {
    @Binding var text: String
    var placeholder: String

    func makeUIView(context: Context) -> UITextField {
        return UITextField()
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.attributedPlaceholder = NSAttributedString(string: self.placeholder, attributes: [
            NSAttributedString.Key.kern: 0.3
        ])
        uiView.attributedText = NSAttributedString(string: self.text, attributes: [
            NSAttributedString.Key.kern: 0.3
        ])
    }
}

Update
The above doesn't work for setting the kerning on the attributedText. Borrowing from the fantastic work done by Costantino Pistagna in his medium article we need to do a little more work.
Firstly we need to create a wrapped version of the UITextField that allows us access to the delegate methods.
class WrappableTextField: UITextField, UITextFieldDelegate {
    var textFieldChangedHandler: ((String)->Void)?
    var onCommitHandler: (()->Void)?

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if let nextField = textField.superview?.superview?.viewWithTag(textField.tag + 1) as? UITextField {
            nextField.becomeFirstResponder()
        } else {
            textField.resignFirstResponder()
        }
        return false
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let currentValue = textField.text as NSString? {
            let proposedValue = currentValue.replacingCharacters(in: range, with: string)
            print(proposedValue)
            self.attributedText = NSAttributedString(string: currentValue as String, attributes: [
                NSAttributedString.Key.kern: 10
            ])
            textFieldChangedHandler?(proposedValue as String)
        }
        return true
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        onCommitHandler?()
    }
}

As the shouldChangeCharactersIn delegate method will get called every time the text changes, we should use that to update the attributedText value. I tried using first the proposedVale but it would double up the characters, it works as expected if we use the currentValue
Now we can use the WrappedTextField in the UIViewRepresentable.
struct SATextField: UIViewRepresentable {
    private let tmpView = WrappableTextField()

    //var exposed to SwiftUI object init
    var tag:Int = 0
    var placeholder:String?
    var changeHandler:((String)->Void)?
    var onCommitHandler:(()->Void)?

    func makeUIView(context: UIViewRepresentableContext<SATextField>) -> WrappableTextField {
        tmpView.tag = tag
        tmpView.delegate = tmpView
        tmpView.placeholder = placeholder
        tmpView.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [
            NSAttributedString.Key.kern: 10
        ])
        tmpView.onCommitHandler = onCommitHandler
        tmpView.textFieldChangedHandler = changeHandler
        return tmpView
    }

    func updateUIView(_ uiView: WrappableTextField, context: UIViewRepresentableContext<SATextField>) {
        uiView.setContentHuggingPriority(.defaultHigh, for: .vertical)
        uiView.setContentHuggingPriority(.defaultLow, for: .horizontal)
    }
}

We set the attributed text for the placeholder in the makeUIView. The placeholder text is not being updated so we don't need to worry about changing that.
And here is how we use it:
struct ContentView: View {

    @State var text = ""

    var body: some View {
        SATextField(tag: 0, placeholder: "Placeholder", changeHandler: { (newText) in
            self.text = newText
        }) {
            // do something when the editing of this textfield ends
        }
    }
}