text:
Q: Different background for section page in Beamer On this picture you can see a titlepage, a section page and a content page done in Powerpoint:

How to modify this code so that the section page has the background shown on the image? I can do the text positioning by myself later on.
\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{tikz, datetime, textpos}
\yyyymmdddate \renewcommand{\dateseparator}{.}

\definecolor{MedianBrown}{RGB}{119,95,85}
\definecolor{MedianLightBrown}{RGB}{235,221,195}
\definecolor{MedianLightBlue}{RGB}{148,182,210}
\definecolor{MedianOrange}{RGB}{221,128,71}
\setbeamercolor*{title page header}{fg=white}
\setbeamercolor*{title}{fg=MedianLightBrown}
\setbeamercolor*{author}{fg=white}
\setbeamercolor*{date}{fg=white}
\setbeamercolor*{item}{fg=MedianOrange}
\setbeamercolor*{frametitle}{fg=MedianBrown}

\setbeamertemplate{navigation symbols}{}
\setbeamertemplate{blocks}[rounded][shadow=true]
\setbeamertemplate{background}{
  \begin{tikzpicture}
  \useasboundingbox (0,0) rectangle(\the\paperwidth,\the\paperheight);
  \ifnum\thepage>1\relax% Not the title page
        \fill[color=MedianOrange] (0,8) rectangle(0.8,8.3);
        \fill[color=MedianLightBlue] (0.9,8) rectangle(\the\paperwidth, 8.3);
  \else% Title page
      \fill[color=MedianBrown] (0,1.5) rectangle (\the\paperwidth,\the\paperheight);
      \fill[color=MedianOrange] (0,0.1) rectangle(3.45,1.4);
      \fill[color=MedianLightBlue] (3.55,0.1) rectangle(\the\paperwidth,1.4);
  \fi
  \end{tikzpicture}
}

\setbeamertemplate{title page}
{
    \begin{textblock*}{12cm}(3cm,2.8cm)
    \begin{beamercolorbox}[wd=8cm]{title page header}
      \usebeamerfont{title}\usebeamercolor{title}\inserttitle%
    \end{beamercolorbox}%
    \end{textblock*}
    \begin{textblock*}{12cm}(-0.5cm,4.9cm)
        \begin{beamercolorbox}{date}
          \usebeamerfont{date}\insertdate%
        \end{beamercolorbox}
    \end{textblock*}
    \begin{textblock*}{9cm}(3cm,4.9cm)
        \begin{beamercolorbox}{author}
          \usebeamerfont{author}\insertauthor%
        \end{beamercolorbox}
    \end{textblock*}
}

\setbeamertemplate{frametitle}
{
    \vskip0.3cm
    \begin{beamercolorbox}{frametitle}
        \insertframetitle
    \end{beamercolorbox}
}
\setbeamertemplate{items}[square]
\setbeamertemplate{sections/subsections in toc}[square]

\author{Author Name}
\title{Quite A Long Title For A Simple Beamer Presentation}
\date{\today}

\begin{document}
\frame{\maketitle}
\section{Introduction}
\frame{\sectionpage}
\begin{frame}{My presentation is about\ldots}
\begin{itemize}
\item Some stuff
\item And some other stuff
\end{itemize}
\end{frame}
\end{document}

A: Another option following the same pattern as the MWE which uses conditionals to define the background once and forall.
I do not like this approach as it is not very modular but since @dcmst asked here's a solution with conditionals.
First let's introduce a new conditional for section pages and set it to false
\newif\ifinsectionframe
\insectionframefalse

Now we can change the background template as follows
\setbeamertemplate{background}{
  \begin{tikzpicture}
  \useasboundingbox (0,0) rectangle(\the\paperwidth,\the\paperheight);
  \ifnum\thepage>1\relax% Not the title page
    \ifinsectionframe%
        \node {Some background}; %% INSERT YOUR GRAPHICS HERE
    \else%
        \fill[color=MedianOrange] (0,8) rectangle(0.8,8.3);
        \fill[color=MedianLightBlue] (0.9,8) rectangle(\the\paperwidth, 8.3);
    \fi%
  \else% Title page
      \fill[color=MedianBrown] (0,1.5) rectangle (\the\paperwidth,\the\paperheight);
      \fill[color=MedianOrange] (0,0.1) rectangle(3.45,1.4);
      \fill[color=MedianLightBlue] (3.55,0.1) rectangle(\the\paperwidth,1.4);
  \fi
  \end{tikzpicture}
}

Then we can create a \sectionframe macro that sets the corresponding flag before creating a frame with the section page:
\newcommand{\sectionframe}{
  \insectionframetrue
  \frame{\sectionpage}
  \insectionframefalse
}

Then if you use \sectionframe instead of \frame{\sectionpage} you have the desired effect.
A note on the conditional to detect the title page: I would recommend creating a new if \ifintitleframe instead of checking the page number; apart from being more semantically sound it is also more flexible because you can now have title frames on an arbitrary page (even more than one) instead than forcing it to be on the first page.

A: The problem is that the section page template gets "called" within a frame but the background template can only be changed before starting the frame.
Also, setting flags patching \sectionpage probably wont work because it would set them after the background is typeset.
So, the simplest solution is to define a macro to create the section frame (instead of page) so you can inject the background-changing code before starting the frame.
First let's introduce few macros to change the background:
\newcommand{\setslidebg}{
    \setbeamertemplate{background}{
      \begin{tikzpicture}
      \useasboundingbox (0,0) rectangle(\the\paperwidth,\the\paperheight);
        \fill[color=MedianOrange] (0,8) rectangle(0.8,8.3);
        \fill[color=MedianLightBlue] (0.9,8) rectangle(\the\paperwidth, 8.3);
      \end{tikzpicture}
    }
}
\newcommand{\setsecbg}{
\setbeamertemplate{background}{
  \begin{tikzpicture}
  \useasboundingbox (0,0) rectangle(\the\paperwidth,\the\paperheight);
      \node {Something else};
  \end{tikzpicture}
}
}
\newcommand{\settitlebg}{
     \setbeamertemplate{background}{
      \begin{tikzpicture}
      \useasboundingbox (0,0) rectangle(\the\paperwidth,\the\paperheight);
          \fill[color=MedianBrown] (0,1.5) rectangle (\the\paperwidth,\the\paperheight);
          \fill[color=MedianOrange] (0,0.1) rectangle(3.45,1.4);
          \fill[color=MedianLightBlue] (3.55,0.1) rectangle(\the\paperwidth,1.4);
      \end{tikzpicture}
    }
}

\setslidebg

where you can replace the tikzcode in \setsecbg to produce the desired graphics.
Then you can simply create the macros \titleframe and \sectionframe as follows:
\newcommand{\titleframe}{
  \settitlebg
  \frame{\maketitle}
  \setslidebg
}

\newcommand{\sectionframe}{
  \setsecbg
  \frame{\sectionpage}
  \setslidebg
}

so now you can just write \titleframe instead of \frame{\maketitle} and have your backgrounds set accordingly.

A: I'll add my answer too, the approach is the same of Bordaigorl but with less code involved.
The idea is to create another \setbeamertemplate{background} and embed it into a custom command to be used instead of \frame{\sectionpage}
The custom command will redefine the background and then the section page template. Just as an example I used a tikzpicture to reposition the section head.
This is the custom command:
\newcommand{\mysectionpage}{
    \begingroup
    \setbeamertemplate{background}{
        \begin{tikzpicture}                                         %edit this tikzpicture to customize the size and colors of the background rectangles
            \useasboundingbox (0,0) rectangle(\the\paperwidth,\the\paperheight);
            \fill[color=MedianOrange] (0,7) rectangle(0.8,8);
            \fill[color=MedianLightBlue] (0.9,7) rectangle(\the\paperwidth, 8);
        \end{tikzpicture}
    }
    \setbeamercolor{section page}{fg=white}
    \setbeamertemplate{section page}{
    \begin{tikzpicture}                                             %edit this tikzpicture to customize the appearance of the section heading
        \node[overlay] at (1,2) {\insertsectionhead};
    \end{tikzpicture}
    }
    \frame{\sectionpage}
    \endgroup
}

The rest of your preamble code stays untouched. The body of the document will look like this:
\begin{document}
\frame{\maketitle}
\section{Introduction}
\mysectionpage                                 %new code
\begin{frame}{My presentation is about\ldots}
\begin{itemize}
\item Some stuff
\item And some other stuff
\end{itemize}
\end{frame}
\end{document}

The result is:

A: I came across the same problem in designing my beamer themes. At last I found a solution: use adjustbox package to make your title page and section page pictures fill the whole page.
Inside your title/section page templates, you could use \node command to add title, author, date and section names. Therefore textpos package is unnecessary.
Also, you could use \AtBeginSection command to add section pages before each \section.
At last, \the commands before \paperwidth and \paperheight inside tikz coordinates may be ommited.
% -*- coding: utf-8 -*-
\documentclass{beamer}
\usepackage{tikz,datetime,adjustbox}
\yyyymmdddate \renewcommand{\dateseparator}{.}

\definecolor{MedianBrown}{RGB}{119,95,85}
\definecolor{MedianLightBrown}{RGB}{235,221,195}
\definecolor{MedianLightBlue}{RGB}{148,182,210}
\definecolor{MedianOrange}{RGB}{221,128,71}
\setbeamercolor*{title page header}{fg=white}
\setbeamercolor*{title}{fg=MedianLightBrown}
\setbeamercolor*{author}{fg=white}
\setbeamercolor*{date}{fg=white}
\setbeamercolor*{item}{fg=MedianOrange}
\setbeamercolor*{frametitle}{fg=MedianBrown}
\setbeamercolor*{section page}{fg=white}

\setbeamertemplate{navigation symbols}{}
\setbeamertemplate{blocks}[rounded][shadow=true]

\setbeamertemplate{background}{
  \begin{tikzpicture}
  \useasboundingbox (0,0) rectangle(\paperwidth,\paperheight);
  \fill[color=MedianOrange] (0,8) rectangle(0.8,8.3);
  \fill[color=MedianLightBlue] (0.9,8) rectangle(\paperwidth, 8.3);
  \end{tikzpicture}
}

