text:
Q: Error in custom php.ini: "Invalid command 'php_value', perhaps misspelled or defined by a module not included in the server configuration" I currently have dedicated server which runs WHM/cPanel.
I ran into as issue after uploading my project to my webroot.
The error:
Invalid command 'php_value', perhaps misspelled or defined by a module not included in the server configuration

My question is:
Is there any way to run the custom php.ini to get my project running?
I tried to edit the php-70u (which I'm running on my server) to edit my custom php.ini file.
But that didn't work for some reason.  Could i get a helping hand?
And my .htaccess
php_value post_max_size 500M
php_value upload_max_filesize 500M
php_value max_execution_time 60000

My custom php.ini
[PHP]

;;;;;;;;;;;;;;;;;
; Data Handling ;
;;;;;;;;;;;;;;;;;

; The separator used in PHP generated URLs to separate arguments.
; PHP's default setting is "&".
; http://php.net/arg-separator.output
; Example:
;arg_separator.output = "&"

; List of separator(s) used by PHP to parse input URLs into variables.
; PHP's default setting is "&".
; NOTE: Every character in this directive is considered as separator!
; http://php.net/arg-separator.input
; Example:
;arg_separator.input = ";&"

; This directive determines which super global arrays are registered when PHP
; starts up. G,P,C,E & S are abbreviations for the following respective super
; globals: GET, POST, COOKIE, ENV and SERVER. There is a performance penalty
; paid for the registration of these arrays and because ENV is not as commonly
; used as the others, ENV is not recommended on productions servers. You
; can still get access to the environment variables through getenv() should you
; need to.
; Default Value: "EGPCS"
; Development Value: "GPCS"
; Production Value: "GPCS";
; http://php.net/variables-order
variables_order = "GPCS"

; This directive determines which super global data (G,P,C,E & S) should
; be registered into the super global array REQUEST. If so, it also determines
; the order in which that data is registered. The values for this directive are
; specified in the same manner as the variables_order directive, EXCEPT one.
; Leaving this value empty will cause PHP to use the value set in the
; variables_order directive. It does not mean it will leave the super globals
; array REQUEST empty.
; Default Value: None
; Development Value: "GP"
; Production Value: "GP"
; http://php.net/request-order
request_order = "GP"

; This directive determines whether PHP registers $argv & $argc each time it
; runs. $argv contains an array of all the arguments passed to PHP when a script
; is invoked. $argc contains an integer representing the number of arguments
; that were passed when the script was invoked. These arrays are extremely
; useful when running scripts from the command line. When this directive is
; enabled, registering these variables consumes CPU cycles and memory each time
; a script is executed. For performance reasons, this feature should be disabled
; on production servers.
; Note: This directive is hardcoded to On for the CLI SAPI
; Default Value: On
; Development Value: Off
; Production Value: Off
; http://php.net/register-argc-argv
register_argc_argv = Off

; When enabled, the ENV, REQUEST and SERVER variables are created when they're
; first used (Just In Time) instead of when the script starts. If these
; variables are not used within a script, having this directive on will result
; in a performance gain. The PHP directive register_argc_argv must be disabled
; for this directive to have any affect.
; http://php.net/auto-globals-jit
auto_globals_jit = On

; Whether PHP will read the POST data.
; This option is enabled by default.
; Most likely, you won't want to disable this option globally. It causes $_POST
; and $_FILES to always be empty; the only way you will be able to read the
; POST data will be through the php://input stream wrapper. This can be useful
; to proxy requests or to process the POST data in a memory efficient fashion.
; http://php.net/enable-post-data-reading
;enable_post_data_reading = Off

; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size = 2G

; Automatically add files before PHP document.
; http://php.net/auto-prepend-file
auto_prepend_file =

; Automatically add files after PHP document.
; http://php.net/auto-append-file
auto_append_file =

; By default, PHP will output a character encoding using
; the Content-type: header.  To disable sending of the charset, simply
; set it to be empty.
;
; PHP's built-in default is text/html
; http://php.net/default-mimetype
default_mimetype = "text/html"

; PHP's default character set is set to empty.
; http://php.net/default-charset
;default_charset = "UTF-8"

; Always populate the $HTTP_RAW_POST_DATA variable. PHP's default behavior is
; to disable this feature. If post reading is disabled through
; enable_post_data_reading, $HTTP_RAW_POST_DATA is *NOT* populated.
; http://php.net/always-populate-raw-post-data
;always_populate_raw_post_data = On

;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;

; UNIX: "/path1:/path2"
;include_path = ".:/php/includes"
;
; Windows: "\path1;\path2"
;include_path = ".;c:\php\includes"
;
; PHP's default setting for include_path is ".;/path/to/php/pear"
; http://php.net/include-path

; The root of the PHP pages, used only if nonempty.
; if PHP was not compiled with FORCE_REDIRECT, you SHOULD set doc_root
; if you are running php as a CGI under any web server (other than IIS)
; see documentation for security issues.  The alternate is to use the
; cgi.force_redirect configuration below
; http://php.net/doc-root
doc_root =

; The directory under which PHP opens the script using /~username used only
; if nonempty.
; http://php.net/user-dir
user_dir =

; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir=/opt/php/php-5.5.0/lib/php/extensions/no-debug-non-zts-20121212
; On windows:
; extension_dir=/opt/php/php-5.5.0/lib/php/extensions/no-debug-non-zts-20121212

; Directory where the temporary files should be placed.
; Defaults to the system default (see sys_get_temp_dir)
; sys_temp_dir = "/tmp"

; Whether or not to enable the dl() function.  The dl() function does NOT work
; properly in multithreaded servers, such as IIS or Zeus, and is automatically
; disabled on them.
; http://php.net/enable-dl
enable_dl = Off

; cgi.force_redirect is necessary to provide security running PHP as a CGI under
; most web servers.  Left undefined, PHP turns this on by default.  You can
; turn it off here AT YOUR OWN RISK
; **You CAN safely turn this off for IIS, in fact, you MUST.**
; http://php.net/cgi.force-redirect
;cgi.force_redirect = 1

; if cgi.nph is enabled it will force cgi to always sent Status: 200 with
; every request. PHP's default behavior is to disable this feature.
;cgi.nph = 1

; if cgi.force_redirect is turned on, and you are not running under Apache or Netscape
; (iPlanet) web servers, you MAY need to set an environment variable name that PHP
; will look for to know it is OK to continue execution.  Setting this variable MAY
; cause security issues, KNOW WHAT YOU ARE DOING FIRST.
; http://php.net/cgi.redirect-status-env
;cgi.redirect_status_env =

; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI.  PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is.  For more information on PATH_INFO, see the cgi specs.  Setting
; this to 1 will cause PHP CGI to fix its paths to conform to the spec.  A setting
; of zero causes PHP to behave as before.  Default is 1.  You should fix your scripts
; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
; http://php.net/cgi.fix-pathinfo
;cgi.fix_pathinfo=1

; FastCGI under IIS (on WINNT based OS) supports the ability to impersonate
; security tokens of the calling client.  This allows IIS to define the
; security context that the request runs under.  mod_fastcgi under Apache
; does not currently support this feature (03/17/2002)
; Set to 1 if running under IIS.  Default is zero.
; http://php.net/fastcgi.impersonate
;fastcgi.impersonate = 1

; Disable logging through FastCGI connection. PHP's default behavior is to enable
; this feature.
;fastcgi.logging = 0

; cgi.rfc2616_headers configuration option tells PHP what type of headers to
; use when sending HTTP response code. If it's set 0 PHP sends Status: header that
; is supported by Apache. When this option is set to 1 PHP will send
; RFC2616 compliant header.
; Default is zero.
; http://php.net/cgi.rfc2616-headers
;cgi.rfc2616_headers = 0

;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
;upload_tmp_dir =

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2G

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20

;;;;;;;;;;;;;;;;;;
; Fopen wrappers ;
;;;;;;;;;;;;;;;;;;

; Whether to allow the treatment of URLs (like http:// or ftp://) as files.
; http://php.net/allow-url-fopen
allow_url_fopen = On

date.timezone =  "Europe/Paris"

; Whether to allow include/require to open URLs (like http:// or ftp://) as files.
; http://php.net/allow-url-include
allow_url_include = On

; Define the anonymous ftp password (your email address). PHP's default setting
; for this is empty.
; http://php.net/from
;from="john@doe.com"

; Define the User-Agent string. PHP's default setting for this is empty.
; http://php.net/user-agent
;user_agent="PHP"

; Default timeout for socket based streams (seconds)
; http://php.net/default-socket-timeout
default_socket_timeout = 60

; If your scripts have to deal with files from Macintosh systems,
; or you are running on a Mac and need to deal with files from
; unix or win32 systems, setting this flag will cause PHP to
; automatically detect the EOL character in those files so that
; fgets() and file() will work regardless of the source of the file.
; http://php.net/auto-detect-line-endings
;auto_detect_line_endings = Off

A: You should use the MultiPHP Editor from WHM. You can define a custom php version for each of your cPanel accounts. Then from the cPanel web interface of your account you can edit/adjust your php settings accordingly. Just search for PHP in cPanel. These settings should be performed using the cPanel/WHM interface and not by manually editing the files on your server. Manually edited files (via ssh/ftp etc) will be overwritten anyway when you do a change via cPanel or WHM.


text:
Q: Using existing SQLite database in Cayenne I've been playing around with Apache Cayenne in an IntelliJ project.
I configure the JDBC in the datanode like in the image but it gives me an error

I have the Cayenne project stored in my IntelliJ project folder, as well as the SQLite database "data.db".
Can anyone help me figuring out this?

A: You need to tell CayenneModeler GUI where to find SQLite jar. To do that on Windows, go to Tools > Preferences > ClassPath and add a path to your SQLLite jar.

A: It works with cayenne 3.1.1 and
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.23.1</version>
    </dependency>

https://bitbucket.org/xerial/sqlite-jdbc/overview

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parquet file load into snowflake table Issue I am trying to load data from parquet file in AWS S3 into snowflake table. But getting the below error. Could you please help.
SQL compilation error: PARQUET file format can produce one and only one column of type variant or object or array.
Use CSV file format if you want to load more than one column.

Parquet file schema
 |-- uuid: string (nullable = true)
 |-- event_timestamp: timestamp (nullable = true)
 |-- params: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: string (nullable = true)
 |    |    |-- name: string (nullable = true)
 |    |    |-- type: string (nullable = true)
 |    |    |-- value: string (nullable = true)

Here is the sample data.
uuid,event_timestamp,params
3f230ea5-dd52-4cf9-bdde-b79201eb1001,2020-05-10 17:06:21.524,[{id=501, type=custom, name=filtering, value=true}, {id=502, type=custom, name=select, value=false}]
snowflake table
create or replace table temp_log (
      uuid string,
      event_timestamp timestamp,
      params array);

I am using the below copy command to load data
 copy into temp_log
 from '<<s3 path>>'
 pattern = '*.parquet'
 storage_integration = <<integration object>
 file_format = (
     type = parquet
     compression = snappy
 )
 ;

A: This documentation explains how to load parquet data into multiple columns:
Loading Parquet
UPDATE
I'm not sure if the comment below is a response to my answer and, if it is, what the relevance of it is? Did you read the document and, if you did, what part of it do you still have questions about?
You need to have your data in a stage (presumably an external stage in your case), or possibly in an external table, and then load from that into your table using "COPY INTO table FROM (SELECT..." with the $1:.. notation allowing you to select the appropriate elements from you parquet structure.
From the documentation:
/* Load the Parquet data into the relational table.                                                           */
/*                                                                                */
/* A SELECT query in the COPY statement identifies a numbered set of columns in the data files you are        */
/* loading from. Note that all Parquet data is stored in a single column ($1).                                */
/*                                                                                */
/* Cast element values to the target column data type.                                                        */

copy into cities
  from (select
  $1:continent::varchar,
  $1:country:name::varchar,
  $1:country:city.bag::variant
  from @sf_tut_stage/cities.parquet);

A: This issue was resolved after creating table as below
create or replace table temp_log (

     logcontent VARIANT);

A: In my case the error message was raised because I was running the command as
COPY INTO my_db.my_schema.my_table
FROM (
    SELECT *
    FROM @my_stage
) FILE_FORMAT = ( TYPE = PARQUET );

Instead each column should be specified as $1:my_column in the 'select statement', for example:
COPY INTO my_db.my_schema.my_table
FROM (
    SELECT $1:my_column1, $1:my_column2, $1:my_column3
    FROM @my_stage
) FILE_FORMAT = ( TYPE = PARQUET );

A: I use these 2 sql to load the data into table,
first: use this SQL to create the table sql
with cols as (
select COLUMN_NAME || '   ' || TYPE  col
  from table(
    infer_schema(
      location=>'@LANDING/myFile.parquet'
      , file_format=>'LANDING.default_parquet'
      )
  )
),
temp as (
    select 'create or replace table myTable (' col1
    union
    select listagg(col, ',') col1
    from cols
    union
    select ') ' col1
)
select listagg(col1)
from temp

Second, use this SQL to create the copy into SQL load the data into table
with cols as (
select expression
  from table(
    infer_schema(
      location=>'@LANDING/myFile.parquet'
      , file_format=>'LANDING.default_parquet'
      )
  )
),
temp as (
    select 'copy into myTable from ( select ' col1
    union
    select listagg(expression, ',') col1
    from cols
    union
    select 'from @LANDING/myFile.parquet ) ' col1
)
select listagg(col1)
from temp


text:
Q: Inline transition duration weird behavior I'm making a floating up animation of a text with CSSTransition. It works, but only if I specify animation's duration in css file. What I want is to keep duration parameter in one place (js file) to keep code DRY. Right now I need to specify it in both css class and CSSTransition's timeout prop.
The problem is that when I uncomment inline style with duration, the animation first goes up, but then it goes backwards and it shouldn't. What am I missing? When *-enter-active class goes off the animated text should become hidden, because of the diff class. Maybe the browser doesn't re-calculate styles? Why does it work, when duration is specified in css and doesn't work when it is in style prop?
Here's the codepen. Uncomment line 20 in js file to see the bug.
const AnimatedDiff = ({value}) => {
  const [prev, setPrev] = React.useState(value)
  const diff = value - prev
  const diffSign = diff > 0 ? '+' : ''
  const diffStr = diffSign + diff

  const timeout = 800

  return (
    <CSSTransition
      classNames='diff'
      timeout={timeout}
      in={diff > 0}
      onEntered={() => setPrev(value)}
    >
      <div
        className='diff'
        // style={{transitionDuration: `${timeout}ms`}}
      >
        {diffStr}
      </div>
    </CSSTransition>
  )
}

.diff {
  position: absolute;
  right: 0;
  visibility: hidden;
}

.diff-enter-active {
  visibility: visible;
  transform: translate(0, -100%);
  transition: transform;
  transition-duration: 800ms;
}

A: I've got it. I need to replace visibility prop with display. This does the trick. Also, display: block should be specified within a separate .diff-enter rule, not in a .diff-enter-active. So, styles become:
.diff {
  position: absolute;
  right: 0;
  display: none;
}

.diff-enter {
  display: block;
}

.diff-enter-active {
  transform: translate(0, -100%);
  transition: transform;
}


text:
Q: Includepdf : issue with figures in addtolist I am using the package pdfpages and I have troubles using the addtolist. I tested with tables and lstlisting (it worked) but for weird reasons, it didn't work with figures :
MWE :
    \documentclass[a4paper,12pt]{report}

    \usepackage{listings}
    \usepackage{graphicx}
    \usepackage{pdfpages}
    \usepackage[toc,page]{appendix}
    \usepackage[compact]{titlesec}
    \usepackage{titletoc}
    \usepackage{hyperref}% Just in case....

    \providecommand{\phantomsection}{}

    \makeatletter
    \newcommand{\appendixlistingname}{Appendix Listings}
    \newcommand{\listofappendixlistings}{%
      % Applying the same trick as listings does with \lstlistoflistings: Modifying \@starttoc such that it can load only .apl files
      \begingroup
      \let\@starttoc@orig\@starttoc%
      \renewcommand{\contentsname}{\appendixlistingname}
      \renewcommand{\@starttoc}[1]{%
        \@starttoc@orig{apl}%
      }%
      \phantomsection
      \addcontentsline{toc}{section}{\appendixlistingname}
      \tableofcontents% Calling \tableofcontents with the `.apl` file instead of `.toc`
      \endgroup
    }

    \newcommand{\appendixFix}{%
      \setcounter{lstlisting}{0}%
      \@ifundefined{theHlstlisting}{%
        }{%
          \renewcommand{\theHlstlisting}{appendix}
        }%
      \write\@auxout{%
        \string\let\string\latex@tf@lol\string\tf@lol% Store the original `\tf@lol` file handle
        \string\let\string\tf@lol\string\tf@apl%
      }%
    }{}{}
    \makeatother

    \begin{document}

    % Start partial lists
    \startlist[appendices]{lof}% starts appendices list of figures
    \startlist[appendices]{lot}% starts appendices list of tables

    % renaming later
    \newcommand\listfigurenameappendixes{\listfigurename}
    \newcommand\listtablenameappendixes{\listtablename}

    \appendixFix

    \begin{appendices}

        \begingroup
            \let\clearpage\relax
            % prints appendices list of figures
            \printlist[appendices]{lof}{}{
                \chapter*{\listfigurenameappendixes}
            }
            % prints appendices list of tables
            \printlist[appendices]{lot}{}{
                \chapter*{\listtablenameappendixes}
            }
            % prints appendices list of tables listings
            \listofappendixlistings
        \endgroup

    \includepdf[
        pages=1,
        pagecommand=\chapter{Analyse Bibliographique}\label{annexe:AnalyseBiblio},
        offset=0 -1cm,
        scale=0.8
    ]{example-image-duck.pdf}

    \includepdf[
        pages=2-,
        pagecommand={},
        width=1.2\textwidth,
        % To have items into list of figures / tables / listings
        % WARNING : As explained by the doc, this option is experimental (it MAY change but I don't think so : many people used that)
        % SECOND WARNING : the page number argument is the real position from starting point !!
        addtolist={
            8, table, {Les 5 types de données de la LOM}, tab:typeLOM,
            15, table, {Éléments de base de notre norme}, tab:baseNorm,
            16, table, {Éléments d'un mot-clé de notre norme}, tab:KeyElementsNorm,
            16, table, {Quelques éléments additionnels de notre norme}, tab:ExtendedElementsNorm,
            17, lstlisting, {Exemple d'une ressource information avec notre norme}, code:exampleJson
            % Bug with figures : no idea why
            %5, figure, {Les 15 éléments de la Dublin Core}, fig:dcListElements,
            %6, figure, {Les 9 catégories d'éléments de la LOM}, fig:LOMTable,
            %7, figure, {Représentation hiérarchique de la LOM}, fig:LOMChart,
            %7, figure, {Correspondance des éléments entre la Dublin Core et la LOM}, fig:mappingDcLom,
            %9, figure, {MLR - Spécification d'un élément de données}, fig:mlr,
            %9, figure, {MLR - Exemple de spécification d'un élément de données}, fig:mlr2,
            %10, figure, {Représentation simplifiée de la MLR}, fig:mlr3,
            %11, figure, {Exemple de taxonomie pour les exercices de programmation}, fig:taxonomieEx,
            %12, figure, {Liste des sous-domaines de l'informatique selon la CC2005}, fig:AllDomainInInfo,
            %13, figure, {Exemple de hiérarchie de compétences}, fig:comptenceTree,
            %13, figure, {Catégories d'exercices informatiques}, fig:CatExoList
        }
    ]{example-image-duck.pdf}

    \end{appendices}

    % Stop partial lists
    \stoplist[appendices]{lof}% stops main list of figures
    \stoplist[appendices]{lot}% stops main list of tables

    \end{document}

If I uncomment all the figures (and not forgot to put a comma after lstlisting), I got this message :

Thanks for the help

A: The error message speaks of \ext@lstlisting and the problem is not with figure but with listings: the package doesn't define all the commands pdfpages expects here and so it doesn't know where to write the entry.
\documentclass[a4paper,12pt]{report}

\usepackage{listings}
\usepackage{pdfpages}
\makeatletter
\def\ext@lstlisting{lol} %<------------ added
\makeatother
\begin{document}

    \includepdf[
        pages=2-20,
        addtolist={
             17, lstlisting, {Exemple d'une ressource information avec notre norme}, code:exampleJson
        }
    ]{example-image-duck}

 \end{document}


text:
Q: Vim Python ImportError No module named xlrd I have tried answers posted here
But I still can't fix the same issue.
Here is my python code:
import xlrd
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

df = pd.read_excel('airquality.xlsx')

print("Column headings:")
print(df.columns)

:!python 'readexcel.py'

Traceback (most recent call last):
  File "readexcel.py", line 1, in <module>
    import xlrd
ImportError: No module named xlrd
shell returned 1

While I check the xlrd it shows it has been satisfied:
$python --version
Python 3.6.9
$ pip3 install xlrd
Requirement already satisfied: xlrd in /usr/local/lib/python3.6/dist-packages (1.2.0)

while in terminal, it seems no issue:
    python
    Python 3.6.9 (default, Nov  7 2019, 10:44:02)
    [GCC 8.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import xlrd
    >>>

A: Try:
pip3 install --upgrade xlrd
python3 readexcel.py

A: Solved by in .vimrc (using !python3 instead of !python):
nnoremap <buffer> <F9> :exec '!python3' shellescape(@%, 1)<cr>


text:
Q: Does Visual Studio generate assembly from the C source or from the binary code it compiled into? When I run my code (any code), in debug mode I have the option of "Disassembly".
I know that "Disassembly" is the creation of assembly code from machine code ('1' and '0' that stored in object files).
So, I can assume that when I compile my code in Visual Studio, there is no "Assembly/Assembler" stage between the C/C++ code to the machine code/object file, and if I want to see the Assembly code I need to ask Visual Studio to disassemble it from object file to assembly.
So my questions are:

*

*am I right, is there no way to see asm other than disassembly?

*(if 1 is no): why does Visual Studio's debugger show a "Disassembly" option, not "Assembly"?

*Does Clang/GCC have an assembly stage, or does the C/C++ code compile to object code directly?

editor's note: the answer to 3 actually differs for GCC vs. most other mainstream C/C++ compilers like clang/LLVM and MSVC.  Since that's kind of a separate question from how MSVC works, that part is a duplicate of these other SO Q&As:

*

*Does a compiler always produce an assembly code?

*What do C and Assembler actually compile to?

*What is the need to generate ASM code in gcc, g++

A: When a debugger provides a disassembly option, it is generally examining memory of the running process, augmented by debugging information embedded in or associated with the executable file, which can include references that help the debugger identify associated source code.
Separately, compilers usually have an option to show you the assembly language that is either the assembly language they use internally (perhaps in temporary files passed to specific subprocesses, such as an assembler) or its equivalent (what it would generate if it were not generating object code directly). For GCC and Clang, the -S switch does this. For Visual Studio, /FA does this.


text:
Q: How would I load an ogg file in node js My goal is to load ogg files in node.js
I've tried ReadFile but hits me up with this error: Could not read file. [Error: ENOENT: no such file or directory, open 'Main\game\songs\test\Voices.ogg'] and the file does exist.
Code:
fs.readdir('./game/songs', function(err, files){
        if (err) {
            console.log("Could not list the directory.", err)
            return
        }
        files.forEach(function(file, index){
            fs.readFile('./game/songs/'+file+"/Inst.ogg", function(err, data){
                if (err) {
                    console.log("Could not read file.", err)
                    return
                }
            })
            fs.readFile('./game/songs/'+file+"/Voices.ogg", function(err, data){
                if (err) {
                    console.log("Could not read file.", err)
                    return
                }
            })
        })
    })

A: You should pass the absolute path of the file, use the built-in path module's join() function:
const path = require('path');
const fs = require('fs');

fs.readFile(path.join(__dirname, 'YOUR_PATH_HERE'), function(err, data) {});


text:
Q: A book teaches tensor products and flatness without the use of categorical stuffs? I'm now working on the exercises of Chapter 2 of Atiyah-Macdonald, and I consult some algebra books, for example, Lang's Algebra and Aluffi's Algebra: Chapter 0, to help me understand the things like tensor products and flatness.
However, these book all use categorical concepts like direct limit, adjoint pair heavily to prove the basic propositions of flatness, for example, the preserving of flatness in direct sums.
So I open some category textbook and try to learn some stuffs like adjoint pair. But they are too abstract for me that I spent whole days only learn category, without any progress on commutative algebra.
So my question is: Is there any textbook teaches the proofs of basic properties of tensor products and flatness in detail and doesn't use the categorical concepts like adjoint pair?
I know that Atiyah-Macdonald itself didn't use any category stuffs, but it didn't give much details in proofs and a lot of key propositions were in exercises. I'm learning these concepts for the first time so it's difficult for me to go through.
Thanks!

A: See abstract algebra by Dummit Foote . The concepts are explained in detail. In particular, it's treatment of tensor product is based on arbitrary rings and not on commutative rings like in Atiyah. It has also has an appendix on Category and functors which is explained in an easy style.
By the way flat modules are explained just after the chapter on tensor product along with projective and injective modules which Atiyah Don't have.
Exercise of Tensor product is highly  recommended from that book.
Also I should mention that in the first two pages of the chapter tensor product it motivates the need to introduce the concept of tensor which Is great and which most of the books doesn't write in detail.


text:
Q: R warning message on recursive expression: If you fail, try, try again I want to create a function that will retry an expression if it fails.  Here's my working version:
retry <- function(.FUN, max.attempts=3, sleep.seconds=1) {
  x <- NULL
  if(max.attempts > 0) {
    f <- substitute(.FUN)
    x <- try(eval(f))
    if(class(x) == "try-error") {
      Sys.sleep(sleep.seconds)
      return(suppressWarnings(retry(.FUN, max.attempts-1)))
    }
  }
  x
}

retry(stop("I'm here"))

If I remove the suppressWarnings() function above, then I get a set of warnings on each recursive call.  Does anyone know what I'm doing wrong that would cause that?
Here's an example that can be run repeatedly:
retry({ tmp <- function() { if(rnorm(1) < 0) stop("I'm here") else "success" }; tmp() })

A: I'm not sure if I can describe the cause exactly, but I've isolated the problem and can fix it.  The basic problem is the recursion: retry(.FUN, max.attempts-1)  - when the recursive call calls substitute(.FUN) it's going to have go up a level of the call stack to figure out what the value of .FUN is - it has to restart the evaluation of a promise (the delayed execution of function arguments) a level up.
A fix is to just do the substitution once:
retry <- function(.FUN, max.attempts = 3, sleep.seconds = 0.5) {
  expr <- substitute(.FUN)
  retry_expr(expr, max.attempts, sleep.seconds)
}

retry_expr <- function(expr, max.attempts = 3, sleep.seconds = 0.5) {
  x <- try(eval(expr))

  if(inherits(x, "try-error") && max.attempts > 0) {
    Sys.sleep(sleep.seconds)
    return(retry_expr(expr, max.attempts - 1))
  }

  x
}

f <- function() {
  x <- runif(1)
  if (x < 0.5) stop("Error!") else x
}

retry(f())

To create functions that you can use flexibly, I highly recommend minimising the use of substitute.  In my experience, you're usually best off having one function that does the substitution, and another that does all the work.  This makes it possible to use the function when called from another function:
g1 <- function(fun) {
  message("Function starts")
  x <- retry(fun)
  message("Function ends")
  x
}
g1(f())
# Function starts
# Error in eval(expr, envir, enclos) : object 'fun' not found
# Error in eval(expr, envir, enclos) : object 'fun' not found
# Error in eval(expr, envir, enclos) : object 'fun' not found
# Error in eval(expr, envir, enclos) : object 'fun' not found
# Function ends

g2 <- function(fun) {
  message("Function starts")
  expr <- substitute(fun)
  x <- retry_expr(expr)
  message("Function ends")
  x
}
g2(f())
# Function starts
# Error in f() : Error!
# Function ends
# [1] 0.8079241

A: Not sure about why you get the warnings... but if use a for loop they disappear.
retry <- function(.FUN, max.attempts=3, sleep.seconds=1)
  {
  x <- NULL
  for (i in 1:max.attempts)
      {
      f <- substitute(.FUN)
      x <- try(eval(f))
      if (class(x) == "try-error")
         {
         Sys.sleep(sleep.seconds)
         }
       else
         {
         return (x)
         }
      }
  x
  }


text:
Q: Symfony 2 form posting data but not inserting it I have a form built in Symfony 2.8 and I have been stumped for a few days trying to work out why a field will not populate.
So I have a form that is inserting a product for an order and the fields are all posting but the insert query is not picking up the data. It thinks the field is null.
Any suggestions?

A: First check your inserted data is valid for price field or change your price field nullable true.
If it's not helping you then describe your code descriptively.


text:
Q: Nice template for writing a speech The title says it all. I think that a beautiful speech deserves to be written in a beautiful template. I can just simply take a basic article or something alike and type the speech, but as a LaTeX geek, I would like the speech to look wonderful. Possibilities for margin notes would be appreciated, they might give some clues to improvise in the middle of the speech.

A: You want your speech to look "wonderful", and "wonderfulness" is subjective. In my case, wonderfulness and sobriety are almost synonymous; below I present a possibility.
You can take the article document class and do some little customizations. In the following example I chose the article document class and use the following settings and packages:

*

*Font size 11pt (or perhaps 12pt) to facilitate reading.

*The geometry package for the page layout: a5paper, narrow right margin, generous left margin for marginal notes.

*The marginnote package to typeset marginal notes: using \marginnote, marginal notes are not floats. \reversemarginpar to guarantee marginal notes on the left margin.

*The parskip package: I think that for a speech is convenient to have some vertical spacing between paragraphs and with no indentation for their first lines.

*The fwlw (first word, last word) package and its NextWordFoot page style: having the possibility to read ahead to the word on the next page can be helpful.

*The micro-typographic features provided by the microtype package.

*A nice font: I choose librebaskerville.
The code:
\documentclass[11pt]{article}
\usepackage[a5paper,lmargin=3.5cm,rmargin=25pt,bmargin=0.8cm,includefoot]{geometry}
\usepackage[T1]{fontenc}
\usepackage{parskip}
\usepackage{microtype}
\usepackage{marginnote}
\usepackage{fwlw}
\usepackage{librebaskerville}
\usepackage{lipsum}% just to generate text for the example

\pagestyle{NextWordFoot}
\reversemarginpar
\renewcommand*\marginfont{\footnotesize}

\begin{document}
Some text\marginnote{Some initial remark here}
\lipsum[1]
\lipsum*[4]\marginnote{Remember to mention something at this point}
\lipsum*[2]\marginnote{Don't forget to mention some people here}\lipsum[5]
\lipsum[4]
\end{document}


text:
Q: awk, sed, grep specific strings from a file in Linux Here is part of the complete file that I am trying to filter:
 Hashmode: 13761 - VeraCrypt PBKDF2-HMAC-SHA256 + XTS 512 bit + boot-mode (Iterations: 200000)

Speed.#2.........:     2038 H/s (56.41ms) @ Accel:128 Loops:32 Thr:256 Vec:1
Speed.#3.........:     2149 H/s (53.51ms) @ Accel:128 Loops:32 Thr:256 Vec:1
Speed.#*.........:     4187 H/s

The aim is to print the following:
13761 VeraCrypt PBKDF2-HMAC-SHA256 4187 H/s
Here is what I tried.
The complete file is called complete.txt
cat complete.txt | grep Hashmode | awk '{print $2,$4,$5}' > mode.txt

Output:
 13761 VeraCrypt PBKDF2-HMAC-SHA256

Then:
cat complete.txt | grep Speed.# | awk '{print $2,$3}' > speed.txt

Output:
 4187 H/s

Then:
paste mode.txt speed.txt

The issue is that the lines do not match. There are approx 200 types of modes to filter within the file 'complete.txt'
I also have a feeling that this can be done using a much simpler command with sed or awk.

A: I am guessing you are looking for something like the following.
awk '/Hashmode:/ { if(label) print label, speed; label = $2 " " $4 " " $5 }
  /Speed\.#/ { speed = $2 " " $ 3 }
END { if (label) print label, speed }' complete.txt

We match up the Hashmode line with the last Speed.# line which follows, then print when we see a new Hashmode, or reach end of file.  (Failing to print the last one is a common beginner bug.)

A: This might work for you (GNU sed):
sed -E '/Hashmode:/{:a;x;s/^[^:]*: (\S+) -( \S+ \S+ ).*\nSpeed.*:\s*(\S+ \S+).*/\1\2\3/p;x;h;d};H;$!d;ba' file

If a line contains Hashmode, swap to the hold space and using pattern matching, manipulate its contents to the desired format and print, swap back to the pattern space, copy the current line to the hold space and delete the current line.
Otherwise, append the current line to the hold space and delete the current line, unless the current line is the last line in the file, in which case process the line as if it contained Hashmode.
N.B. The first time Hashmode is encountered, nothing is output. Subsequent matches and the end-of-file condition will be the only times printing occurs.


text:
Q: Is it ok to create and handle the action items in the action bar withing fragments? Background
I have a similar scenario as shown on the sample of android website about fragments (link here) :

*

*small screen, portrait: single pane

*small screen, landscape: single pane

*7" tablet, portrait: single pane

*7" tablet, landscape: dual pane, wide

*10" tablet, portrait: dual pane, narrow

*10" tablet, landscape: dual pane, wide

*TV, landscape: dual pane, wide

The action bar in my case is always shown, and for now I only have action items in it.
The problem
The next scenario is very weird:

*

*Device has one pane for portrait, and 2 panes for landscape.

*Both of my fragments create their own action bar items.

*Switching from portrait to landscape show all of the action items (which is what I want)

*Switching from landscape to portrait show all of the action items.
This doesn't make much sense as the right pane doesn't exist, yet for some reason its fragment seems to exist in the fragmentManager, and its onCreateOptionsMenu is called even though it's not shown at all.
What I've tried
I've tried to call invalidateOptionsMenu() on the activity that holds both fragments, but it didn't help
I've also added the next code for each of the fragments, and it works perfectly:
@Override
public void onStart() {
    super.onStart();
    setHasOptionsMenu(true);
}

@Override
public void onStop() {
    super.onStop();
    setHasOptionsMenu(false);
}

The question
Why does it happen?
Is my solution of enabling/disabling the optionsMenu (thus enabling/disabling the action bar items creation by the fragments) a viable solution? Is there a better solution?
Is it even a good thing to make the fragments handle the action items in the first place?

A: I generally only have fragments handle action bar items in the single-pane case.  Logically the visible fragment owns all the screen space at that point, and since there's limited screen real estate it makes sense to use the action bar.  In the dual-pane case I tend to keep each fragment's UI within its own fragment and don't use the action bar.  However, if it makes visual sense in your scenario I don't see any reason why you can't.
My understanding is that the set of fragments in existence before a configuration change is recreated after a configuration change.  Android doesn't rely on the activity's layout file or anything like that.  Whatever fragments you have created is considered to be state to be preserved across configuration changes.  You might try manually removing the potentially unnecessary fragment when your activity is being torn down, and then count on Android to recreate it from the layout if it needs to exist after all.  However this is educated musing and not tested.
That said I don't see anything wrong with your current solution.

A: You could, in the onPrepareOptionsMenu(..) method of the right-hand fragment, hide and show the menu items as appropriate, by looking at the Configuration obtainable from getResources().getConfiguration().
As the other answer says, it is generally undesirable to change the amount of fragments shown during runtime - my app used to do this and I ran into thousands of issues.


text:
Q: R script to read file got as an argument from command line I cannot figure out how to read from file based on command line argument:( All the answers I was able too google seemed too complicated.
I want to run this script from command line and let $1 be replaced by name of file I pass as an argument.
#!/usr/bin/Rscript
duplication<- read.table($1, header=T)
options(scipen=10)
plot(duplication$x,duplication$y,col="blue");

So that by typing
R CMD BATCH script.R path_to_file

I want to read file and ideally output graph with the same name as was the name of file.

A: Take a look at commandArgs. You should be able to do something like:
args <- commandArgs(trailingOnly = FALSE)

Then access the arguments as a vector. See also this answer


text:
Q: Type erasure with function pointers does not work with GCC I am trying a sort of type-erasure with some function pointers and templates as given in the example below. What I find strange is with GCC i get wrong result where as with VS 2017, I get the expected one. So, who is correct and who is wrong and why ?
Live example on COLIRU: http://coliru.stacked-crooked.com/a/225db5711c07c8b0
struct A { void PrintA() { std::cout << "Event A" << std::endl; } };
struct B { void PrintB() { std::cout << "Event B" << std::endl; } };
struct C { void PrintC() { std::cout << "Event C" << std::endl; } };

struct RunBase
{
    virtual void operator()() = 0;
};

template <typename T>
struct Run : public RunBase
{
    using FUNC = void (T::*)();
    Run(T& o, FUNC&& f) : mObj(o), mFunc(f) {}
    void operator()() override { (mObj.*mFunc)(); }

    T& mObj;
    FUNC& mFunc;
};

int main()
{
    A a;
    B b;
    C c;

    std::vector<std::unique_ptr<RunBase> > mFuncs;
    mFuncs.push_back(std::make_unique<Run<A> >(a, &A::PrintA));
    mFuncs.push_back(std::make_unique<Run<B> >(b, &B::PrintB));
    mFuncs.push_back(std::make_unique<Run<C> >(c, &C::PrintC));

    for (auto& i : mFuncs)
        (*i)();

  return 0;
}

Expected result:
Event A
Event B
Event C

But GCC gives me:
Event C
Event C
Event C

A: It's because you store a reference inside your object, but &A::PrintA etc. are temporaries which are destroyed at the end of the full expression, and so the member reference is left dangling, and its use results in undefined behaviour.
Simply store a copy of the member function pointer to fix it:
FUNC mFunc;

PS. When mFuncs is destroyed, the unique pointers delete child objects through a base pointer. The behaviour is undefined unless you declare RunBase::~RunBase virtual.

So, who is correct and who is wrong and why ?

Your program is wrong; There is no correct behaviour for it.


text:
Q: How to publish Eclipse Dynamic Web Project on the internet (not localhost)? I have a dynamic web project with a .jsp, some java code which is called by scriptlets, which calls some database entries and so on. It runs great on my tomcat localhost server.
I want to publish this to the internet now (for free), just for purpose of practicing it. I don't want it to be safe, i don't need a high uptime or anything else, i just want to send a buddy the url to show it to him.
I tried AWS elastic beanstalk but for some reasons (have a running question on it) it doesnt work.
I found this: How to publish a JSP project on the Internet using Tomcat web server?
But somehow its too vague for me.
I have a Hostname and IP address from Dyndns.org.
I have Tomcat set up and it works locally on my machine.
In the description above i miss the point where i connect tomcat with the hostname and ip and whatever else i need.
Perhaps someone can give me better instructions how to set it up?

A: Your router is the only one reachable from the internet and he knows the local address of your pc with tomcat.
One problem:
Everytime your router goes online, he gets an other ip, so you can't specify a static ip within dyndns.org. You can setup your router to login at dyndns.org everytime it goes online - this way dyndns knows the ip of your router!
Next problem:
The router is not the server and normally blocks requests from outside. So you have to forward a port to another ip within your local network - your server with tomcat.
I hope this will your tomcat going online as my tomcat on my raspberry pi. :)


text:
Q: Trigger evaluation of PropertyTester The code from two years back had to be upgraded to E4, and now a bunch of stuff does not work anymore. One of these is the IEvaluationService if used like this:
<handler class="org.acme.PrintHandler" commandId="org.eclipse.ui.file.print">
  <activeWhen>
    <with variable="activePart">
      <test property="org.acme.printable" />
    </with>
  </activeWhen>
</handler>

IEvaluationService service = (IEvaluationService) PlatformUI.getWorkbench().getService(IEvaluationService.class);
service.requestEvaluation("org.acme.printable");

How do I (re)trigger the evaluation of a PropertyTester? Since E4 is really not even close to being production ready, I need a workaround for E3 (compatibility layer).
Related question - but this user was searching for the equivalent in E4, while I need one that works in E3.
Funnily enough, if I replace the <activeWhen> tags with <enabledWhen> it works. In that case IEventBroker#post and IEventBroker#send work, too.
This is a similar question. That user used Eclipse 4.2 - I tested the problem with 4.5, 4.6 and 4.7.

A: eventBroker.post(UIEvents.REQUEST_ENABLEMENT_UPDATE_TOPIC, UIEvents.ALL_ELEMENT_ID);

See also Eclipse bug 436755 and Eclipse Wiki: Eclipse 4 - RCP - Event Model

A: The EvaluationService is API compatible in the E3 Compatibility Layer. But the implementation in E4 is completely different, causing the behaviour of requestEvaluation to be fundamentally different.
The best solution to this problem I could find is to manually deactivate and activate all contexts of currently active parts. This causes internally to re-evaluate and, when required, re-render all UI elements of the respective parts.
One could argue this is less efficient than requesting the evaluation of a very specific property, as the EvaluationService is supposed to do. But since the evaluation is limited to active parts only, it should not create too much overhead. And it does work globally, as no specific property string is required anymore.
The only usecase not covered by this yet may be the main toolbar of your RCP application.
/**
 * Triggers evaluation of all UI elements (buttons, etc.) of the active part.
 * Also causes test of all property testers of all opened parts implicitly.
 * Workaround of the broken IEvaluationService.requestEvaluation.
 */
public static void triggerUIElementsEvaluation() {
    try {
        final EPartService partService = PlatformUI.getWorkbench().getService(EPartService.class);
        final MPart activePart = partService.getActivePart();

        /* Toggle context of active part to trigger re-evaluation of its UI elements. */
        if (activePart != null) {
            activePart.getContext().deactivate();
            activePart.getContext().activateBranch();
        }
    } catch (IllegalStateException e) {
        /* Ignore "Application does not have an active window" exception to allow program to continue. */
    }
}

A: I'm going to share my workaround, which is not good, and does not work in alles cases. And only really works because in my use case I have a IWorkbenchPart with an ISelectionProvider... but maybe it will help the next person:
IWorkbenchPart activePart = // get active view or editor
ISelectionProvider selectionProvider = activePart.getSite().getSelectionProvider();
ISelection selection = selectionProvider.getSelection();
selectionProvider.setSelection(new StructuredSelection());
selectionProvider.setSelection(selection);

This code just resets the selection, which normally triggers the PropertyTester. I don't think it'll work if nothing was selected.


text:
Q: Select siblings of siblings in jQuery In the following code, when the user clicks on the '.more' span element, I want to retrieve information (eg, the ID) from the img within the article tag using jQuery.
Here's the HTML:

some text link read more

I've tried this code:
   $('.more').click(function () {

        var id = $(this).siblings().siblings('img').attr('id');

});

but it doesn't seem to work. Any thoughts?
Many thanks!

A: You can do that like this:
$(".more").click(function() {
    var id = $(this).closest("article").find("img:first").attr("id");
});

This looks up the parent tree for the containing
 tag.  Then, it finds the first  tag in that and gets its id value.
You can't use .siblings() on $(this) because the image isn't a direct sibling of $(this).  You could use .siblings() if you got the right parent that the img was a sibling of, but that's a little more fragile than what I've proposed.  For example, this would also work, but it relies on more precise positioning of the HTML objects and any slight edits could break this code:
$(".more").click(function() {
    var id = $(this).parent().prev().attr("id");
});

or
$(".more").click(function() {
    var id = $(this).parent().siblings("img").attr("id");
});

You can't use .closest() on the  tag directly because the img isn't a parent of the .more object.
If this were my code, I'd do it like this because it's the most flexible and the least likely to break if the HTML is edited slightly and you're sure to get the right img object, even if there are more images nearby:

some text link read more

$(".more").click(function() {
    var id = $(this).closest("article").find(".target").attr("id");
});

A: Use parent().siblings() instead of siblings().siblings()
$('.more').click(function () {
    var left = $(this).parent().siblings('img').attr('id');
    alert(left);
});

See demo here

A: You can use a regular class selector:
$('article > img[id]').attr('id');


text:
Q: Weird django REST APIs behaviour We are having django application, which is hosted on AWS Elastic Beanstalk.
It is connected to RDS.
Application Server: c5.4xlarge
RDS: postgreSQL 9.5 (m5.4xlarge)
The issue is APIs are sometimes returning 500 and sometimes 200
even though the request params are exactly same.
That is causing Elastic Beanstalk to degrade every now and then.
I tested the APIs with all possible requests on my local by connecting to Cloud database.
But did not receive a single 500 error.
Same app is there on Test environment and it is not causing a single 500.
There is no load on the RDS when EB degrades.
So, it seems application is not the issue here.
Could it be due to Application Server resources?
Please help.
Cloudwatch References:


text:
Q: JPQL joins on many to many relationship I have a many to many relationship between clients and users and am trying to run a query to return me all active users and their clients where the clients should also only be active. However it returns me all inactive clients too. My query looks like this
select u from User u inner join u.clientUsers cu join cu.client c where u.active = true and c.active = true

I am sure that my join type is incorrect. Can someone help please?

A: It will return all Users that are active and have an Active client.  It is not returning clients, so when you access the user.clientUsers relationship, you get all associated clients.  Returned entities are meant to reflect the state of the entity as it is in the database, so building an incomplete entity based on your query isn't supported in the specification.  It would cause issues when tracking changes, and confusion when the real data is needed.  Try instead basing your query on active clients with active users, and then access the the user from the client (assuming the relationships are bidirectional):
"select c from Client c join c.clientUsers cu where c.active = true and cu.user.active = true"
or if you want both in one query:
 "select c, u from Client c join c.clientUsers cu join cu.user u where c.active = true and u.active = true"
The second query will return a list of object[], with each object array containing a client and its associated active User.  You can process it to map users and client collections if needed.


text:
Q: SQLite error on Create table This :
create table cartao(
    _id integer primary autoincrement,
    nome text not null
    );
create table vacina(
    _id integer primary autoincrement,
    idCartao long not null,
    nome text not null,
    descricao text not null
);
create table remedio(
    _id integer primary autoincrement,
    nome text not null
    );

SELECT * FROM CARTAO;

Return the following error :

Error: near "autoincrement": syntax error

A: [Off Topic] In SQLite, AUTOINCREMENT without the _ is OK

You forgot KEY after PRIMARY :
It should be _id integer primary key autoincrement
SQL Fiddle
SQLite (SQL.js) Schema Setup:
create table cartao(_id integer primary key autoincrement, nome text not null);

Insert into cartao(nome) Values('test 1'),('test 2');

Query 1:
SELECT * FROM CARTAO

Results:
| _id |   nome |
|-----|--------|
|   1 | test 1 |
|   2 | test 2 |

A: use AUTO_INCREMENT instead of autoincrement in the queries


text:
Q: Saving multiple strings in Android memory for use later I have an app that generates five strings every time I use it and I want these strings saved for use later, ie. when I open and run the app again.  When I use the app the second time I want to save the new five stings for use later along with the first five strings I generated the first time I ran the app.  On and on until I have say 10 sets of these five strings.
I and confused as to what it the best way to do this, Internal Memory, sql database, etc.  could someone point me to a good example on the best practices for this.  My experience with sql databases is very limited.

A: Sqlite would be the best practice in my opinion
also u could have used SharedPreferences if you had a fixed number of strings.

A: You can use SharedPreferences for storing strings

A: Android actually provides you a wide range of Storage Mechanisms like,

*

*Shared Preference

*Sqlite

*File

*External or Internal    Directories.

take a look at these: Data Storage and Data Storage Mechanisms in Android

A: From the android website: http://developer.android.com/guide/topics/data/data-storage.html#pref
To save:
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);

// Commit the edits!
editor.commit();

To load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);


text:
Q: Minoration of an expectation I'm working on the next exercise, it's an excerpt from an Oral HEC
$X$ is a random variable defined on a probabilistic space $(Ω, A, P)$ that follows the uniform law on $[a, b]$
with $1≤a <b$     prove that   $E(X+\frac{1}{X})\ge a+\dfrac{1}{a}$
to show that :
$E(X+\frac{1}{X}) \ge a+\dfrac{1}{a}$
Indeed
$$E\left(X+\frac{1}{X}\right)= \int_a^b \left(x+\frac{1}{x}\right)\left(\frac{1}{b-a}\right)\,dx = \frac{a+b}2 + \frac{\ln(b)-\ln(a)}{b-a}$$
as $(a+b)/2 >a$  a and $\frac{\ln (b) -\ln (a)}{b-a} = 1 / c$ by the theorem of finite increments
it is larger than $a$, so $1/c$ is smaller than $a.$ I get an inequality that is not in the right direction there may be another way to achieve good inequality.

A: Define $f(x):=x+1/x$. Then $f'(x)=1-1/x^2$. So on $[a,b]$ with $a\geq 1$, $f$ is monotonically increasing, hence $f\geq f(a)=a+1/a$. It follows that $E[X+1/X]\geq E[a+1/a]=a+1/a$.


text:
Q: Authentication flow steps order and captcha functionality I didn't find any good reference where the steps for authentication are defined (at least steps order).
To be more specific I am interested what sequence of steps should be:

*

*UserName verification (whether user name is found);

*Password verification;

*Credentials expired or not expired.

*Credentails temporary or not temporary

*Captcha verification.

I understand that in particular case the order of these steps are not so important but generally it will be good to know about such recommendations. Even in order to create appropriate use cases for the system.
As example it can be designed in different ways:

*

*System can provide only general message that user name or password is not correct. In case of incorrect captcha message will be the same.

*System can provide more different messages. As example incorrect captcha will provide message similar to "Incorrect captcha is entered";
Incorrect username or password message will be "user name or password is not correct". (I am not sure whether form security perspective it's ok)
And the question is what use case is better? (it will be good to provide some proof that this is better with appropriate arguments).

A: It depends on a lot of cause. But I would do it like this:
Clientside

*

*If you want, check general requirements e.g username and password lengths and prompt the user, this can be done in javascript.

Do not forget that this code will be public, meaning a hacker will see this requirements and take them in to account while preforming an attack.
Serverside

*

*Captcha verification. Do this first because if this fails there is no need to use your database for lookups.(Probably your using some kind of third party service here I assume)

*Username and password check, because this would be the second most common failure.

*Credentials expired or not expired and Credentails temporary or not temporary, any order.

Good to know:
2 and 3 could also, probably(depending on your architecture), be done in one single database lookup. If you use an SQL-database do not forget to use prepared statements.
You could also do a lot server side to detect attack attempts and restrict permissions if something is fishy. E.g temporary ban users accounts after X failed login attempts. Store ip addresses and match them to locations. E.g an American user login in from china 10 minutes later is suspicious behaviour(Facebook and others do this).
Make sure you know exactly what you do client side and server side and the execution order. A good idea can be to draw a information flow diagram. And to use a interception proxy to see what is sent. Are the passwords sent in clear?(use ssl and hash them clientside, not said you do not hash  them again(and salt) serverside so that the method can be as secret as possible)


text:
Q: jsf2 RequiredValidator.validate() bypassed but form is still validated I need to implement forms with a "save-your-work" as well as a "submit" button. The user needs to be able to save their work before it is complete. This causes problems with the validation
of required values. I have looked at the solution suggested here JSF 2.0: How to skip JSR-303 bean validation? and others like it. They require adding a parameter to the button that requires the validation
<h:commandButton>
    <f:param name="SHOW_VALIDATION" value="true" />
</h:commandButton>

And then festooning every input tag with a test
<h:inputText>
    <f:validateRequired disabled="#{!param['VALIDATE']}" />
</h:inputText>

A cleaner and more secure solution is outlined in
http://javalabor.blogspot.com/2012/02/jsf-2-conditional-validation.html. This approach was also attempted here https://community.jboss.org/thread/211982?tstart=0&_sscc=t. Cleaner because only one change is needed in the form to indicate which button should skip validation using the button's id. More secure because one is not adding a parameter to the request that is potentially manipulated and whose purpose is to bypass validation! The goal is to replace the base validator so the custom validator can detect which button is clicked and skip validation on the entire page.
The faces-config.xml is
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">

<application>
    <default-validators>
        <validator-id>javax.faces.Bean</validator-id>
    </default-validators>
    <default-validators>
        <validator-id>javax.faces.Required</validator-id>
    </default-validators>
</application>

<validator>
    <validator-id>javax.faces.Bean</validator-id>
    <validator-class>edu.wustl.mir.ctt.util.SkipBeanValidator</validator-class>
</validator>
<validator>
    <validator-id>javax.faces.Required</validator-id>
    <validator-class>edu.wustl.mir.ctt.util.SkipRequiredValidator</validator-class>
</validator>

The custom validators are
public class SkipRequiredValidator extends RequiredValidator {

    @Override
    public void validate(final FacesContext context, final UIComponent component, final Object value) {
        if (ValidatorUtil.check(context)) {
            super.validate(context, component, value);
        }
    }
}

public class SkipBeanValidator extends BeanValidator {

    @Override
    public void validate(final FacesContext context, final UIComponent component, final Object value) {
        if (ValidatorUtil.check(context)) {
            super.validate(context, component, value);
        }
    }
}

And the helper class
public class ValidatorUtil {

    private static final String VALIDATE = "VALIDATE";

    public static boolean check() {
        return check(FacesContext.getCurrentInstance());
    }

    public static boolean check(final FacesContext context) {
        final ExternalContext externalContext = context.getExternalContext();
        final Object validate = externalContext.getRequestMap().get(VALIDATE);
        if (validate != null) {
            return (Boolean) validate;
        }
        for (final Map.Entry<String, String[]> requestParameters : externalContext.getRequestParameterValuesMap()
            .entrySet()) {
            final String key = requestParameters.getKey();
            if (key.contains(":do")) {
                externalContext.getRequestMap().put(VALIDATE, Boolean.TRUE);
                return true;
            }
        }
        externalContext.getRequestMap().put(VALIDATE, Boolean.FALSE);
        return false;
    }
}

Using tomcat7 and mojarra2.2, I can see that custom Required validator is indeed replaced and super.validate() is NOT called as appropriate to the detected button id but the form is still validated for required fields.
Can anyone see what is wrong with what otherwise seems like an elegant solution?
Thanks in advance.


text:
Q: Can you explain this piece of code? Rest is ok but, I did not understand what is happening in this part:
for (x = 15; x % i ? ++i : ++k, i < x; x--, i++)
#include <stdio.h>
#include <stdlib.h>
int main() {
    int x, i = 2, k = 1;
    for (x = 15; x % i ? ++i : ++k, i < x; x--, i++) {
        x = -k + i;
        i++;
        printf("X = %d, I = %d, K = %d\n", x, i, k);
    }

    switch (x) {
      case 2: printf("Display 2.\n");
      case 5: printf("Display 5.\n");
      case 0: printf("Display 0.\n");
        break;
      default: printf("Display default\n");
    }
    system("pause");
    return 0;
}

A: This is idiotic code, but to understand it you just have to break it down:
for(x=15 ;                 // init x = 15
    x%i ? ++i : ++k, i<x ; // if x is not a multiple of i then increment i,
                           // otherwise increment k,
                           // and then exit loop if i >= x
    x--, i++)              // decrement x, increment i

A: In general, a for loop has the following structure:
for (part1; part2; part3) {
    ....
}

*

*Part 1 is a statement which is executed once, before the loop starts.

*Part 2 is the condition you check at each iteration.

*Part 3 is a statement which is executed at the end of each iteration.

So here, Part 2 is x%i ? ++i : ++k, i<x ; which checks two conditions :

*

*x%i ? ++i : ++k. This is a short way to write an if-elsestatement. It can be written as:
if (x % i)    //equivalent to : if ((x%i) == 1)
    ++i;
else
    ++k;

This means that i is incremented if x can be divided by i and k is incremented if it cannot.

*

*i < x is an obvious comparison.

A: This is composition of c++ ternary operator, comma operator and increment operator. It's equivalent function will
bool f(int x, int &i, int&k)
{
   if (x%i != 0)
   {
      ++i;
      return i != 0;
   }
   else
   {
      ++k;
      return i < x;
   }
}

And the for will be now
for(x=15 ; f(x, i, k); x--, i++)
{
    x=-k+i;
    i++;
    printf("X = %d, I = %d, K = %d\n", x, i, k);
}

A: This is the Ternary Operator (read about it on wiki)
conditionalStatement ? "returnsThisWhenStatementIsTrue" : "returnsThisWhenStatementIsFalse"

It returns ++i when "x % i" is truthy, and returns ++k otherwise.
That's all. ; )


text: Q: Generate crystal report from dynamic stored procedure I have to create crystals report from stored procedure. But my column name from stored procedure are not fixed means my stored procedure is dynamic it column name change  every time. It problem to generate the crystals report because i do not mapped column name in stored procedure to crystals report. What I have to Do? Can it possible to generate dynamic crystals report ????


text:
Q: Admin Error after Update: Specified invalid parent id (Magento_Analytics::business_intelligence) After upgrading from 2.1.17 to 2.1.18, I'm receiving this error when accessing the admin panel:
Specified invalid parent id (Magento_Analytics::business_intelligence)";i:1;s:3699:"<pre>#1 Magento\Backend\Model\Menu\Builder\Interceptor->___callPlugins() called at [var/generation/Magento/Backend/Model/Menu/Builder/Interceptor.php:39]

I can't find any references to Magento_Analytics in the codebase. Any ideas on how to fix this?
Edit: information on the Magento_Analytics module might be helpful as well, if anyone knows why this might be referenced somewhere in 2.1.18


text:
Q: Google+ within an iOS app I am trying to set Google+ to work within an iOS app I am developping. I got things set up to a certain point.
And now I see this message in the debugger:

[GPPNativeShareBuilderImpl open] User must be signed in to use the
  native sharebox.

I have to sign into Google+ but the question is where do I have to do that? I am not sure I get the meaning of this message.
Is it something I should do inside the app or outside?


text:
Q: Single, horizontally scrollable line in a pre? I have a pretty simple bit of HTML which I'm attempting (and failing miserably at) getting formatted properly. I essentially have the following element:

http://myserver.com:9000/something/REQUEST/124125125125?username=username&password=password

I essentially need to mimic what you're seeing above me in a pre. I need to have a single line of text show up as a single line of text within a pre with a horizontal scroll if necessary.
All attempts to do this so far have failed. The
 exists as a child of a :

                Behold some incredible, glowy sample text, and then a URL:

...

A: StackOverflow uses
overflow: auto;
width: auto;

With an explicit width (730px) on a parent container of the


text:
Q: For arbitary dimensions, showing that the square root of the identity matrix is diagonalizable For arbitrary size, let $A$ be a square matrix such that $A^2=I$ where $I$ is the identity matrix. Then how do I show that $A$ is diagonalizable? Also, is $A$ diagonalizable when $A^2=B$ for some arbitrary diagonalizable matrix $B$?

A: The polynomial $x^2-1$ annihilates $A$, so its minimal polynomial must be one of $x-1$, $x+1$ or $x^2-1=(x-1)(x+1)$. All of these are products of distinct linear factors, therefore $A$ is diagonalizable.
One the other hand, consider $B=-I_2$. For $A=\tiny{\begin{bmatrix}0&-1\\1&0\end{bmatrix}}$ we have $A^2=B$, but $A$ is not diagonalizable over the reals.

A: Every vector $x \in \mathbb{R}^n$ can be written as $x = \frac{1}{2}(x + Ax) + \frac{1}{2}(x - Ax)$ where $\frac{1}{2}(x + Ax)$ is in the eigenspace for $\lambda = 1$ and $\frac{1}{2}(x - Ax)$ is in the eigenspace for $\lambda = -1$.  Therefore, the eigenvectors for $\lambda = \pm 1$ span $\mathbb{R}^n$, implying that $A$ is diagonalizable.

More generally, we can apply a useful decomposition theorem: suppose $T \in L(V)$ is a linear operator, and we have pairwise relatively prime polynomials $p_1, \ldots, p_r \in F[t]$, where $F$ is the scalar field, and let $p(t) := p_1(t) \cdots p_r(t)$.  Then $\ker p(T) = \ker p_1(T) \oplus \cdots \oplus \ker p_r(T)$.
In this particular case, we can use $p_1(t) = t-1$, $p_2(t) = t+1$; so $p(t) = t^2-1$, $\ker p(A) = \ker 0 = \mathbb{R}^n$, and thus $\mathbb{R}^n = \ker(T-I) \oplus \ker(T+I)$.

(Do note, however, that these proofs only work if the scalar field does not have characteristic 2.  In fact, the statement is false over characteristic 2 scalar fields; for example, $\begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}^2 = I$ in this case but $\begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}$ is not diagonalizable.)

A: For every matrix $A$, there exists an invertible matrix $T$ such that $J:=TAT^{-1}$ is in Jordan form. It is then easily seen that
$$J^2 = TAT^{-1}TAT^{-1} = TA^2T^{-1} = TIT^{-1} = TT^{-1} = I$$
The diagonal of $J^2$ contains just the diagonal values of $J$ squared, therefore on the diagonal, so to get $I$, there can only be $1$ or $-1$ on the diagonal. It is also easily checked that on squaring, for each Jordan block, the subdiagonal is replaced by $2\lambda$ where $\lambda$ is the eigenvalue ($=$ value on the diagonal). But to be equal to the identity matrix, the subdiagonal of the square must be zero;but we've seen before that $\lambda=\pm1\ne 0$. Therefore the only way the condition can be fulfilled is if all Jordan blocks have no subdiagonal, that is, are of size $1$, which means that $J$ is actually a diagonal matrix. But that means that $A$ is diagonalizable.

A: Let $K$ be an algebraically closed field with characteristic not $2$ and $A\in M_n(K)$ be  a diagonalizable invertible matrix. We consider the equation $(*)$ $X^2=A$ where $X\in M_n(K)$.
$\textbf{Proposition}$. Then $(*)$ has at least one  solution $X$ and each solution is diagonalizable.
$\textbf{Proof}$. We may assume that $A=diag(\lambda_1I_{i_1},\cdots,\lambda_kI_{i_k})$ where the $(\lambda_i)$ are non-zero distinct.
i) Thus, $2^k$ obvious solutions are $X=diag(\pm \sqrt{\lambda_1}I_{i_1},\cdots,\pm \sqrt{\lambda_k}I_{i_k})$. Obviously, the existence stands even if $A$ is singular.
ii) Conversely, $X$ is in the form $X=diag(X_1,\cdots,X_k)$ where ${X_j}^2=\lambda_jI_{i_j}$. If $X$ is not diagonalizable, then some $X_j$ is not diagonalizable; since we may assume that $\lambda_j=1$, that implies that there is $m\geq 2$ s.t. $(\pm I_m+J_m)^2=I_m$, where $J_m$ is the nilpotent Jordan matrix of dimension $m$. Note that $(\pm I_m+J_m)^2=I_m\pm 2J_m+{J_m}^2\not =I_m$ because $charac(K)\not= 2$. That is contradictory.  $\square$


text:
Q: UDP Client on Android I have made an UDP Server on a Wi-Fi demo board and test it using and android App (UDP Sender).
I created my own UDP client apps on Android, but it doesn't work.
I created and configured well the socket port and the IPaddress but the app doesn't work and I don't know why.
PS : In the manifest I added the uses-permission to access to the Wi-Fi
her is my simple code
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Udp_Client extends Activity {

    /** Called when the activity is first created. */
    TextView txt5,txt1;
    byte[] send_data = new byte[1024];
    Button hello;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txt1   = (TextView)findViewById(R.id.textView1);
        txt5   = (TextView)findViewById(R.id.textView5);

        hello = (Button) findViewById(R.id.button1);

        hello.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {

                try {
                    client();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

         });

    }

    public void client() throws IOException{

            String str="Hello";
            int port = 50000;
         DatagramSocket client_socket = new DatagramSocket(port);
         InetAddress IPAddress =  InetAddress.getByName("192.168.0.1");

                        send_data = str.getBytes();

            DatagramPacket send_packet = new DatagramPacket(send_data,str.length(), IPAddress, port);
            //client_socket.setBroadcast(true);
            client_socket.send(send_packet);

            client_socket.close();

        }

}

  [1]: http://i.stack.imgur.com/aXPhf.png

A: I found the solution for the problem
The problem was in the manifest
Here is my new code and my manifest
The main in wich I call the UDP_Client :
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements View.OnClickListener {
    private TextView sceen = null;
    private Button launch = null;

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

        sceen = (TextView)findViewById(R.id.textView1);
        launch = (Button)findViewById(R.id.udpbutton);
        launch.setOnClickListener(this);

       launch.setOnClickListener((OnClickListener) this);

    }
           public void onClick(View v) {
               //UDP Client erstellen
               UDP_Client Client = new UDP_Client();
               Client.Message = "Your message";
                    Client.NachrichtSenden();

           }

    }

The code of my UDP_Client
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;

public class UDP_Client
{

    private InetAddress IPAddress = null;
    private String message = "Hello Android!" ;
    private AsyncTask<Void, Void, Void> async_cient;
    public String Message;

    @SuppressLint("NewApi")
    public void NachrichtSenden()
    {
        async_cient = new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected Void doInBackground(Void... params)
            {
                DatagramSocket ds = null;

                try
                {
                    byte[] ipAddr = new byte[]{ (byte) 192, (byte) 168,43, (byte) 157};
                    InetAddress addr = InetAddress.getByAddress(ipAddr);
                    ds = new DatagramSocket(5000);
                    DatagramPacket dp;
                    dp = new DatagramPacket(Message.getBytes(), Message.getBytes().length, addr, 50000);
                    ds.setBroadcast(true);
                    ds.send(dp);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    if (ds != null)
                    {
                        ds.close();
                    }
                }
                return null;
            }

            protected void onPostExecute(Void result)
            {
               super.onPostExecute(result);
            }
        };

        if (Build.VERSION.SDK_INT >= 11) async_cient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else async_cient.execute();
    }
}

The manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.udp_server"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I added the part of code in my manifest

hope that it will help someone in the future ;)

A: I think you miss this:
public void connect (InetAddress address, int port)

Of the DataGramSocket Object.
Try:
client_socket.connect(IPAddress, port);
client_socket.send(send_packet);


text:
Q: I have problem with transactional email -magento 1.9 Can anyone help me to send transactional email through the custom module and its editable with transactional email in backend template?
I want to send transactional email but it's not working.
I have created below function to send email from transactional email.
        $translate = Mage::getSingleton('core/translate');
        $translate->setTranslateInline(false);
        $receverEmail=Mage::getStoreConfig('ultimo/education_email/education_sendemail');
        $custom_template=Mage::getStoreConfig('customer/account_share/custom_template');
        $custom_identity=Mage::getStoreConfig('customer/account_share/custom_identity');

         Mage::getModel('core/email_template')
        ->setDesignConfig(array('area' => 'frontend', 'store' => $storeId))
        ->sendTransactional(
            $custom_template,
            array('name' => $fromName,'email' => $fromEmail),
            $receverEmail,
            null,
            array('name' => $params['person-name'],'email' => $params['person-email'],'school_name' => $params['school-name'],'school_address' => $params['school-address']));

        $translate->setTranslateInline(true);

A: Try it
    $storeId = Mage::app()->getStore()->getId();

    $sender = array(
      'name'  =>  $fromName,
      'email' =>  $fromEmail
    );

    $storeName = Mage::app()->getStore()->getName();

    $receverEmail = Mage::getStoreConfig('ultimo/education_email/education_sendemail', $storeId);

    $custom_template = Mage::getStoreConfig('customer/account_share/custom_template', $storeId);

    $custom_identity = Mage::getStoreConfig('customer/account_share/custom_identity',$storeId);

    $translate = Mage::getSingleton('core/translate');

    $translate->setTranslateInline(false);

    $data = array(
        'name' => $params['person-name'],
        'email' => $params['person-email'],
        'school_name' => $params['school-name'],
        'school_address' => $params['school-address']
    );

    Mage::getModel('core/email_template')->sendTransactional($custom_template, $sender, $receverEmail, $storeName, array('data'=>  $data), $storeId);

    $translate->setTranslateInline(true);


text:
Q: How to make a link apply only to the parent element of a nested div? I want to add a link to the button, but not the label elements.
I tried to disable them using a class but it doesn't work unless it's applied to a (link) tags only (i.e, a.disabled), and even then, it disables the button's link as well.
There's literally nothing I can add to this. It's a simple question. I just cannot get good answers on Google.

@keyframes show-label {
    from {
        opacity: 0%;
    }

    to {
        opacity: 100%;
    }
}

body {
    display: flex;
    flex-direction: column;
    flex: auto;
    align-items: center;
}

div.button {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    flex: auto;
    width: 20vw;
    height: 20vw;
    background-color: lightgray;
    border-radius: 10px;
}

.label {
    opacity: 0%;
}

.label:hover {
    animation: show-label 500ms forwards;
}

div.label {
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 0px 0px 10px 10px;
}

p.label {
    color: white;
    font-size: min(1.8vw, 18.17px);
    text-align: center;
}

        <link rel="stylesheet"
              href="style.css">

the big

A: You've wrapped both the button and its label in an  tag and it's nothing like adding a link to the button. Please describe the style you want more clearly. Link in not a style.
If you want the link to be on button only, you can take the label out.
I suggest this structure and style for what I understood from your question and it changes your structure:

@keyframes show-label {
    from {
        opacity: 0%;
    }

    to {
        opacity: 100%;
    }
}

body {
    display: flex;
    flex-direction: column;
    flex: auto;
    align-items: center;
}

div.wrapper {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    flex: auto;
    width: 20vw;
    height: 20vw;
    background-color: lightgray;
    border-radius: 10px;
}

a.button {
    height: 100%;
    transition: 0.5s;
}

a.button:hover {
    background-color: #FFFFFF;
    transition: 0.5s;
}

.label {
    opacity: 0%;
}

.label:hover {
    animation: show-label 500ms forwards;
}

div.label {
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 0px 0px 10px 10px;
}

p.label {
    color: white;
    font-size: min(1.8vw, 18.17px);
    text-align: center;
}

        <link rel="stylesheet"
              href="style.css">

the big

NOTE: Do not hard code styles in your html when you have a style sheet, I left the style="max-width: 157.39px; max-height: 157.39px; as it was in your html but it's better to move it to the style.css file.


text:
Q: How to get HTML with expanded containers using Python? When I get HTML of the page, e.g
response = urllib2.urlopen('http://www.wunderground.com/us/fl/miami/precipitation')
html = response.read()

I get HTML with collapsed containers, e.g

6-Hour Precipitation Forecast

while the real HTML looks like that:

Clearly, I need to extract 6-hour forecast, which I cannot do having it collapsed into

I will be very thankful if you can help me with this issue. Thank you

A: The content is loaded dynamically using ajax. You can sniff this request with Chrome. Press F12 -> Network -> XHR and look at requests, one of them (wwir.json) returns a nice json that you can parse using:
 import json
 weather = json.loads(response)

It looks like they use API key from api.weather.com, which probably means you should get your own.


text:
Q: Multiple whereHas calls are not being aggregated together I've got multiple calls to whereHas() on an instance of \Illuminate\Database\Query\Builder ($cars):
$cars->whereHas("finance", function (Eloquent\Builder $query) {
    $query->where('term'...)
}
$cars->whereHas("finance", function (Eloquent\Builder $query) {
    $query->where('payment'...)
}

Is there some way to aggregate the where(s) together without needing to do all the where calls within the containing whereHas?
The SQL query being executed:
SELECT id
FROM `cars`
WHERE EXISTS
    (SELECT `finance`.`payment` as payment
    FROM `finance`
     INNER JOIN `car_finance` ON `finance`.`id` = `car_finance`.`finance_id`
     WHERE `car_finance`.`car_id` = `cars`.`id`
       AND `payment` >= 50)
  AND EXISTS
    (SELECT *
     FROM `finance`
     INNER JOIN `car_finance` ON `finance`.`id` = `car_finance`.`finance_id`
     WHERE `car_finance`.`car_id` = `cars`.`id`
       AND `payment` <= 200)
  AND EXISTS
    (SELECT *
     FROM `finance`
     INNER JOIN `car_finance` ON `finance`.`id` = `car_finance`.`finance_id`
     WHERE `car_finance`.`car_id` = `cars`.`id`
       AND `term` = 48)
  AND EXISTS
    (SELECT *
     FROM `finance`
     INNER JOIN `car_finance` ON `finance`.`id` = `car_finance`.`finance_id`
     WHERE `car_finance`.`car_id` = `cars`.`id`
       AND `deposit` = 1000)
  AND `active` = 1

The SQL query that I would like to be executed:
SELECT *
        FROM cars
WHERE EXISTS
    (SELECT *
        FROM `finance`
     INNER JOIN `car_finance` ON `finance`.`id` = `car_finance`.`finance_id`
     WHERE `car_finance`.`car_id` = `cars`.`id`
    AND deposit = 1000
    AND term = 48
    AND payment >= 50
    AND payment <= 200)
  AND active = 1

A: Your question it's not clear but I think you want this:
$cars->whereHas("finance", function ($query) {
   $query->where('deposit', 1000)->where('term', 48)
     ->whereBetween('payment', 50, 200);
})->where('active', 1)->get();


text:
Q: Restructure the date in multiple columns at the same time in R I have multiple data frames, each of which represents data from the year 2016 - 2019 (i.e., df.16, df.17, df.18, df.19), and I would like to transform the date column in each from YYYY/MM/DD 00:00:00 to simply show the month. I'd like to accomplish this by making a new column month and doing this concurrently to all dataframes. I think I thould use lapply although I am not entire sure. My code is as follows:
Making the list:
df.list <- list(df.16, df.17, df.18, df.19, df.20)
Applying the function:
lapply(df.list, function(x) {x$month <- month(date); x})
However, I continually get the following error: Error in as.POSIXlt.default(x, tz = tz(x)) :  do not know how to convert 'x' to class "POSIXlt"
Any help would be appreciated!

A: I used the following to solve the problem:
new_df_list <- lapply(df.list, function(df)  within(df, month <- month(date)))

A: Another option is transform where we don't have to use the anonymous function
new_df_list <- lapply(df.list, transform, month = month(date))


text:
Q: How to set a cookie through CORS I've reviewed other related posts and none are working for me. I am using vue on the client-side and node on the server-side.
I've tried the suggested method in other posts of using the cors library without success.
One would think the below would allow me to send requests from my client localhost:8080 to my server, localhost:3000 but all posts are failing.
const cors = require("cors");
if (process.env.ENV !== "prod") {
  let corsOptions = {
    origin: ["http://localhost:8080"],
    credentials: true,
    optionsSuccessStatus: 200,
  };
  app.use(cors(corsOptions));
}

Here is my controller for setting the cookie.
router.route("/login").post(async (req, res) => {
  //Authenticate users
  const user = await Users.findOne({ where: { email: req.body.email } });

  if (user == null) {
    return res.status(400).send("Cannot find user!");
  }
  try {
    if (await bcrypt.compare(req.body.password, user.password)) {
      const userInfo = {
        username: user.username,
        email: user.email,
        age: user.age,
      };
      const accessToken = generateAccessToken(userInfo);

      const refreshToken = jwt.sign(userInfo, process.env.REFRESH_TOKEN_SECRET);
      res.cookie("token", accessToken, {
        maxAge: 300000,
        secure: true,
        httpOnly: true,
        sameSite: "none",
      });
      res.status(200).send("Logged in!");
    } else {
      res.send("Incorrect email or password!");
    }
  } catch {
    res.status(500).send();
  }
});

Every answer on this site more or less loops back to app.use(cors), for whatever reason it does not work for me.

A: This may be because for cross domain cookies you are setting {sameSite: true} and {secure: true} but in your example you are doing this on http://localhost so it will not set any cookie. Please refer following link for requirements.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
Also set proper headers i.e.  Access-Control-Allow-Credentials,  Access-Control-Allow-Origin, Access-Control-Allow-Headers
For reference you can use mkcert for secure connection on localhost.
I do also suggest to use same top level domain for frontend and backend and use subdomain.
One more thing to note here is that i think Chrome will not set the cookie if the domain has a port in it.so please give it a try.

A: I managed to resolve the issue for any who may land here later. I moved up my declaration of cookieparser to above where I initialized my sequelize connection. I also added withCredentials to my axios post. In doing both my cookies are now both setting correctly and are able to be accesssed.
const express = require("express");
require("dotenv").config();
const cors = require("cors");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const cookieParser = require("cookie-parser");
app.use(cookieParser());
const port = process.env.PORT || 8080;
const lib = require("./lib"); //This is all custom functions
const sql = require("./database");

      onSubmit() {
        let loginInfo = {
          email: email.value,
          password: password.value,
        };
        axios
          .post("http://localhost:3000/user/login", loginInfo, {
            withCredentials: true,
          })
          .then(() =>
            $q.notify({
              color: "green-4",
              textColor: "white",
              icon: "cloud_done",
              message: "Account successfully created!",
            })
          )
          .catch(() =>
            $q.notify({
              color: "red-5",
              textColor: "white",
              icon: "warning",
              message: "Email or username already taken!",
            })
          );
      },


text:
Q: How can I set custom variables in tmux? I have the following section in my tmux.conf file:
bind -r H resize-pane -L 10 # defaults to Ctrl-LeftArrow
bind -r J resize-pane -D 10
bind -r K resize-pane -U 10
bind -r L resize-pane -R 10

Id like to set a custom variable called step and assign it to 10 so I can reference it as:
bind -r H resize-pane -L $step

I don't know how to do that in tmux configuration file, but I think it should be possible.

A: Place this line in your config:
TMUX_STEP=10

And use it as such:
bind -r H resize-pane -L $TMUX_STEP


text:
Q: angular Error: $injector:modulerr Module Error I am trying to run one of Angular Materials examples but for the life of me I can't figure out why I'm getting this error.
The error I am getting is Error: $injector:modulerr Module Error
This is the error report I got: link
Any ideas what the issue could be? I practically copy-pasted this from their examples website.
Here is the code:

angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])

.controller('AppCtrl', function($scope) {

});
.buttondemoBasicUsage section {
  background: #f7f7f7;
  border-radius: 3px;
  text-align: center;
  margin: 1em;
  position: relative !important;
  padding-bottom: 10px; }

.buttondemoBasicUsage md-content {
  margin-right: 7px; }

.buttondemoBasicUsage section .md-button {
  margin-top: 16px;
  margin-bottom: 16px; }

.buttondemoBasicUsage .label {
  position: absolute;
  bottom: 5px;
  left: 7px;
  font-size: 14px;
  opacity: 0.54; }

  <md-content>

      <md-button class="md-icon-button md-primary" aria-label="Settings">
        <md-icon md-font-icon="icon-home"></md-icon>
      </md-button>
      <md-button class="md-icon-button md-accent" aria-label="Favorite">
        <md-icon md-font-icon="icon-home"></md-icon>
      </md-button>
      <md-button class="md-icon-button" aria-label="More">
        <md-icon md-font-icon="icon-home"></md-icon>
      </md-button>
      <md-button href="http://google.com" title="Launch Google.com in new window" target="_blank" ng-disabled="true" aria-label="Google.com" class="md-icon-button launch">
        <md-icon md-font-icon="icon-home"></md-icon>
      </md-button>

Icon Button

  </md-content>

A: Change the module script to remove the reference to material.svgAssetsCache and the demo will run but without the final row of buttons - which reference "local" image resources.
If you grab a copy of the icons(bower install material-design-icons) and locate the relevant 24px .svg files and pop them in (say) /img/icons/ from the root of your web site (adjusting file names and path as required) then even this section will work just fine.
The demo is rather off-putting when you think about it as it is likely to be chosen as a first stab at trying things out yet it only works within the CodePen sand-tray.

A: Most probably you are missing svg icons

A: Did you reference the .js file related to your angular app?
I can just see the external javascript dependencies but nothing related to your app - controller. Take care about the order you're importing it

A: You need to add:
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">


text:
Q: Native base component's theme is not updating when the theme changes of the App I am using native base + react-navigation in an app and need to change the theme of the app. As soon as I change the theme the react-navigation update that easily but the problem is that the native base component theme does not change. It looks odd to the user.
I had used this code to change the theme of the app
    <StyleProvider style={getTheme(theme === 'LIGHT' ? platform : material)}>
                <Container>
                    <NavigationContainer
                        theme={theme === 'LIGHT' ? DefaultTheme : MyThemeDark}>
                        <Stack.Navigator
                            initialRouteName={isProfile ? 'Root' : 'Selection'}>
                              ..................

                        </Stack.Navigator>
                    </NavigationContainer>
                </Container>
    </StyleProvider>

As I said React navigation theme is updating correctly but the native base theme is not updating.

A: For native base 3, to change the theme, you can use the React Native hook useColorScheme to get the current theme of the device and update the theme using native base method setColorMode.
I believe the code needs to be added as child component of NativeBaseProvider. For example, may not work in App.js if you define NativeBaseProvider there.
import React from "react";
import { useColorMode } from 'native-base';
import { useEffect } from 'react';
import { Alert, useColorScheme } from 'react-native';

export const UseColorMode = () => {
  const colorScheme = useColorScheme();
  const {
    setColorMode,
  } = useColorMode();

  useEffect(() => {
    if (colorScheme) {
      Alert.alert(`${colorScheme}`)
      setColorMode(colorScheme);
    }
  }, [colorScheme, setColorMode])

  return (<></>)
}

App.js
const App = () => {
  return (<NativeBaseProvider>
    <UseColorMode/>
  </NativeBaseProvider>)
}


text:
Q: How can I know how many files synced in desktop client software Resilio Sync? I know I can see how many files synced in mobile app about Resilio Sync by clicking the i icon near by a folder name.  You can see it at https://help.getsync.com/hc/en-us/articles/206217345-How-to-link-my-mobile-device-to-my-desktop-computer-via-My-Devices and the following image.
But in desktop software of Resilio Sync such as Windows 7, I can't find a the i icon to display how many files in a folder are synced, how can I do ? Thans!


text:
Q: Batch script to call executable and exit if it hangs So I need to write a batch script that starts an executable and exits the script as soon as the executable finishes (so no ip pinging wait scripts) but will automatically kill the exe and exit the script after 30 minutes if the executable is still running (hung, not responding, etc)
Here is what I have so far. The find statement correctly outputs the number of processes that match, but my problem is that the ERRORLEVEL always returns 0, regardless of whether or not there are matching executables running.
I am fairly new to batch scripting, so it is very possible I am overlooking some really simple thing.
@echo off
start calc.exe

REM loop 600 times, each loop being 3 seconds (30 minutes total)
FOR /L %%A IN (1,1,600) DO (

   REM find the running executable
   tasklist | find /I /C "calc.exe" > nul
   echo %ERRORLEVEL%

   Rem exit the script if no executable is found (i.e it has run successfully)
   if %ERRORLEVEL% eq 1 EXIT

   Rem pause for 3 seconds
   ping 1.1.1.1 -n 1 -w 3000 > nul
)

REM kill executable if we haven't exited yet
taskkill /f /im calc.exe

Thanks in advance!

A: in a code block you need always delayed expansion:
@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
start calc.exe

REM loop 600 times, each loop being 3 seconds (30 minutes total)
FOR /L %%A IN (1,1,600) DO (

   REM find the running executable
   tasklist | find /I /C "calc.exe" > nul
   echo !ERRORLEVEL!

   Rem exit the script if no executable is found (i.e it has run successfully)
   if !ERRORLEVEL! eq 1 EXIT

   Rem pause for 3 seconds
   ping 1.1.1.1 -n 1 -w 3000 > nul
)

REM kill executable if we haven't exited yet
taskkill /f /im calc.exe

A: Change your batch script call to tasklist and find somewhat:
tasklist /FI "IMAGENAME eq calc.exe" | find /I "calc.exe" > nul

This works correctly if I test both with and without a copy of Calculator running (Win7 64 in a command window).


text:
Q: PhoneGap & Sencha Touch 2 loading screen Im building a sencha touch 2 phonegap based app and my app pulls JSON data from a remote server. Currently the phonegap native load screen appears until the device is ready, and then the sencha touch 2 load screen appears until sencha touch 2 is ready.
I'd like the native phonegap screen to appear until everything is loaded, including sencha touch 2.
I've googled around for a solution, but can't find anything. Is there a method available to tell phonegap to wait for sencha touch 2 before hiding the load screen?
Thanks.

A: On iOS you can set AutoHideSplashScreen to NO in your Cordova.plist, and later hide your splashscreen using
navigator.splashscreen.hide();
On Android you can do something similar, Simon Mac Donald has a guide on this:
http://simonmacdonald.blogspot.nl/2012/04/phonegap-android-splashscreen-just-got.html