\setbeamertemplate{title page}{%
  \nointerlineskip
  \begin{adjustbox}{width=\paperwidth,center}
  \begin{tikzpicture}
    \useasboundingbox (0,0) rectangle(\paperwidth,\paperheight);
    \fill[color=MedianBrown] (0,1.5) rectangle (\paperwidth,\paperheight);
    \fill[color=MedianOrange] (0,0.1) rectangle(3.45,1.4);
    \fill[color=MedianLightBlue] (3.55,0.1) rectangle(\paperwidth,1.4);
    \node[text width=0.8\paperwidth,right] at (4,3) {
      \begin{beamercolorbox}[wd=8cm]{title page header}
      \usebeamerfont{title}\usebeamercolor{title}\inserttitle%
      \end{beamercolorbox}%
    };
    \node[text width=0.2\paperwidth,right] at (1,0.7) {
      \begin{beamercolorbox}{date}
        \usebeamerfont{date}\insertdate%
      \end{beamercolorbox}
    };
    \node[text width=0.8\paperwidth,right] at (4,0.7) {
      \begin{beamercolorbox}{author}
        \usebeamerfont{author}\insertauthor%
      \end{beamercolorbox}
    };
  \end{tikzpicture}
  \end{adjustbox}
}

\setbeamertemplate{section page}{%
  \nointerlineskip
  \begin{adjustbox}{width=\paperwidth,center}
  \begin{tikzpicture}
    \useasboundingbox (0,0) rectangle (\paperwidth,\paperheight);
    \fill[color=white] (0,0) rectangle (\paperwidth,\paperheight);
    \fill[color=MedianOrange] (0,6) rectangle (1.5, 7);
    \fill[color=MedianLightBlue] (1.6, 6) rectangle (\paperwidth, 7);
    \node[text width=0.8\paperwidth,right] at (1.8,6.5) {
      \begin{beamercolorbox}{section page}
        \insertsectionhead
      \end{beamercolorbox}
    };
  \end{tikzpicture}
  \end{adjustbox}
}

\setbeamertemplate{frametitle}
{
    \vskip0.3cm
    \begin{beamercolorbox}{frametitle}
        \insertframetitle
    \end{beamercolorbox}
}
\setbeamertemplate{items}[square]
\setbeamertemplate{sections/subsections in toc}[square]

\author{Author Name}
\title{Quite A Long Title For A Simple Beamer Presentation}
\date{\today}

\AtBeginSection{\frame{\sectionpage}}

\begin{document}

\frame{\titlepage}

\section{Introduction}

\begin{frame}{My presentation is about\ldots}
\begin{itemize}
\item Some stuff
\item And some other stuff
\end{itemize}
\end{frame}
\end{document}


text:
Q: gulp error process teminated with code 1 Hello I am trying to run jasmine unit tests using karma in VS. I have a var simple gulp task that should just work. I am getting the error Process terminated with code 1..
gulp.task('test', function (done) {
    new Server({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done()).start();
});

this gets the error above.
when I add funtion(){done();}
I get the below error:

Chrome 67.0.3396 (Windows 10.0.0): Executed 0 of 0 SUCCESS (0 secs / 0
  secs) Chrome 67.0.3396 (Windows 10.0.0): Executed 0 of 0 ERROR (0.008
  secs / 0 secs) [10:11:37] Finished 'test' after 2.27 s

and when i do just done I get the following error.

at formatError
  (C:\Users\James.Tays\Desktop\UnitTestingAngular\Tests\node_modules\gulp\bin\gulp.js:169:10)
      at Gulp. (C:\Users\James.Tays\Desktop\UnitTestingAngular\Tests\node_modules\gulp\bin\gulp.js:195:15)
      at emitOne (events.js:77:13)
      at Gulp.emit (events.js:169:7)
      at Gulp.Orchestrator._emitTaskDone (C:\Users\James.Tays\Desktop\UnitTestingAngular\Tests\node_modules\orchestrator\index.js:264:8)
      at C:\Users\James.Tays\Desktop\UnitTestingAngular\Tests\node_modules\orchestrator\index.js:275:23
      at finish (C:\Users\James.Tays\Desktop\UnitTestingAngular\Tests\node_modules\orchestrator\lib\runTask.js:21:8)
      at cb (C:\Users\James.Tays\Desktop\UnitTestingAngular\Tests\node_modules\orchestrator\lib\runTask.js:29:3)
      at removeAllListeners (C:\Users\James.Tays\Desktop\UnitTestingAngular\Tests\node_modules\karma\lib\server.js:380:7)
      at Server. (C:\Users\James.Tays\Desktop\UnitTestingAngular\Tests\node_modules\karma\lib\server.js:391:9)
      at Server.g (events.js:260:16)
      at emitNone (events.js:72:20)
      at Server.emit (events.js:166:7)
      at emitCloseNT (net.js:1523:8)
      at nextTickCallbackWith1Arg (node.js:463:9)
      at process._tickCallback (node.js:385:17)

Can someone please tell me why I am getting different errors, and how can I can debug this?

A: I have Figured out the error, this came from the karma.conf.js basePath was wrong.
the documention shows basePath: '../...', so i copied that exactly and saw that it should be basePath:'../Path_TO_TEST_PROJECT_HERE'.
I thought that may help others.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replace specific section of text in a file, with text from url in bash? I am trying to replace some text in a file with text from a url link.  I have gotten close, but the result has unintended complications.
Here is the text of the file I need to do this with (wp-config.php):
<?php
/**
 * The base configuration for WordPress
 *
 * The wp-config.php creation script uses this file during the installation.
 * You don't have to use the web site, you can copy this file to "wp-config.php"
 * and fill in the values.
 *
 * This file contains the following configurations:
 *
 * * Database settings
 * * Secret keys
 * * Database table prefix
 * * ABSPATH
 *
 * @link https://wordpress.org/support/article/editing-wp-config-php/
 *
 * @package WordPress
 */

// ** Database settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', 'database_name_here' );

/** Database username */
define( 'DB_USER', 'username_here' );

/** Database password */
define( 'DB_PASSWORD', 'password_here' );

/** Database hostname */
define( 'DB_HOST', 'localhost' );

/** Database charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );

/** The database collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );

/**#@+
 * Authentication unique keys and salts.
 *
 * Change these to different unique phrases! You can generate these using
 * the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}.
 *
 * You can change these at any point in time to invalidate all existing cookies.
 * This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define( 'AUTH_KEY',         'put your unique phrase here' );
define( 'SECURE_AUTH_KEY',  'put your unique phrase here' );
define( 'LOGGED_IN_KEY',    'put your unique phrase here' );
define( 'NONCE_KEY',        'put your unique phrase here' );
define( 'AUTH_SALT',        'put your unique phrase here' );
define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
define( 'LOGGED_IN_SALT',   'put your unique phrase here' );
define( 'NONCE_SALT',       'put your unique phrase here' );

/**#@-*/

/**
 * WordPress database table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix = 'wp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the documentation.
 *
 * @link https://wordpress.org/support/article/debugging-in-wordpress/
 */
define( 'WP_DEBUG', false );

/* Add any custom values between this line and the "stop editing" line. */

/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
    define( 'ABSPATH', __DIR__ . '/' );
}

/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';

I need to replace the section of salts with the ones in this link:
https://api.wordpress.org/secret-key/1.1/salt/

I believe there are escape characters in the salts complicating things for me as I am new to bash. Here is the closest I have gotten but this took some help:
cp wp-config.php wp-config.bak
curl https://api.wordpress.org/secret-key/1.1/salt/ | awk -F "'" 'NR==FNR {a[$2]=$4;next} {$4=a[$2]}1' OFS="'" - wp-config.php > wp-config.tmp
mv wp-config.tmp wp-config.php
cat wp-config.php

Once again, this creates new issues, while it does replace the salts section it also makes the file unreadable.  Hoping someone can help me tweak this, or show me a better way to accomplish this.

A: Since you trust the contents of the URL, you could replace (once) the defines lines in wp-config.php with:
require '/path/to/salts';

and then when you need new salts, just do something like:
url='https://api.wordpress.org/secret-key/1.1/salt/'

if salts=$(curl -fs "$url"); then
    printf '<?php\n%s\n' "$salts" > /path/to/salts
fi

You'll need to ensure that your webserver process has permission to read the salts file.
This is probably what is causing wp-config.php to become unreadable when you do your awk/mv:
if the user creating the temporary file creates it as rw------- for example (or as rw-r---- but the webservice process does not run in the same group), then the webserver process will be unable to read the file.


text:
Q: Memory allocate in c++ I have a project in which I have to allocate 1024 bytes when my program starts. In C++ program.
void* available = new char*[1024];

I write this and I think it is okay.
Now my problem starts, I should make a function that receives size_t size (number of bytes) which I should allocate. My allocate should return a void* pointer to the first bytes of this available memory. So my question is how to allocate void* pointer with size and to get memory from my available.
I'm a student and I'm not a professional in C++.
Also sorry for my bad explanation.

A: It looks like you're trying to make a memory pool. Even though that's a big topic let's check what's the minimal effort you can pour to create something like this.
There are some basic elements to a pool that one needs to grasp. Firstly the memory itself, i.e. where do you draw memory from. In your case you already decided that you're going to dynamically allocate a fixed amount of memory. To do it properly the the code should be:
char *poolMemory = new char[1024];

I didn't choose void* pool here because delete[] pool is undefined when pool is a void pointer. You could go with malloc/free but I'll keep it C++. Secondly I didn't allocate an array of pointers as your code shows because that allocates 1024 * sizeof(char*) bytes of memory.
A second consideration is how to give back the memory you acquired for your pool. In your case you want to remember to delete it so best you put it in a class to do the RAII for you:
class Pool
{
  char *_memory;
  void *_pool;
  size_t _size;

public:
  Pool(size_t poolSize = 1024)
    : _memory(new char[poolSize])
    , _pool(_memory)
    , _size(poolSize)
  {
  }

  ~Pool() { delete[] _memory; } // Forgetting this will leak memory.
};

Now we come to the part you're asking about. You want to use memory inside that pool. Make a method in the Pool class called allocate that will give back n number of bytes. This method should know how many bytes are left in the pool (member _size) and essentially performs pointer arithmetic to let you know which location is free. There is catch unfortunately. You must provide the required alignment that the resulting memory should have. This is another big topic that judging from the question I don't think you intent to handle (so I'm defaulting alignment to 2^0=1 bytes).
#include <memory>

void* Pool::allocate(size_t nBytes, size_t alignment = 1)
{
    if (std::align(alignment, nBytes, _pool, _size))
    {
        void *result = _pool;
        // Bookkeeping
        _pool = (char*)_pool + nBytes; // Advance the pointer to available memory.
        _size -= nBytes;               // Update the available space.

        return result;
    }
    return nullptr;
}

I did this pointer arithmetic using std::align but I guess you could do it by hand. In a real world scenario you'd also want a deallocate function, that "opens up" spots inside the pool after they have been used. You'd also want some strategy for when the pool has run out of memory, a fallback allocation. Additionally the initially memory acquisition can be more efficient e.g. by using static memory where appropriate. There are many flavors and aspects to this, I hope the initial link I included gives you some motivation to research a bit on the topic.


text:
Q: copyright annotations in both XSD and XML According to Where to put copyright information in an XSD?, one way to put a copyright notice in an xsd is to insert something like
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsd:annotation>
  <xsd:appinfo>
    <copyright-notice>
      Copyright 2015 Example.com. All rights reserved.
    <copyright-notice>
    <license uri="http://www.apache.org/licenses/LICENSE-2.0"
             version="2.0">Apache License, Version 2.0</license>
    <!-- ... -->
  </xsd:appinfo>
</xsd:annotation>
<!-- ... -->
</xs:schema>

If I do that, it works indeed.
But now, I want to insert something alike in the corresponding XML:
<MyCase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="MyCaseDefinition.xsd">
<annotation>
  <appinfo>
    <copyright-notice>
      Copyright 2015 Example.com. All rights reserved.
    </copyright-notice>
    <license uri="http://www.apache.org/licenses/LICENSE-2.0"
             version="2.0">Apache License, Version 2.0</license>
  </appinfo>
</annotation>
<!-- ... -->
</MyCase>

However, if I do that, I get an error:

Invalid content starting with element 'annotation'

at the loading of the file.
It seems the 2 above are exclusive:

*

*If I put the annotation in the XSD, then I cannot put the equivalent in the XML.

*If I don't put anything in the XSD, then the annotation in the XML is OK.

How can I get the copyright notice in both files?

A: I think that you simply forgot  a slash to close your COPYRIGHT-NOTICE tag:
try to put please
</copyright-notice>

instead of the 2nd
<copyright-notice>

tag in your xsd file.
What do you think ?

A:
It seems the 2 above are exclusive:

*

*If I put the annotation in the XSD, then I cannot put the equivalent in the XML.

*If I don't put anything in the XSD, then the annotation in the XML is OK.

There is no such coupling:

*

*You can place any XML elements you or your tools would like into the XSD's xsd:annotation/xsd:appinfo element.

*If you wish to allow a different XML content model for any elements in your XML, you have to adjust the content model specified for such elements in your XSD.

How can I get the copyright notice in both files?

To allow copyright-notice as a child of MyCase, add it to the content model of MyCase in the XSD.  You can do so with or without the shown xsd:annotation/xsd:appinfo heritage.  (Probably do not want it as there's no need to follow the requirements of adding xsd:annotation/xsd:appinfo elements to an XSD when creating your XML.)


text:
Q: Express Router param validation The express 4x api docs claim that you can pass regex as a second argument to router.param in order validate params.

The method could now be used to effectively validate parameters (and
  optionally parse them to provide capture groups)

It then provides the following examples.
// validation rule for id: should be one or more digits
router.param('id', /^\d+$/);

router.get('/user/:id', function(req, res) {
  res.send('user ' + req.params.id);
});

// validation rule for range: should start with one more alphanumeric characters, followed by two dots, and end with one more alphanumeric characters
router.param('range', /^(\w+)\.\.(\w+)?$/);

router.get('/range/:range', function(req, res) {
  var range = req.params.range;
  res.send('from ' + range[1] + ' to ' + range[2]);
});

But, this doesn't actually seem to work. Taking a deeper dive, it doesn't look as if the express code actually supports what the docs claim. In fact, passing anything other than a function will get you a tidy invalid param() call exception.

Using

express 4.12.3
node 0.12.4
So my question is whether this functionality actually exists or if I'm doing something wrong. I'm trying to accomplish the same thing provided in the doc but am receiving the error mentioned above. Any guidance would be greatly appreciated :)

A: The answer can be found here.
Essentially the following snippet would need to be run prior to leveraging the router.param(fn) method as outlined above if you're using express <= 4.11.
express 4.11
router.param(function(name, fn) {
  if (fn instanceof RegExp) {
    return function(req, res, next, val) {
      var captures;
      if (captures = fn.exec(String(val))) {
        req.params[name] = captures;
        next();
      } else {
        next('route');
      }
    }
  }
});

express 4.12
If you're using express >= 4.12 you can accomplish the same without the need of router.param(fn) using the following. In fact, the pre 4.12 example above will pop a deprecation warning.
app.get('/user/:userId([0-9]+)', fn);

While this is stated in the doc, it isn't quite clear.Hope this helps.

A: I was facing the same issue and I got it resolved by converting my code

exports.customerValidator = () => {
    return [
        body("name").trim().toString(),
        body("email")
          .isEmail()
          .withMessage("Please enter a valid email id")
          .custom((value, { req }) => {
            return Customer.findOne({ email: value })
              .then((customer) => {
                if (customer) {
                  return Promise.reject("E-mail address is already exists!");
                }
              })
          })
          .normalizeEmail(),
        body("address").trim().toString(),
        body("city").trim().toString()
    ]
}

to this:

exports.customerValidator = () => {
    return [
      body('name').trim(),
      body("email")
        .isEmail()
        .normalizeEmail()
        .custom((value, { req }) => {
          return Customer.find({ email: value })
            .then((customer) => {
              if (customer) {
                return Promise.reject("E-mail address is already exists!");
              }
            })
        }),
      body("address").trim(),
      body("city").trim(),
    ];
  };


text:
Q: Stuck on loops c# I calculated distance between a unit and a building, I put the distance inside a struct[] and sorted the distance smallest to largest. The AI goes to the closest building each time and this works as it is. Now my question is I want to add a check and remove the last line of code thats hardcoded to index 0. I want the AI to go to the next index each time the current index runs out of resources. How would i go about doing this? The struct populates with sorted distances each time the AI selects the closest building to bring resources from.
Would it be an if statement inside the for loop? Or another for loop with an if statement? Or do you change the indexes in the struct if the building is exhausted of resources?
    Destination2 = GameObject.FindGameObjectsWithTag("Storehouses");        // storehouse distance should be based off  production

    Vector3 position = transform.position;
    for (int i = 0; i < Destination2.Length; i++) // put in 10 storehouses, find the closest distance to the colonist
    {
        Debug.Log("1");
        buildingInformation[i].buildingID2 = Destination2[i];      // stores game objects 0,1

        Vector3 direction = (Destination2[i].transform.position - position);
        float distance = direction.sqrMagnitude;

        buildingInformation[i].buildingDistance2 = distance;
        Array.Sort<BuildingInformation>(buildingInformation, (x, y) => x.buildingDistance2.CompareTo(y.buildingDistance2));// smallest to largest

    }
    Supplier = buildingInformation[0].buildingID2;

A: Some Linqy pseudocode on how I'd approach it:
destination = storehouses
              .OrderBy( storehouse.distance )
              .FirstOrDefault( storehouse.contains(item) )

Although you're probably better off doing a single-pass iteration:
SomeType destination
foreach storehouse in storehouses
    if ( storehouse.contains(item) )
        if ( destination is null || storehouse.distance < destination.distance )
            destination = storehouse


text:
Q: How to disassemble a shellcode into assembly instruction? Is there some tool to disassemble a raw hex into assembly instructions? for example: lets say we have \xeb\x1d that disassemble into jmp 0x1f according to this online disassembler. So is there some offline tool? I have tried ndisasm its not giving me the right output.
ndisam -b32 foo gives me:
OUTPUT:
00000000  5C                pop esp

00000001  7833              js 0x36

00000003  315C7865          xor [eax+edi*2+0x65],ebx

00000007  620A              bound ecx,[edx]

It should be jmp 0x1f.
I have also tried objdump like:
objdump -D -b binary -mi386 -M intel foo
OUTPUT:
00000000 <.data>:

   0:   5c                      pop    esp

   1:   78 33                   js     0x36

   3:   31 5c 78 65             xor    DWORD PTR [eax+edi*2+0x65],ebx

   7:   62 0a                   bound  ecx,QWORD PTR [edx]

SO can you tell me some tool that will disassemble raw hex codes into assembly language.
I have also tried gdb but I want something more flexible.

A: As the comments have suggested, your issue is that you have output the string \xeb\x1d as ASCII into the file you are trying to disassemble. You may have done something like:
echo '\xeb\x1d' >foo

You can do this but you will want to tell echo to interpret the escape character \. This can be done with the -e option.
You'll want it to not append a newline on the end using the -n option. This is documented in the ECHO manual page:

  -n     do not output the trailing newline
  -e     enable interpretation of backslash escapes

This may work:
echo -ne '\xeb\x1d' >foo

Using NDISASM to disassemble the bytes:
ndisasm -b32 foo

Should now produce:

00000000  EB1D              jmp short 0x1f

Without using an intermediate file (like foo) you can pipe ECHO output into NDISASM and disassemble it that way. This line would take a shell code string and output the disassembly as well:
echo -ne '\xeb\x1d' | ndisasm -b32 -

The - on the end is needed to tell NDISASM to disassemble input from standard input rather than an explicit file.
We have now revolutionized the IT industry! ;-)


text:
Q: Property info's GetAccessors method returning IsVirtual for non-virtual property I have this class:
public class Model : IModel
{
    public int Id {get; set;}
}

public interface IModel
{
    int Id {get; }
}

I get the property info as follows:
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
var property = properties[0];

var isVirtual = property.GetAccessors()[0].IsVirtual;

isVirtual is true. Why does happen even though the property is not explicitly marked as virtual?

A: You are probably checking IsVirtual against interface IModel. Hence, it is returning true. This is because:

The accessor of an interface property does not have a body. Thus, the purpose of the accessors is to indicate whether the property is read-write, read-only, or write-only.

Source: MSDN
Also, if look into IL Code, you would see
For Interface:
.method public hidebysig newslot specialname abstract virtual
    instance int32  get_Id() cil managed

For Class:
.method public hidebysig newslot specialname virtual final
            instance int32  get_Id() cil managed

Note the final in IL (or Sealed in C#), this prevents derived class overriding the interface method. If you explicitly mark the method as virtual, the compiler marks the method as virtual (and no final) allowing a derived class to override the interface method. Thus, Virtual in signature is way the run time provides polymorphic behavior and more like implementation details.
So, If you check IsVirtual against class Model, it would return false.


text:
Q: Add Css class depending on mouse position I'm trying to add a class to a set of divs depending on mouse position, the final outcome will be a wall of people looking at the cursor...
I've wrote something I believe should work and I can get to addClass but its very buggy and only seems to add the class once and not constantly check mouse position. Can anybody see where I'm going wrong?
this.setImageDirection = function(){
    if(mouseX >= this.imageLeft && mouseX <= this.imageRight && mouseY <= this.imageTop){
        $(this).removeClass();
        $(this).addClass("up");
    } else if(mouseX < this.imageLeft && mouseY < this.imageTop){
      $(this).removeClass();
       $("."+this.className+">.head-image").addClass("up-left");
    } else if(mouseX <= this.imageLeft && mouseY >= this.imageTop && mouseY <= this.imageBottom){
        $(this).removeClass();
       $(this).addClass("left");
    } else if(mouseX < this.imageLeft && mouseY > this.imageBottom){
        $(this).removeClass();
        $(this).addClass("down-left");
    } else if(mouseX >= this.imageLeft && mouseX <= this.imageRight && mouseY >= this.imageBottom){
        $(this).removeClass();
        $(this).addClass("down");
    } else if(mouseX > this.imageRight && mouseY > this.imageBottom){
        $(this).removeClass();
        $(this).addClass("down-right");
    } else if(mouseX >= this.imageRight && mouseY >= this.imageTop && mouseY <= this.imageBottom){
        $(this).removeClass();
        $(this).addClass("right");
    } else (mouseX > this.imageRight && mouseY < this.imageTop){
        $(this).removeClass();
        $(this).addClass("up-right");
    }
};

Working Demo
https://jsfiddle.net/cppsh7y9/

A: Your code is invalid. See this line:
} else (mouseX > this.imageRight && mouseY < this.imageTop){

It should be:
} else if(mouseX > this.imageRight && mouseY < this.imageTop){

A: You're trying to reference a jquery element with $(this), but this is not an element, it is an instance of the HeadImage 'class', so the jquery methods aren't going to work. You'll want to save a reference to the element when you instantiate it, and add/remove the css class from that.
for example, maybe something like this:
function HeadImage(className){
   this.element = $('.' + className);
   this.className = className;
   /* rest of the function ... */
}

and then in the setImageDirection method:
this.setImageDirection = function(){
    if(mouseX >= this.imageLeft && mouseX <= this.imageRight && mouseY <= this.imageTop){
        this.element.removeClass();
        this.element.addClass("up");
    }
    /* ... */
}


text:
Q: C pointer ,seg fault I have the following program going to segfault. I am unable to understand why. Kindly help me.
int main(){
    char *a="String One", *b="String Two";
    while(*a++=*b++);
return 0;
}

To analyse it, I removed the while loop and made it simpler. Still it gives segfault!
int main(){
    char *a="String One", *b="String Two";
    *a++=*b++;
return 0;
}

But this works. I mean no segfault!
int main(){
    char *a="String One", *b="String Two";
    *a++;
    *b++;
return 0;
}

Replying to Luchien:
I was actually trying to emulate strcpy. Something like this. Now that i know that string literal is read only, I could get this working. Thank you all.
main(){
char x[10];
char *xx = x;

char *y = "Hello";

char *t=x, *f=y;

while(*xx++ = *y++);

printf(" %s ...%s \n",t,f);
}

A: With
char *a="String One", *b="String Two";

your a points to readonly memory containing the given string. Modifying this is undefined behaviour.

A: Many operating systems store literal string values in a read-only memory section, which means that attempts to modify the memory lead to the OS telling the program: hey, you can't touch that! On unix systems the OS does this by sending the process the SEGV signal, which usually leads to process termination.
Since C programs run on bare metal embedded systems and on many different operating systems, some of which have this restriction, some of which don't, the C standard declares this undefined behaviour.

A: You're modifying a string literal, which is undefined behavior.
I also find it annoying that
char *a="String One"

is actually
const char *a="String One"

"StringOne" is stored in read-only memory, and can thus not be modified.

A: When you create a string constant by saying char *a="String One" 'a' is not an array, but a pointer which is initialized to point to a string constant. If you want to change the string that it points to, you can point it elsewhere, but trying to modify the contents in place results in undefined behavior.

A: In the third piece of code, *a++ will access the address pointed to by a, which holds the character 'S', so no segment fault.

A: while(*xx++ = *y++);

Is this really something you want? What do you wish to accomplish? This is actually undefined behavior, as you don't know what xx will be after this. Will you first increment xx, or will you first copy the value from y to xx, and then increment? See http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf 6.5.2

A: Those strings that a, b are stored in data section. That section is read-only area. So you couldn't modify the strings at data section. a and b is just a pointer to point strings at data section. x is stored in stack, so you can modify it.


text:
Q: What subject is more useful for statistics students I am deciding which of the following two subjects to take as one elective in the coming term.

*

*Complex Analysis

*Theory of Partial Differential Equations

Ideally I'd like to take both. However, I will have other things to do. Therefore, I want to take something that is direct relevant to statistics and probability. Any suggestion? Thank you!

A: If those are the choices, then Complex Analysis is probably the way to go.  PDEs are interesting and useful, but not too much in statistics.  Complex Analysis, on the other hand does pop up from time to time.  Its most common application is in distribution theory, where the characteristic function is defined as: $$ \phi_X (t) = E\{e^{itX} \}.$$
There is an important theorem in distribution theory which states that there is a 1:1 correspondence between distribution functions and characteristic functions.
Now I personally don't think that by itself is a reason to do CA.  But if it's that or PDE and you know you want to do mathematical statistics, then CA is the choice.


text:
Q: Confirming form submission on form created with javascript I've run into a problem trying to get a confirmation on a dynamically created form submission.  The form is being generated with information returned from an ajax call.  This HTML page submits a form to a php script via ajax and the page responds back with a transaction number.
After the response, the code below creates a new "Void Transaction" button and form that will void the previous transaction.
It all works perfectly, but I can't find a way to do a confirmation (e.g. "Are you sure you want to void the last transaction?") before the new button is clicked.


text:
Q: Nokogiri search over a document and modify parent node and can't access child node I am using nokogiri to search through an HTML document using the css method. When I find an element I modify it by wrapping it in another element and reinserting it into that node. The issue is if that element that contains a child with a class that I am searching for, since I modify the parent node it skips the child.
Here is an example to help explain.
html_string = <<-HEREDOC

Hello

HEREDOC

doc = Nokogiri::HTML(html_string)
doc.css('.mt-1').each do |node|
  node.replace(Nokogiri::HTML::DocumentFragment.parse("
#{node.to_html}
"
end

The child-div never gets accessed because the parent had it's contents rebuilt and it doesn't research the updated node.
Is there a way I can update the parent node and still have access to the child node on the next loop?

A: I figured out the answer to my own question with a bit of consulting from coworkers. The issue is that we are modifying from parent to child. What I really want to do is modify from child to parent so that I never mess with the contents of anything.
To do so I sort the node list in reverse order of the number of ancestors the element has.
# the key change -> .sort_by{ |n| n.ancestors.size }.reverse!
doc.css('.mt-1').sort_by{ |n| n.ancestors.size }.reverse!.each do |node|
  node.replace(Nokogiri::HTML::DocumentFragment.parse("
#{node.to_html}
"
end


text:
Q: Receiving blocks of data from a TCP IP hardware device using c# I have a barcode scanner hardware device that continually scans barcodes passing passing by and sends the data through it's tcpip port.  The scanner is installed on a production line and reads all passing barcodes for verification purposes.  There isn't any information sent to the barcode scanner other than what might be sent through the NetworkStream class upon connection.  I implemented a very simple interface to verify connectivity and receipt of the expected data being sent by the device. Obviously the problem with this code is it only iterates a certain number of times.  Regardless of the looping choice, I need an app that receives data and continues to receive data until my code chooses to stop close the connection and stop receipt of data.  It has to always be watching the port for incoming data from the device's tcp ip server.
public void readData()
    {
        int n = 1;

            Byte[] data;
            Int32 port = 51236;
            TcpClient client = new TcpClient("192.168.0.70", port);
            NetworkStream stream = client.GetStream();
            String responseData = String.Empty;
            try
            {
                while (n < 50)
                {
                data = new Byte[256];  //arbitrary length for now

                // String to store the response ASCII representation.

                // Read the first batch of the TcpServer response bytes.
                Int32 bytes = stream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                m_upcCode = responseData;
                n++;
                }
            }
            catch (ArgumentNullException ArgEx)
            {
                m_upcCode = "ArgumentNullException: {0}" + ArgEx.Message.ToString();
            }
            catch (SocketException exSocket)
            {
                m_upcCode = "SocketException: {0}" + exSocket.Message.ToString();
            }
    }

I've been looking through numerous posts regarding establishing a connection to a tcp ip server and receiving data from the server.  The post I found with the most promise might be Can a TCP c# client receive and send continuously/consecutively without sleep?. I'm just having an issue understanding how to implement the design.  I would be happy just to see the code from that post simply called and implemented on a form and display data in a text box.  The data being received is always a fixed length of 12 digits of a bar code and a .  The data doesn't stop unless the conveyor belt stops.  But we don't want the connection to close just because of a line pause.  There was also a post at C# TCP Client listening for data specifically trying to address reading barcodes but didn't get much of a response.

A: Take out the counter completely.  When you do a read and there are zero bytes returned, put the thread to sleep momentarily, and loop.
public void readData()
{
    Byte[] data;
    Int32 port = 51236;
    TcpClient client = new TcpClient("192.168.0.70", port);
    NetworkStream stream = client.GetStream();
    String responseData = String.Empty;
    try
    {
        while (true)
        {
            data = new Byte[256];  //arbitrary length for now

            // String to store the response ASCII representation.

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(data, 0, data.Length);
            if (bytes == 0){
                System.Threading.Thread.Sleep(1000);
            }
            else {
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                m_upcCode = responseData;
            }
        }
    }
    catch (ArgumentNullException ArgEx)
    {
        m_upcCode = "ArgumentNullException: {0}" + ArgEx.Message.ToString();
    }
    catch (SocketException exSocket)
    {
        m_upcCode = "SocketException: {0}" + exSocket.Message.ToString();
    }
}

A: Maybe this code can help you.
It's a TCP server i wrote for a connector (protocol conversion) application. It can only handle one connection from one client. It run's a separate thread and can be controlled trough some public methods. It raises event's to communicate with other code. You might need to alter some code (for example the logging part). I hope it helps you.
public class TCPServer : ITCPServer
{
    private readonly IPEndPoint _ipEndPoint;
    private TcpListener _tcpListener;
    private TcpClient _tcpClient;
    private bool _runServer;
    private bool _connectToClient;
    private NetworkStream _networkStream;
    private volatile bool _isRunning;

    public TCPServer(IPEndPoint ipEndpoint)
    {
        _ipEndPoint = ipEndpoint;
    }

    #region Properties

    public bool IsRunning
    {
        get { return _isRunning; }
    }

    #endregion

    #region Events

    public event Action<byte[]> OnMessageReceived;
    public event Action<string> OnConnectionOpened;
    public event Action<string> OnConnectionClosed;
    public event Action<LogLevel, string> OnLogMessage;

    #endregion

    #region Public Methods

    public void Start()
    {
        _tcpListener = new TcpListener(_ipEndPoint);
        _runServer = true;
        _tcpListener.Start();

        var thread = new Thread(RunServerEngine);
        thread.Name = "TcpServer";
        thread.Start();

        while (!_isRunning)
        {
        }

        var localEndpoint = (IPEndPoint)_tcpListener.LocalEndpoint;
        RaiseOnLogMessage(LogLevel.Info, String.Format("Server started listening at ip address {0} on port {1}", localEndpoint.Address, localEndpoint.Port));
    }

    public void Stop()
    {
        _connectToClient = false;
        _runServer = false;
    }

    public void SendMessage(byte[] message)
    {
        _networkStream.Write(message, 0, message.Length);
        _networkStream.Flush();
    }

    public void DisconnectClient()
    {
        _connectToClient = false;
    }

    #endregion

    #region Private Methods

    private void RunServerEngine(Object obj)
    {
        try
        {
            _isRunning = true;

            while (_runServer)
            {
                Thread.Sleep(250);
                if (_tcpListener.Pending())
                {
                    using (_tcpClient = _tcpListener.AcceptTcpClient())
                    {
                        var socketForClient = _tcpClient.Client;
                        _networkStream = new NetworkStream(socketForClient);
                        RaiseOnConnectionOpened((IPEndPoint)_tcpClient.Client.RemoteEndPoint);
                        _connectToClient = true;

                        while (_connectToClient)
                        {
                            if (CheckClientConnection() == false)
                            {
                                _connectToClient = false;
                                break;
                            }

                            if (_networkStream.DataAvailable)
                            {
                                var bytes = new Byte[1024];
                                _networkStream.Read(bytes, 0, 1024);
                                bytes = bytes.TakeWhile(b => b > 0).ToArray();
                                RaiseOnMessageReceived(bytes);
                            }

                            Thread.Sleep(100);
                        }
                    }
                    RaiseOnConnectionClosed();
                }
            }

            RaiseOnLogMessage(LogLevel.Info, "Stopping TCP Server");
            _tcpListener.Stop();
            _isRunning = false;
            RaiseOnLogMessage(LogLevel.Info, "TCP Server stopped");
        }
        catch (Exception ex)
        {
            RaiseOnLogMessage(LogLevel.Error, String.Format("Fatal error in TCP Server, {0}", ex.ToString()));
            throw;
        }
    }

    private bool CheckClientConnection()
    {
        var connected = true;

        try
        {
            var pollResult = _tcpClient.Client.Poll(1, SelectMode.SelectRead);
            var dataAvailable = _tcpClient.Client.Available;
            connected = !(pollResult && _tcpClient.Client.Available == 0);

            if (!connected)
            {
                RaiseOnLogMessage(LogLevel.Info, "Detected disconnection from client");
                RaiseOnLogMessage(LogLevel.Info, String.Format("TCPServer.CheckClientConnection - connected: {0}, pollResult: {1}, dataAvailable: {2}", connected, pollResult, dataAvailable));
            }
        }
        catch (SocketException ex)
        {
            RaiseOnLogMessage(LogLevel.Info, String.Format("Exception occurred in TCPServer.CheckClientConnection. Ex: {0}", ex.ToString()));
            connected = false;
        }

        return connected;
    }

    private void RaiseOnMessageReceived(byte[] message)
    {
        if (OnMessageReceived != null)
        {
            try
            {
                OnMessageReceived(message);
            }
            catch (Exception ex)
            {
                RaiseOnLogMessage(LogLevel.Warning, ex.Message);
            }
        }
    }

    private void RaiseOnConnectionOpened(IPEndPoint remoteEndpoint)
    {
        if (OnConnectionOpened != null)
        {
            var msg = String.Format("Connected to client with ip address: {0}, port: {1}", remoteEndpoint.Address, remoteEndpoint.Port);
            OnConnectionOpened(msg);
        }
    }

    private void RaiseOnConnectionClosed()
    {
        if (OnConnectionClosed != null)
            OnConnectionClosed("Disconnected from client");
    }

    private void RaiseOnLogMessage(LogLevel level, string message)
    {
        if (OnLogMessage != null)
            OnLogMessage(level, message);
    }

    #endregion
}


text:
Q: C#/Windows: Play one audio file from speaker, and another audio file from the 'default audio device' (headphones/headset)? Is it possible to play one audio file from speaker, and another audio file from the 'default audio device' (headphones/headset), using any C# library e.g. NAudio.
I have some example code running in a C# console application, which does not seem to work:
using var mp3 = new Mp3FileReader(stream);
var enumerator = new MMDeviceEnumerator();

var dev = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);

Console.WriteLine(dev.Count); // - 2: Speaker + Headset

// basically play from all devices
foreach (var o in dev)
{
    var outSpeakerInit = new WasapiOut(o, AudioClientShareMode.Shared, true, 100);
    var ev = new ManualResetEvent(false);
    outSpeakerInit.PlaybackStopped += (s, e) => ev.Set();
    outSpeakerInit.Init(mp3);
    outSpeakerInit.Play();
    ev.WaitOne();
}

A: It seems to work on non-console apps .e.g WinForms. Maybe it's because of the presence of a windows event loop.


text:
Q: How to load multiple csv into pandas without concatenate? I would like to apply two separate graphs to each text file in a folder with subdirectories, however I wouldn't want them to be joined into one data frame.
I am currently only able to load one file into pandas at a time. If I put the root directory, I get an error that the File doesn't exist.
data = pd.read_csv(r'/Users/work/DexterStudio/DataFolder/*', sep=" ", header = None, na_values='NaN')

# organize data
data.drop(data.columns[[4]], axis=1, inplace=True)
data.columns = ["timestamp", "x", "y", "z"]

#get current axes object
frame1 = plt.gca()

#draw two graphs
plt.plot(data['timestamp'],data['x'],color='r', label='x-axis')
plt.plot(data['timestamp'],data['y'], color='b', label='y-axis')

# hide axes
frame1.axes.get_xaxis().set_visible(False)
plt.legend(loc='upper right')
plt.show()

plt.plot(data['timestamp'],data['z'],color='g', label='z-axis')
plt.legend(loc='upper right')
plt.show()

A: Just do two read statements into two variables and go from there:
data1 = pd.read_csv(r'/Users/work/DexterStudio/DataFolder/file1', sep=" ", header = None, na_values='NaN')
data2 = pd.read_csv(r'/Users/work/DexterStudio/DataFolder/file2', sep=" ", header = None, na_values='NaN')

Note naming the files in the read statement and that you now have data1 and data2


text:
Q: Android: tag rotation in imageview cutting image inside listview i'm new in android development and i'm trying rotating an image view inside a listview. I have the follow xml for the custom cell:
<RelativeLayout
    android:id="@+id/content"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true">

    <ImageView
        android:id="@+id/borderImageView"
        android:layout_width="@dimen/photoReceiverWidth"
        android:layout_height="@dimen/photoReceiverHeight"
        android:scaleType="fitXY"
        android:rotation="-10"/>
 </RelativeLayout>

When it display, it cut a peace of the image. The view is not calculating the size for the rotation.
I don't want to create a new bitmap because the cost is too high.

A: android:adjustViewBounds="true"

This is an image view property, so place it within the image view rather than the relative layout. I am not sure if adjustViewBounds works on a fixed size ImageView.
You could change the width and height to wrap_content and use a maxHeight or minHeight property to define some additional bounding rules.
The scale type should also probably be centerInside, but play with these to see what suits.


text:
Q: check if all elements in hive array contain a string pattern I have two columns in a hive table that look something like this:
code    codeset
AB      AB123,MU124
LM      LM123,LM234

I need to verify that all elements in codeset column contain the value in code column so in the above example the first row would be false and the second row would be true.
Is there a simple way to do this that I am missing? I already read about array_contains but that returns true if just one element matches, I need all elements to contain what's in the code column.
Thanks in advance.

A: split the string, explode and use lateral view to unpivot the data. Then check using locate if the split codeset contains each code (which is done with group by and having).
select code,codeset
from tbl
lateral view explode(split(codeset,',')) t as split_codeset
group by code,codeset
having sum(cast(locate(code,split_codeset)>0 as int))=count(*)

A: select a.pattern,b.listOfInputs from ( select  * from (select a.pattern, case when inputCount = sumPatternMatchResult then true else false end finalResult from (select pattern , sum(patternMatchResult) as sumPatternMatchResult from (select pattern,case when locate(pattern,input) !=0 then 1 else 0 end patternMatchResult from (select pattern,explode(split(listOfInputs,',')) as input from tbl)a ) b group by pattern) a join (select pattern , count(input) inputCount from (select pattern,explode(split(listOfInputs,',')) as input from tbl)a group by pattern) b on a.pattern=b.pattern )c where finalResult=true)a  join (select * from tbl) b on a.pattern=b.pattern
This works too.
column mapping details for your table:
code -> pattern
codeset -> listOfInputs


text:
Q: (Java) Get value of string loaded into dynamic-type object? I'm very new to Java (~10 days), so my code is probably pretty bad, but here's what I've got:
ArgsDataHolder argsData = new ArgsDataHolder();  // a class that holds two
                                                 // ArrayList's where each element
                                                 // representing key/value args
Class thisArgClass;
String thisArgString;
Object thisArg;

for(int i=2; i< argsString.length; i++) {
    thisToken = argsString[i];
    thisArgClassString = getClassStringFromToken(thisToken).toLowerCase();
    System.out.println("thisArgClassString: " + thisArgClassString);
    thisArgClass = getClassFromClassString(thisArgClassString);

    // find closing tag; concatenate middle
    Integer j = new Integer(i+1);
    thisArgString = getArgValue(argsString, j, "</" + thisArgClassString + ">");

    thisArg = thisArgClass.newInstance();
    thisArg = thisArgClass.valueOf(thisArgString);
    argsData.append(thisArg, thisArgClass);
}

The user basically has to input a set of key/value arguments into the command prompt in this format: <class>value</class>, e.g. <int>62</int>.  Using this example, thisArgClass would be equal to Integer.class, thisArgString would be a string that read "62", and thisArg would be an instance of Integer that is equal to 62.
I tried thisArg.valueOf(thisArgString), but I guess valueOf(<String>) is only a method of certain subclasses of Object.  For whatever reason, I can't seem to be able to cast thisArg to thisArgClass (like so: thisArg = (thisArgClass)thisArgClass.newInstance();, at which point valueOf(<String>) should become accessible.
There's got to be a nice, clean way of doing this, but it is beyond my abilities at this point.  How can I get the value of the string loaded into a dynamically-typed object (Integer, Long, Float, Double, String, Character, Boolean, etc.)?  Or am I just overthinking this, and Java will do the conversion for me?  :confused:

A:
I can't seem to be able to cast thisArg to thisArgClass (like so: thisArg = (thisArgClass)thisArgClass.newInstance();,

This will not work like this as you need to initialize thisArgClass first.This will produce compile time error. Change the code something like this:
Class thisArgClass = null;
try {
    Object thisArg = thisArgClass.newInstance();
} catch (InstantiationException ex) {
    Logger.getLogger(Test3.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
    Logger.getLogger(Test3.class.getName()).log(Level.SEVERE, null, ex);
}

Hope this will help you.

A: There are several things wrong here.  I'll assume that thisArgClass has been set correctly; for your example it would contain Integer.class.  In order to invoke newInstance() on a Class object, the class must have a no-arg constructor. Class Integer does not have such a constructor, so you have to invoke one of the existing constructors using a more roundabout method:
Constructor<Object> c = thisArgClass.getConstructor(String.class);
Object i = c.newInstance(thisArgString);

Since you don't know the actual type of the object until runtime you must use <Object> and cast the result to the desired type before using the value.


text:
Q: Using Promise.all() in which the the individual promises retry on error I have an array of promises (request-promises) that are wrapped in another method so that they will retry 3 times if an error is caught. That part is working fine. I want to use promise.all() because I am going to have a big array of http-requests eventually. With the method I am using so far, promise.all() still calls it callback function before all retry attempts have been done. Is there a way I can wait for all retry attempts to finish before promise.all() does it's callback.
var http_req = require('request-promise')

function My_Http(retries, options)
{
    return http_req(options)
            .then(data=>{console.log('success')})
            .catch(err => {
                retries > 0 ? My_Http(retries-1, options) :  console.log(err.message)
             })
}

var promises = []
promises.push( My_Http(3, options1))
promises.push( My_Http(3, options2))

promise.all(promises).then( data=> {console.log(data)} )

A: Okay I think this was a dumb mistake but might be good for others to see, I removed the then inside My_Http and return the entire ternary statement.
var http_req = require('request-promise')

function My_Http(retries, options)
{
    return http_req(options)
            .catch(err => {
                return retries > 0 ? My_Http(retries-1, options) :  console.log(err.message)
             })
}

var promises = []
promises.push( My_Http(3, options1))
promises.push( My_Http(3, options2))

promise.all(promises).then( data=> {console.log(data)} )


text:
Q: How to read a JSON with ORACLE How can I make a query or function that allows me to obtain the description when sending the language en_US or es_LA
Currently what I have in the OFFER_DESC field is the text indicated below
SELECT OFFER_DESC FROM TAB_DESCRIPTION
{"en_US":"English text example","es_LA":"Ejemplo de texto en español"}

How can I send the language en_US or es_LA
and get the value English text example or Ejemplo de texto en español

A: Maybe this?
    with TAB_DESCRIPTION as(
    SELECT '{"en_US":"English text example","es_LA":"Ejemplo de texto en español"}'  OFFER_DESC FROM dual )
    select json_value( offer_desc, '$.en_US'),json_value( offer_desc, '$.es_LA')
from tab_description


text:
Q: Is there a sass tool for Javascript? Is there a tool like Sass for Javascript?
To be more specific:
A tool that allows the user to include multiple javascript files via a special syntax and watch for any changes on the files included. Once a change occurs on one or more of those files, the tool should concatenate and compress the files and ideally do some error checking along the way. The results should be included in a single file.
I'm looking for a tool that runs in the background while I'm coding, not a server or client side tool like minify or less.js

A: You can try CoffeeScript but you need to compile oyur .coffee to make a .js


text:
Q: How to secure user show page alongside user admin functions when using devise I'm using devise and have let admins manage users with a Manage::UsersController.
This is locked down using cancan:
# models/ability.rb
def initialize(user)
  if user admin?
   can :manage, User
  end
end

Normal users can have nothing to do with User other than through devise, so everything looks secure.
Now I want to give users a 'show' page for their own account information (rather than customising the devise 'edit' page).  The advice (1,2,3) seems to be to add a users_controller with a show method.
I tried to give non-admins the ability to read only their own information with:
if user admin?
  can :manage, User
else
  can :read, User, :id => user.id    # edited based on @Edwards's answer
end

However this doesn't seem to restrict access to Manage::UsersController#index, so it means that everybody can see a list of all users.
What's the simplest way to achieve this?  I can see two options, (but I'm not sure either is right):
1) Prevent user access to Manage::UsersController#index
def index
  @users = User.all
  authorize! :manage, User   # feels hackish because this is 'read' action
end

2) Over-write devise controller
Per this answer over-writing a devise controller could be a good approach, but the question is which controller (the registrations controller?) and how.  One of my concerns with going this route is that the information I want to display relates to the User object but not devise specifically (i.e. user plan information etc.).  I'm also worried about getting bogged down when trying to test this.
What do you recommend?

A: I would keep your registration and authentication as Devise controllers; then, create your own User controller that is not a devise controller.
In your own controller, let's call it a ProfilesController, you could only show the specific actions for the one profile (the current_user)
routes
resource :profile

profiles controller
class ProfilesController
  respond_to :html
  def show
    @user = current_user
  end

  def edit
    @user = current_user
  end

  def update
    @user = current_user
    @user.update_attributes(params[:user])
    respond_with @user
  end
end

Since it's always only editing YOU, it restricts the ability to edit or see others.

A: In your ability.rb you have
  can :read, User, :user_id => user.id

The User model won't have a user_id - you want the logged in user to be able to see their own account - that is it has the same id as the current_user. Also, :read is an alias for [:index, :show], you only want :show. So,
  can :show, User, :id => user.id

should do the job.


text:
Q: How can I extract a number from a command's output? How may I structure a command to print only 2.60 from the following string (the output from another command, lscpu):
model name      : Intel(R) Xeon(R) CPU E5-2690 v4 @ 2.60GHz

A: Assuming you mean to print the number between @<whitespaces> and GHz at the end of lines that start with model name, that would be:
sed -nE 's/^model name.*@[[:space:]]*([.[:digit:]]+)GHz$/\1/p' /proc/cpuinfo

Or with GNU grep:
grep -Po '^model name.*@\s*\K[.\d]+(?=GHz$)' /proc/cpuinfo

With lscpu, see also:
lscpu -J | jq -r '
  .lscpu[] |
  select(.field == "Model name:").data |
  match("@\\s*([\\d.]+)GHz$").captures[0].string |
  tonumber'

Or:
lscpu -J | jq -r '.lscpu[]|select(.field == "CPU max MHz:").data|tonumber'

For the max frequency in MHz instead of the base frequency from the model name.

A: Using sed (GNU sed for its I flag for case insensitive matching).
$ lscpu | sed -En 's/^model name.* ([0-9.]+).*/\1/Ip'
2.60

A: You can try something like this with awk:
awk '{print int($NF*100)/100.0}' /proc/cpuinfo

this line can be rewrited but I am not sure how different awk implementations will handle it:
awk '{print $NF*1.0}' /proc/cpuinfo

This will print 2.6. If you want to have it with zero you can use:
awk '{printf "%4.2f",int($NF*100)/100.0}' /proc/cpuinfo

If you want to use lscpu you can it on this way:
lscpu|awk '/odel name/ {print int($NF*100)/100.0}'

A: <command>| awk '{gsub(/[a-zA-Z]/,"",$NF);print $NF}'

Tested with echoing the following command output
echo "model name      : Intel(R) Xeon(R) CPU E5-2690 v4 @ 2.60GHz"| awk '{print $NF}'|sed "s/[a-zA-Z]//g"

output

2.60

A: LANG=C lscpu | sed -rn "s/.*Model name.* @ (.*)GHz/\1/p"

The LANG=C is needed, if your language setting isn't set to English.
The -n for sed suppresses output by default. The -r is for simpliefied typing of capturing groups (without backslash).
The "s/A/B/p" command substitutes A with B and the p performs a print, if condition A is met (since we suppressed output by default, that's neccessary).
A is the regex, and \1 the first (and only) capture group.


text:
Q: iOS/Swift - If/ if else statement not working as it should I've been trying to get this code to work for the past few hours. But I have been getting mixed results.
 static func uploadDataToServer(data: Data, secondData: Data? = nil, thirdData: Data? = nil, firstVideoURL: URL? = nil, secondVideoURL: URL? = nil, thirdVideoURL: URL? = nil, caption: String, onSuccess: @escaping () -> Void) {

    if let firstVideoURL = firstVideoURL {
        SingleVideoHandler.uploadOneVideoToFirebase(firstVideoURL: firstVideoURL, onSuccess: { (vidURL) in
            uploadImagesToFirebaseStorage(data: data, secondData: secondData!, thirdData: thirdData!, onSuccess: { (firstImage, secondImage, thirdImage) in
                sendDataToDatabase(firstPhotoURL: firstImage, secondPhotoURL: secondImage, thirdPhotoURL: thirdImage ,firstVideoURL: vidURL, caption: caption, onSuccess: onSuccess)

                })
        })
    } else {

    if let firstVideoURL = firstVideoURL, let secondVideoURL = secondVideoURL {
    print("Got two pics!")
        MultipleVideoHandler.uploadTwoVideosToFirebase(firstVideoURL: firstVideoURL, secondVideoURL: secondVideoURL, onSuccess: { (firstVidURL, secondVidURL) in
            uploadImagesToFirebaseStorage(data: data, secondData: secondData!, thirdData: thirdData!, onSuccess: { (firstImage, secondImage, thirdImage) in
                sendDataToDatabase(firstPhotoURL: firstImage, secondPhotoURL: secondImage, thirdPhotoURL:  thirdImage, firstVideoURL: firstVidURL, secondVideoURL: secondVidURL, caption: caption, onSuccess: onSuccess)

            })
        })
    } else {
          if let secondImageData = secondData, let thirdImageData = thirdData {
            uploadThreeImagesToFirebaseStorage(data: data, secondData: secondImageData, thirdData: thirdImageData) { (firstPhotoURL, secondPhotoURL, thirdPhotoURL) in
                self.sendDataToDatabase(firstPhotoURL: firstPhotoURL, secondPhotoURL: secondPhotoURL, thirdPhotoURL: thirdPhotoURL, caption: caption, onSuccess: onSuccess)
                }
            }
    }
}
}

Basically, I'm trying to detect wether I have a firstVideoURL, a secondVideoURL and a thirdVideoURL.
However, in order to have a secondVideoURL you must have a firstVideoURL. Like wise with regards to having a thirdVideoURL you must have both a firstVideoURL and a secondVideoURL.
What I'm doing in essence it allowing for optional videos, where users can select up to three videos to upload and images. Only have 3 parameters as of now, due to to testing.
I'm trying to detect how many videoURLs I have, and based of that, upload however many videos have been selected and additional content.
My results so far:
Only the first if-let statement is called and executed. Even thought I have more than one videoURL.
The code is called multiple times, creating the same instance of a post, however, the first instance will only contain the firstVideoURL and the second instance will have both the first and second video URL. The second instance is what I want. But I do not want the first instance.
I cannot figure out as to why this is happening?
Could someone please help me out?
Thank you.
In essence this is what I want-
I've got 2 video URL
The code is executed
Checks the conditions
Skips the first if-let statement
Executes the second if-let statement.
In terms of uploading and create posts, the server/api code works as expected. Just this conditional operation is not working as I anticipated.

A: The first if condition (if let firstVideoURL = firstVideoURL) passes if there's firstVideoURL, it doesn't care about secondVideoURL and/or thirdVideoURL. If thats what you need you should consider constructing your if-else like below:
if let firstVideoURL = firstVideoURL{
   if let secondVideoURL = secondVideoURL{
      if let thirdVideoURL = thirdVideoURL{
         //Do what you would if there are all the three video urls.
      } else {
         //Do what you would if there are firstVideoURL and secondVideoURL but not the thirdVideoURL
      }
   } else {
      //Do what you would if there is only the firstVideoURL
   }
} else {
     //Handle the case when there are no video urls.
}

A: Do you want to allow it to be called with NO video URLS? If so, why? You've made all 3 videoURL parameters optional, which doesn't seem to make sense. It seems to me that you should allow one, 2, or 3.
In any case, your code doesn't make sense as written. Once the first if clause fails, you know that firstVideoURL is nil, so the second if clause is also going to fail.
If you're going to continue with this approach, I think @CodeDifferent has the right idea with their comment:
if let firstVideoURL = firstVideoURL,
  let secondVideoURL = secondVideoURL,
  let thirdVideoURL = thirdVideoURL {
    //upload 3 videos
} else if let firstVideoURL = firstVideoURL,
  let secondVideoURL = secondVideoURL {
    //upload 2 videos
} else if let firstVideoURL = firstVideoURL {
    //upload 1 video
} else {
    //No videos. Why is this possible?
}

(I don't really understand your use of both video URLs and data objects, so I ignored that part.)
However, lets take a step back. Why are you using 3 separate sets of optional parameters and dealing with a messy construct of if let optional bindings? Why not pass in an array of video URLS?
func uploadDataToServer( data: [Data], urls: [URL]) {
  //Loop through the array of data objects/URLs and upload each one.
}


text:
Q: Browser Compatibility Problem 1
Browser Compatibility
I use Dreamweaver CS5.
I have all the major Browsers installed on my system to have my sites checked with all of them.
I recently designed a site that enabled users to sign in to our Company Site.
It worked very well in all other browsers but when i tried it on my Internet Explorer; it was just a disaster.
First of all, all the objects were misplaced.

Problem 2
Repeated Clicks
Another site of mine works fine in all browsers and versions. (TESTED @ Adobe Browser Lab)
But when I opened that site in the host machine @ Internet Explorer it makes multiple click sound. Hearing the sound I feel like the address is demanded with too many clicks. At the end IE stops working...!
Please Help Me !

A: You can't really rely on WYSIWYG editors for producing cross platform designs. The only real way to get it working correctly is by manually editing the css/html and testing as you go.


text:
Q: Obfuscation removes datacontext class I'm trying to obfuscate my Winforms app using EAZfuscator. When I try and run the obfuscated app, I get an Entity Framework exception (ProviderIncompatibleException).
Using IlSpy to look at the obfuscated assembly - I notice that whilst most of my namespaces and classes remain as they were (it just seems to be some variable names that have been renamed), it has completely removed my DataContext class (ie. the one that derives from DbContext).
I presume my ProviderIncompatibleException exception is due to the name of connection string needing to match the datacontext class name. I have this in my app.config:
<add name="DsDataContext" connectionString="Data Source=Database.sdf" providerName="System.Data.SqlServerCe.4.0" />

Where DsDataContext is the name of my class that derives from DbContext (the one that appears to have been removed by Eazfuscator).
Has anyone experienced this before? Any reason why this class has been removed by Eazfuscator? Also, I'm curious to why my class names have remained intact. The obfuscation doesn't seem to be very obfuscated.
Update
Below is the exception for completeness. I presume I'm getting it due to the missing class I mention above though:
Type: System.Data.ProviderIncompatibleException
Message: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
Source = EntityFramework
StackTrace:
  at System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
  at System.Data.Entity.ModelConfiguration.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
  at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
  at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
  at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
  at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
  at System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps()
  at System.Data.Entity.Database.Exists()
  at   .()
  at   .()

A: Or maybe your class is being renamed by the obfuscator.
Try to add the ObfuscationAttribute to your data context class:
[ObfuscationAttribute(Exclude=true)]


text:
Q: Android studio, Metodo Switch trava o app to tendo um problema com o Switch do Android studio, simplesmente não consigo fazer nem uma manipulação com o dado dele porque simplesmente trava o App na VM.
MAIN.Java

uma duvida, essas alterações são na MAIN.JAVA ou na Fragment?


text:
Q: The entitlements in your app bundle signature do not match the ones that are contained in the provisioning profile I have submitted many app builds to TestFlight, even yesterday, but today when I tried to submit my app to TestFlight via XCODE I get the following error:
ERROR ITMS-90164: "Invalid Code Signing Entitlements. The entitlements in your app bundle signature do not match the ones that are contained in the provisioning profile. According to the provisioning profile, the bundle contains a key value that is not allowed: '[ ]' for the key 'com.apple.developer.healthkit.access' in 'Payload/Runner.app/Runner'."
I'm building a flutter project via XCODE. I have tried the following:

*

*Cleaning my project.

*Re-enabling automatic app signing in XCODE.

*Deleting my provisioning files from ~/Library/MobileDevice/Provisioning\ Profiles/

*Disabling automatic signing in xcode and creating my own provisioning profile via the Apple Developer site

But I'm still getting this error. My enablements haven't changed from the last time I uploaded my app. Please help, thank you.
UPDATE 1:
Appears to be a change made on Apples end that is causing this error. No official response/explanation from Apple has been provided yet. Some workarounds have been provided below. I went with enabling Clinical Health Records usage for the Health Kit enablement since this workaround doesn't use any non-apple approved changes. So still technically not a final solution, but a workaround.
UPDATE 2:
Apple has resolved the issue on their end, no workarounds are required anymore.

A: Same error for me with "icloud-container", just comment these lines in your . entitlements file:
<key>com.apple.developer.[YOUR-ERROR]</key>
<array/>

A: Deleting the empty iCloud Container entitlement (array) from the entitlement files solved the issue for me. Seems like a server-side change from Apple that no longer allows an empty array there.

A: What worked for me
Before started trying, I checked my .entitlements file it looks like this:
    ...
    <key>com.apple.developer.healthkit</key>
    <true/>
    <key>com.apple.developer.healthkit.access</key>
    <array/>
    ...

Step 1: Remove and add HealthKit capability again.

*

*Remove HealthKit from "Signing and Capabilities"

*

*Add HealthKit back

Step 2: Check on "Clinical Health Records"

Once done, you shall be able to see your .entitlements file become
    <key>com.apple.developer.healthkit</key>
    <true/>
    <key>com.apple.developer.healthkit.access</key>
    <array>
        <string>health-records</string>
    </array>

Step 3: Add Privacy - Health Records Usage Description and its value to info.plist
Final: Then I tried to archive and upload to TestFlight, it worked.

A: Apple has fixed the issue. You can now try submitting app to TestFlight without making any changes.
Thread on Apple Developer forum: https://developer.apple.com/forums/thread/671352

A: I commented-out/removed
<key>com.apple.developer.healthkit.access</key>

in .entitlements and it works!

A: A key with a value that is an empty array seems to be not allowed in entitlements anymore. Just removing the key/value pair fixed it for me.

A: Solution
What worked for me was to remove the following line in the .entitlements file
<key>com.apple.developer.healthkit.access</key>
<array/>

Validation

*

*I double checked and the HealthKit access still works for read/write when building via Xcode

*I tested the app via TestFlight and everything still looks good

*My app got approved and everything works fine for existing and new users :)

Side notes

*

*I had the same issue. I haven't changed the entitlements for months and out of a sudden that error appeared. It might be the case that Apple changed some logic and applied stricter rules on their backend entitlement validation.

*Interesting that if you create a new Xcode project and add the HealthKit entitlements it creates the entitlements like:
<key>com.apple.developer.healthkit</key>
<true/>
<key>com.apple.developer.healthkit.access</key>
<array/>

*

*Interesting read: https://developer.apple.com/forums/thread/10738

A: I was facing the similar error.
I believe the Apple back-end has changed and has started applying a stricter rule to entitlement keys that take array values.
I believe the Apple back-end used to accept empty arrays for entitlement keys that took array values but now require the entitlement key to either not be present at all or to contain actual values.
Evidence to back this assertion:

*

*I have an entitlements file with a key for "com.apple.developer.icloud-container-identifiers" entitlement with an empty array like so:

  <key>com.apple.developer.icloud-container-identifiers</key>
  <array/>

*

*This was fine until just yesterday (I successfully submitted a build, and have submitted builds like this for more than a year).

The Fix:
Remove or Comment out the following line from the .entitlements file:
  <key>com.apple.developer.icloud-container-identifiers</key>
  <array/>

*

*The key was empty anyway so should not have an effect after being removed.

Now the TestFlight submission is successful.

A: Remove 'com.apple.developer.healthkit.access' won't help the issue. So far we can just hope to wait for Apple to fix this.
Thread on forum (i can't access the Marceeelll's thread):
https://developer.apple.com/forums/thread/671352
Related:

*

*App Store Connect Operation Error: ITMS-90164 [] for key com.apple.developer.healthkit.access

A: For me solution is to remove the following line in the .entitlements file
<key>com.apple.developer.healthkit.access</key>
<array/>

!This work if you submit the app for TestFlight!
This does not work if you submit the app for review :(. Binary will be rejected ITMS-90000: This bundle is invalid - $message.
What work for me: First, when you enable your app's HealthKit capabilities: you must also select the Clinical Health Records checkbox!

Next, you must provide a Health Records Usage string in your app's Info.plist file.

A:
I had the same issue with Network extensions, it is also empty and deleting it from Entitlements solved the issue.

A: Deleting the empty iCloud container entitlement will resolve the upload issue. But the app cannot select any documents from iCloud using document picker (UIDocumentMenuViewController).
We would end up with a crash in the app as below:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Application initializing
document picker is missing the iCloud entitlement. Is
com.apple.developer.icloud-container-identifiers set?'


text:
Q: I have the visual basic code on excel and need help resolving this Sub Refresh()
'
' Refresh Macro
'
    'Save a copy with date stamp before refreshing data
    Dim dtToday As String
    dtToday = Format(Date, "yyyymmdd")
    ActiveWorkbook.SaveCopyAs Filename:="\\NABDC01SDPRS01\C01905_SHARE_S_01\TOR1\Resource\Service Ontario RESP Tracker\Archived\RESP Leads List_" & dtToday & ".xlsm"
'
    Dim reccnt As Integer
    ActiveWorkbook.Connections("Query - service_ontario_master_list").Refresh

    'Added logic in hope that it will wait for connectino to refresh before running the rest of code
    ActiveWorkbook.Save

    Sheets("Working List").Select
    'Unprotect sheet
    ActiveSheet.Unprotect

    'Added logic to remove all filter before delete.  This should resolve the duplicate issue
    ActiveWorkbook.Worksheets("Working List").ListObjects("Table2").AutoFilter.ShowAllData

    Cells.Select
    Selection.EntireColumn.Hidden = False
    reccnt = Range("A3") + 1
    Range("A5:AO1000").Select
    Selection.clear
    Sheets("Query").Select
    Range(Cells(2, 1), Cells(reccnt, 40)).Select
    Selection.Copy
    Sheets("Working List").Select
    Range("A5").Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False
    Range("S3").Select
    Application.CutCopyMode = False
    Selection.Copy
    Range("S5").Select
    Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False

    Range(Cells(5, 22), Cells(5 + reccnt, 22)).Select
    Application.CutCopyMode = False
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Lists!$D$3:$D$6"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    Range(Cells(5, 29), Cells(5 + reccnt, 29)).Select
    Application.CutCopyMode = False
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Lists!$D$3:$D$6"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    Range(Cells(5, 35), Cells(5 + reccnt, 35)).Select
    Application.CutCopyMode = False
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Lists!$D$3:$D$6"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    Range("AA5").Select
    Application.CutCopyMode = False
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Lists!$B$3:$B$12"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    Range(Cells(5, 27), Cells(5 + reccnt, 27)).Select
    Application.CutCopyMode = False
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Lists!$B$3:$B$12"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    Range(Cells(5, 33), Cells(5 + reccnt, 33)).Select
    Application.CutCopyMode = False
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Lists!$B$3:$B$12"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    Range(Cells(5, 39), Cells(5 + reccnt, 39)).Select
    Application.CutCopyMode = False
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Lists!$B$3:$B$12"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    Range(Cells(5, 3), Cells(5 + reccnt, 3)).Select
    Application.CutCopyMode = False
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Lists!$K$3:$K$4"
        .IgnoreBlank = False
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With

    'Add data validation (drop down) for Status and Outcome
    Range("T5").Select
    Range(Selection, Selection.End(xlDown)).Select
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Lists!$N$3:$N$4"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    Range("U5").Select
    Range(Selection, Selection.End(xlDown)).Select
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Lists!$B$3:$B$5"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With

    'Sort list: lead arrival data aesc and UID aesc
    ActiveWorkbook.Worksheets("Working List").ListObjects("Table2").sort.SortFields _
        .clear
    ActiveWorkbook.Worksheets("Working List").ListObjects("Table2").sort.SortFields _
        .Add2 Key:=Range("Table2[Lead Arrival Date]"), SortOn:=xlSortOnValues, _
        Order:=xlAscending, DataOption:=xlSortNormal
    ActiveWorkbook.Worksheets("Working List").ListObjects("Table2").sort.SortFields _
        .Add2 Key:=Range("Table2[UID]"), SortOn:=xlSortOnValues, Order:= _
        xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Working List").ListObjects("Table2").sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    'Hide calculation columns
    Range("A:B").EntireColumn.Hidden = True
    Columns("F:G").Select
    Selection.EntireColumn.Hidden = True
    Range("Y:Y").EntireColumn.Hidden = True
    'Freeze Panel
    Range("H5").Select
    ActiveWindow.FreezePanes = True

    'Protect Sheet
    Columns("T:AN").Select
    Selection.Locked = False
    Selection.FormulaHidden = False
    Range("V1:AN4").Select
    Selection.Locked = True
    Selection.FormulaHidden = False
    Columns("C:C").Select
    Selection.Locked = False
    Selection.FormulaHidden = False
    Range("C1:C4").Select
    Selection.Locked = True
    Selection.FormulaHidden = False
    Columns("D:U").Select
    ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingCells:=True, AllowFormattingColumns:=True, _
        AllowFormattingRows:=True, AllowSorting:=True, AllowFiltering:=True

    'Date Cloumns Adjustment
    Columns("W:W").ColumnWidth = 13
    Columns("W:W").NumberFormat = "m/d/yyyy"
    Columns("AD:AD").ColumnWidth = 13
    Columns("AD:AD").NumberFormat = "m/d/yyyy"
    Columns("AJ:AJ").ColumnWidth = 13
    Columns("AJ:AJ").NumberFormat = "m/d/yyyy"

    Range("V4").Select

End Sub


text:
Q: PHP Simple HTML DOM Parser - get element's hyphenated attribute value I'm using PHP Simple HTML DOM Parser. In the page which I want to parse the images 'src' attribute is replaced with 'data-src'. So, if I try to get the image path using the following code, it will return nothing:
$elimage = $offer->find('div.photo', 0);
$im = $elimage->last_child('a');
$img = $im->last_child('img');
$item['image'] = $img->src;

I've tried to do it like this, but it does not work either:
$elimage = $offer->find('div.photo', 0);
$im = $elimage->last_child('a');
$img = $im->last_child('img');
$item['image'] = $img->data-src;

Does anybody know if that's possible to get the value of a custom attribute and, if yes, how can that be achieved?
Thanks for helping!

A: instead of
 $img->data-src;

use
$img->{'data-src'};

taken from here

A: Anyway, I was about to find a solution to this kind of problem and stumble here then suddenly got an idea.
Just put it in variable first:
$dataSrc='data-src';
$item['image'] = $img->$dataSrc;

A: <?php
$str= "Hello";
$var=preg_split("/data-src=\'/",$str);
//echo $var[1];
$var1=preg_split("/\'/",$var[1]);
echo $var1[0];
?>

You can use this also..

A: Thanks for the help!
I grabbed the URL from the string using the following function:
function checkURL($str) {
    $regex = '$\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]$i';

    preg_match_all($regex, $str, $result, PREG_PATTERN_ORDER);
    $A = $result[0];

    foreach($A as $a) {
        $retval .= $a;
    }

    return $retval;
}

The URL-s I was finding were absolute and there was only one URL in the given string.
Thanks again for the hint @Rajat Singhal!


text:
Q: how to get NSBezier paths to stroke with a consistant line width In my NSView subclass in drawRect I stroke a number of NSBezierPaths. I would like the lines drawn as a result of these strokes to have the exact same with, preferably just a couple of pixels wide no matter the scaling of the view. Here's my drawRect:
- (void)drawRect:(NSRect)dirtyRect
{
    NSSize x = [self convertSize:NSMakeSize(1,1) fromView:nil];
    printf("size = %f %f\n", x.width, x.height);
    for(NSBezierPath *path in self.paths) {
        [path setLineWidth:x.width];
        [path stroke];
    }
}

Here's a screenshot of what I am seeing:

(source: crb at www.sonic.net)
Can anyone suggest how I can get the crisp consistant path outlines that I am looking for?
Thanks.

A: Try to match the exact pixels of the device. (more difficult since iphone 5)
Do not use coordinates with on half points: like 0.5 (The work on retina, but on "non retina" they are unsharp).
Th eline width goes half to the left / or up, half to the right.
So if you have a lineWidth of 2 and coorinates at integer values it should be sharp.


text:
Q: Run the same gradle task multiple times in parallel in IntelliJ My java project consists of two modules, client and server. I am using IntelliJ and gradle. I want to run one server instance and two client instances in parallel. Until now, I have opened three terminal windows with the commands gradle server:run and 2x gradle client:run and everything worked as expected. Now, I tried the following configuration in IntelliJ:

*

*Gradle:

*

*Run Server

*Run Client 1

*Run Client 2

*Compound:

*

*Run Two Clients (contains the three gradle configurations)

However, if I run the compound configuration, only one client is executed. The other client prints Executing task 'run'... but does not actually run. Only when I terminate the first client, the other client starts. Is there a way to run both client tasks in parallel?

A: It is a known issue: IDEA-270755 Gradle Task with 'Allow Parallel Run' option hangs when executed subsequently.


text:
Q: Calculating Chi-square probability with $X^2$ and degrees of freedom How do I calculate the probability (%) for chi square test using $X^2$ value and DoF as inputs?
Im trying to create a C++ program to calculate chi square tests with very high DoF, so I cannot use the table to check the probability. I have already written functions to calculate DoF and $X^2$ values.
I'm not a mathematician so an example with the values inserted would be greatly helpful, for example with DoF of $14$ and $X^2$ of $17$.

A: For very large $n$ the chi-squared distribution is nearly normal
with mean equal to df and variance twice the df.
R statistical software available free from r-project.org has
density function 'dchisq', cumulative distribution function
'pchisq', quantile function (inverse CDF) 'qchisq', and
also 'rchisq' which samples from the distribution.
From what you say I believe you want the area under the
density curve of chi-squared with 14 DF to the right of 17 (the
P-value for a right-tailed test with test statistic 17).
In R that would be
 > 1 - pchisq(17, 14)
 [1] 0.2561779

Here are other examples, some of which are in your table, and
the last of which shows the good agreement with normal for large DF:
 > qchisq(.95, 10)
 [1] 18.30704   # 95% area below 18.3
 > dchisq(2, 15)
 [1] 9.829755e-05  # PDF almost 0 at 2
 > pchisq(190, 200);  pnorm(190, 200, 20)  # 3rd arg is SD
 [1] 0.3173568  # exact
 [1] 0.3085375  # normal appprox

Unless you have considerable experience programming probability
functions I do not recommend writing your own C++ code.
Surely, there is compiled code you can import that is written
by experts, using best procedures for various DFs.
Addendum: If $Q \sim Chisq(df = \nu),$ with large $\nu,$ then
$q$ with $P\{Q > q\} = \alpha$ has
$$q \approx \nu\left(1 - \frac{2}{9\nu} + z_{\alpha} \sqrt{\frac{2}{9\nu}}\right)^3,$$
where $z_{\alpha}$ cuts probability $\alpha$ from
the upper tail of a standard normal curve. For example:
 > qchisq(.95, 150)
 [1] 179.5806  # cuts 5% from right tail of CHISQ(150)
 > 150*(1 - 2/(9*150) + qnorm(.95)*sqrt(2/(9*150)))^3
 [1] 179.5788  # good approximation of above