text:
Q: How to remove a TextView that was added dynamically So I have a snippet of code where I create a textView on a user's click on a button. Since it was created after runtime I'm unsure what the ID is. But what I'm trying to do is have the option of deleting the last textView that is added and also clear all of the TextViews that were added. Thank you
private TextView createNewTextView(String text)
    {
        ArraySize++;
        final LinearLayout mLayout=findViewById(R.id.linearLayout);
        String newLine=System.getProperty("line.separator");
        final LinearLayout.LayoutParams lparams =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        ViewGroup.LayoutParams params=(RelativeLayout.LayoutParams) mLayout.getLayoutParams();
        final TextView textView=new TextView(this);
        textView.setLayoutParams(lparams);
        textView.setText("New texT:: "+text+newLine);
        listOfNames.add(text);
        return textView;
    }

A: you could create a XML File in this path res/values/ids.xml;
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="view_1" type="id"/>
</resources>

then in Java you add the id, like this
textView.setId(R.id.view_1);

and when you want to remove it
LinearLayout mLayout=findViewById(R.id.linearLayout);//to find in this specific view
TextView textView = (TextView)mLayout.findViewById(R.id.view_1);
mLayout.removeView(textView);

A: You use removeViewAt with the index
final LinearLayout mLayout=findViewById(R.id.linearLayout)
mLayout.removeViewAt(mLayout.getChildCount()-1); // get the last view

//or using index counter variable
//mLayout.removeViewAt(ArraySize-1); // adjust the value accordingly

or you can fetch the view and remove it using removeView
final LinearLayout mLayout=findViewById(R.id.linearLayout)
View v = mLayout.getChildAt(mLayout.getChildCount()-1);
mLayout.removeView(v);

A: As mentioned in this question, you can simply use
((ViewGroup) textView.getParent()).removeView(textView);

A: To remove all views:
mLayout.removeAllViews();

To remove last TextView:
mLayout.removeView(mLayout.getChildAt(mLayout.getChildCount()-1));

A: You can give an Id as edgar mentions or use the View.setTag , you can then find views by tag using viewGroup.findViewWithTag.


text:
Q: Ring buffer mode for GPIO Beaglebone Black libpruio allows using the ring buffer mode to sample the analog inputs with a constant time interval. Is it possible to use the ring buffer mode to sample and store the values of selected analog inputs AND a the states of a few selected GPIO pins?

A: Yes, that's possible. At least with the current version 0.4 compiled from source:
github.com/dtjf/libpruio
The GPIO sampling may be a little slower than in IO mode, depending on the ADC sampling rate.
Other actions like PWM, CAP, QEP and GPIO.output are also possible, in RB as well as MM mode. (In MM you'll need a second thread to handle that.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: proving if $\sum_{n=2}^{\infty} \frac{n\cdot \cos(2n)}{n^2 + 11} + \frac{\cos(\pi n)}{\ln(n)\cdot \ln(n^n + n)}$ converge conditionally or absolutely I have already proven that $$\sum_{n=2}^{\infty}\frac{\cos(\pi n)}{\ln(n)\cdot \ln(n^n + n)}$$ conditionally converge and $$\sum_{n=2}^{\infty} \frac{n\cdot \cos(2n)}{n^2 + 11}$$ converge, hence $$\sum_{n=2}^{\infty} \frac{n\cdot \cos(2n)}{n^2 + 11} + \frac{\cos(\pi n)}{\ln(n)\cdot \ln(n^n + n)}$$ converge, but I wasn't able to determine whether it is conditionally or absolutely.

If I can prove that $$\sum_{n=2}^{\infty} \frac{n\cdot \cos(2n)}{n^2 + 11}$$ converge absolutely, then using the triangle inequality I get $$-\sum_{n=2}^{\infty}\left|\frac{\cos(\pi n)}{\ln(n)\cdot \ln(n^n + n)}\right| \le \sum_{n=2}^{\infty}\left|\frac{n\cdot \cos(2n)}{n^2 + 11}\right| - \sum_{n=2}^{\infty} \left|\frac{n\cdot \cos(2n)}{n^2 + 11} + \frac{\cos(\pi n)}{\ln(n)\cdot \ln(n^n + n)}\right|$$ which means if $\sum_{n=2}^{\infty}\left|\frac{n\cdot \cos(2n)}{n^2 + 11} + \frac{\cos(\pi n)}{\ln(n)\cdot \ln(n^n + n)}\right|$ converged I would have reached a contradiction. But I wasn't able to find a way to prove that $\sum_{n=2}^{\infty} \frac{n\cdot \cos(2n)}{n^2 + 11}$ converge absolutely nor that it  conditionally converge, in which case my attempt to prove this won't work

A: $\sum_{n = 2}^{\infty} \left \lvert \frac{n \cdot cos(2 \cdot n)}{n^{2} + 11} \right \rvert \sim $(in terms of convergence) $\sum_{n = 2}^{\infty} \left \lvert \frac{n \cdot cos(2 \cdot n)}{n^{2}} \right \rvert = \sum_{n = 2}^{\infty} \left \lvert \frac{cos(2 \cdot n)}{n} \right \rvert$. And $\sum_{n = 2}^{\infty} \left \lvert \frac{cos(2 \cdot n)}{n} \right \rvert > \sum_{n = 2}^{\infty} \frac {cos^2(2 \cdot n)}{n} = \sum_{n = 2}^{\infty} \frac {1 - cos(4 \cdot n)}{2 \cdot n}$, which, obviously diverges, because $\sum_{n = 2}^{\infty} \frac{1}{n}$ diverges. So $\sum_{n = 2}^{\infty}  \frac{n \cdot cos(2 \cdot n)}{n^{2} + 11}$ converges conditionally. Howewer, $\lvert cos(\pi \cdot n) \rvert = 1$ for natural n, and $\sum_{n = 4}^{\infty} \frac{1}{ln(n) * ln(n^{n} + n)}$ converges, so $\sum_{n = 4}^{\infty} \frac{cos(\pi \cdot n)}{ln(n) * ln(n^{n} + n)}$ converges absoulutely. So the series in your question converge conditionally, because  $\sum_{n = 2}^{\infty}  \frac{n \cdot cos(2 \cdot n)}{n^{2} + 11}$ converges conditionally, $\sum_{n = 4}^{\infty} \frac{cos(\pi \cdot n)}{ln(n) * ln(n^{n} + n)}$ converges absoulutely.


text:
Q: libpng: C compiler cannot create executables I am trying to call ./configure command. But, it shows this error:
C compiler cannot create executables.

Here the output:
checking for a BSD-compatible install... /home/linuxbrew/.linuxbrew/bin/ginstall -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /home/linuxbrew/.linuxbrew/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking whether to enable maintainer-specific portions of Makefiles... no
checking for gcc... gcc
checking whether the C compiler works... no
configure: error: C compiler cannot create executables
See `config.log' for more details

I checked the config.log, it can detect gcc installed but it can't find conftest.c file. I already tried:
sudo apt-get update
sudo apt-get install build-essential

But it still shows the error. I also checked that my libc6 is already installed in the newest version.
How to solve it?
This is the config.log:
This file contains any messages produced by compilers while
running configure, to aid debugging if configure makes a mistake.

It was created by libpng configure 1.6.32, which was
generated by GNU Autoconf 2.69.  Invocation command line was

  $ ./configure

## --------- ##
## Platform. ##
## --------- ##

hostname = MP3C-ISIT-048
uname -m = x86_64
uname -r = 4.4.0-116-generic
uname -s = Linux
uname -v = #140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018

/usr/bin/uname -p = unknown
/bin/uname -X     = unknown

/bin/arch              = unknown
/usr/bin/arch -k       = unknown
/usr/convex/getsysinfo = unknown
/usr/bin/hostinfo      = unknown
/bin/machine           = unknown
/usr/bin/oslevel       = unknown
/bin/universe          = unknown

PATH: /home/shrinivasan/anaconda2/bin
PATH: /usr/local/MATLAB/R2016b/bin/matlab
PATH: /usr/local/cuda/bin
PATH: /home/linuxbrew/.linuxbrew/bin
PATH: /home/linuxbrew/.linuxbrew/sbin
PATH: /home/shrinivasan/bin
PATH: /home/shrinivasan/.local/bin
PATH: /usr/local/sbin
PATH: /usr/local/bin
PATH: /usr/sbin
PATH: /usr/bin
PATH: /sbin
PATH: /bin
PATH: /usr/games
PATH: /usr/local/games
PATH: /snap/bin
PATH: /usr/lib
PATH: /usr/local/cuda/bin

## ----------- ##
## Core tests. ##
## ----------- ##

configure:2358: checking for a BSD-compatible install
configure:2426: result: /home/linuxbrew/.linuxbrew/bin/ginstall -c
configure:2437: checking whether build environment is sane
configure:2492: result: yes
configure:2643: checking for a thread-safe mkdir -p
configure:2682: result: /home/linuxbrew/.linuxbrew/bin/mkdir -p
configure:2689: checking for gawk
configure:2705: found /usr/bin/gawk
configure:2716: result: gawk
configure:2727: checking whether make sets $(MAKE)
configure:2749: result: yes
configure:2778: checking whether make supports nested variables
configure:2795: result: yes
configure:2925: checking whether to enable maintainer-specific portions of Makefiles
configure:2934: result: no
configure:3014: checking for gcc
configure:3030: found /usr/bin/gcc
configure:3041: result: gcc
configure:3270: checking for C compiler version
configure:3280: gcc --version >&5
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

configure:3291: $? = 0
configure:3280: gcc -v >&5
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 5.4.0-6ubuntu1~16.04.9' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-5-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-5-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-5-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.9)
configure:3291: $? = 0
configure:3311: checking whether the C compiler works
configure:3333: gcc    conftest.c /media/Data/Libs >&5
/usr/bin/ld: cannot find /media/Data/Libs: File format not recognized
collect2: error: ld returned 1 exit status
configure:3337: $? = 1
configure:3375: result: no
configure: failed program was:
| /* confdefs.h */
| #define PACKAGE_NAME "libpng"
| #define PACKAGE_TARNAME "libpng"
| #define PACKAGE_VERSION "1.6.32"
| #define PACKAGE_STRING "libpng 1.6.32"
| #define PACKAGE_BUGREPORT "png-mng-implement@lists.sourceforge.net"
| #define PACKAGE_URL ""
| #define PACKAGE "libpng"
| #define VERSION "1.6.32"
| /* end confdefs.h.  */
|
| int
| main ()
| {
|
|   ;
|   return 0;
| }
configure:3380: error: in `/home/shrinivasan/Documents/anneke/software/libpng-1.6.32':
configure:3382: error: C compiler cannot create executables
See `config.log' for more details

## ---------------- ##
## Cache variables. ##
## ---------------- ##

ac_cv_env_CCASFLAGS_set=
ac_cv_env_CCASFLAGS_value=
ac_cv_env_CCAS_set=
ac_cv_env_CCAS_value=
ac_cv_env_CC_set=
ac_cv_env_CC_value=
ac_cv_env_CFLAGS_set=
ac_cv_env_CFLAGS_value=
ac_cv_env_CPPFLAGS_set=
ac_cv_env_CPPFLAGS_value=
ac_cv_env_CPP_set=
ac_cv_env_CPP_value=
ac_cv_env_LDFLAGS_set=
ac_cv_env_LDFLAGS_value=
ac_cv_env_LIBS_set=set
ac_cv_env_LIBS_value=/media/Data/Libs
ac_cv_env_LT_SYS_LIBRARY_PATH_set=
ac_cv_env_LT_SYS_LIBRARY_PATH_value=
ac_cv_env_PNG_COPTS_set=
ac_cv_env_PNG_COPTS_value=
ac_cv_env_build_alias_set=
ac_cv_env_build_alias_value=
ac_cv_env_host_alias_set=
ac_cv_env_host_alias_value=
ac_cv_env_target_alias_set=
ac_cv_env_target_alias_value=
ac_cv_path_install='/home/linuxbrew/.linuxbrew/bin/ginstall -c'
ac_cv_path_mkdir=/home/linuxbrew/.linuxbrew/bin/mkdir
ac_cv_prog_AWK=gawk
ac_cv_prog_ac_ct_CC=gcc
ac_cv_prog_make_make_set=yes
am_cv_make_support_nested_variables=yes

## ----------------- ##
## Output variables. ##
## ----------------- ##

ACLOCAL='${SHELL} /home/shrinivasan/Documents/anneke/software/libpng-1.6.32/missing aclocal-1.15'
AMDEPBACKSLASH=''
AMDEP_FALSE=''
AMDEP_TRUE=''
AMTAR='$${TAR-tar}'
AM_BACKSLASH='\'
AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)'
AM_DEFAULT_VERBOSITY='1'
AM_V='$(V)'
AR=''
AS=''
AUTOCONF='${SHELL} /home/shrinivasan/Documents/anneke/software/libpng-1.6.32/missing autoconf'
AUTOHEADER='${SHELL} /home/shrinivasan/Documents/anneke/software/libpng-1.6.32/missing autoheader'
AUTOMAKE='${SHELL} /home/shrinivasan/Documents/anneke/software/libpng-1.6.32/missing automake-1.15'
AWK='gawk'
CC='gcc'
CCAS=''
CCASDEPMODE=''
CCASFLAGS=''
CCDEPMODE=''
CFLAGS=''
CPP=''
CPPFLAGS=''
CYGPATH_W='echo'
DEFS=''
DEPDIR=''
DFNCPP=''
DLLTOOL=''
DO_INSTALL_LIBPNG_CONFIG_FALSE=''
DO_INSTALL_LIBPNG_CONFIG_TRUE=''
DO_INSTALL_LIBPNG_PC_FALSE=''
DO_INSTALL_LIBPNG_PC_TRUE=''
DO_INSTALL_LINKS_FALSE=''
DO_INSTALL_LINKS_TRUE=''
DO_PNG_PREFIX_FALSE=''
DO_PNG_PREFIX_TRUE=''
DSYMUTIL=''
DUMPBIN=''
ECHO_C=''
ECHO_N='-n'
ECHO_T=''
EGREP=''
EXEEXT=''
FGREP=''
GREP=''
HAVE_CLOCK_GETTIME_FALSE=''
HAVE_CLOCK_GETTIME_TRUE=''
HAVE_LD_VERSION_SCRIPT_FALSE=''
HAVE_LD_VERSION_SCRIPT_TRUE=''
HAVE_SOLARIS_LD_FALSE=''
HAVE_SOLARIS_LD_TRUE=''
INSTALL_DATA='${INSTALL} -m 644'
INSTALL_PROGRAM='${INSTALL}'
INSTALL_SCRIPT='${INSTALL}'
INSTALL_STRIP_PROGRAM='$(install_sh) -c -s'
LD=''
LDFLAGS=''
LIBOBJS=''
LIBS='/media/Data/Libs'
LIBTOOL=''
LIPO=''
LN_S=''
LTLIBOBJS=''
LT_SYS_LIBRARY_PATH=''
MAINT='#'
MAINTAINER_MODE_FALSE=''
MAINTAINER_MODE_TRUE='#'
MAKEINFO='${SHELL} /home/shrinivasan/Documents/anneke/software/libpng-1.6.32/missing makeinfo'
MANIFEST_TOOL=''
MKDIR_P='/home/linuxbrew/.linuxbrew/bin/mkdir -p'
NM=''
NMEDIT=''
OBJDUMP=''
OBJEXT=''
OTOOL64=''
OTOOL=''
PACKAGE='libpng'
PACKAGE_BUGREPORT='png-mng-implement@lists.sourceforge.net'
PACKAGE_NAME='libpng'
PACKAGE_STRING='libpng 1.6.32'
PACKAGE_TARNAME='libpng'
PACKAGE_URL=''
PACKAGE_VERSION='1.6.32'
PATH_SEPARATOR=':'
PNGLIB_MAJOR='1'
PNGLIB_MINOR='6'
PNGLIB_RELEASE='32'
PNGLIB_VERSION='1.6.32'
PNG_ARM_NEON_FALSE=''
PNG_ARM_NEON_TRUE=''
PNG_COPTS=''
PNG_INTEL_SSE_FALSE=''
PNG_INTEL_SSE_TRUE=''
PNG_MIPS_MSA_FALSE=''
PNG_MIPS_MSA_TRUE=''
PNG_POWERPC_VSX_FALSE=''
PNG_POWERPC_VSX_TRUE=''
PNG_PREFIX=''
POW_LIB=''
RANLIB=''
SED=''
SET_MAKE=''
SHELL='/bin/bash'
STRIP=''
SYMBOL_PREFIX=''
VERSION='1.6.32'
ac_ct_AR=''
ac_ct_CC='gcc'
ac_ct_DUMPBIN=''
am__EXEEXT_FALSE=''
am__EXEEXT_TRUE=''
am__fastdepCCAS_FALSE=''
am__fastdepCCAS_TRUE=''
am__fastdepCC_FALSE=''
am__fastdepCC_TRUE=''
am__include=''
am__isrc=''
am__leading_dot='.'
am__nodep=''
am__quote=''
am__tar='$${TAR-tar} chof - "$$tardir"'
am__untar='$${TAR-tar} xf -'
binconfigs=''
bindir='${exec_prefix}/bin'
build=''
build_alias=''
build_cpu=''
build_os=''
build_vendor=''
datadir='${datarootdir}'
datarootdir='${prefix}/share'
docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
dvidir='${docdir}'
exec_prefix='NONE'
host=''
host_alias=''
host_cpu=''
host_os=''
host_vendor=''
htmldir='${docdir}'
includedir='${prefix}/include'
infodir='${datarootdir}/info'
install_sh='${SHELL} /home/shrinivasan/Documents/anneke/software/libpng-1.6.32/install-sh'
libdir='${exec_prefix}/lib'
libexecdir='${exec_prefix}/libexec'
localedir='${datarootdir}/locale'
localstatedir='${prefix}/var'
mandir='${datarootdir}/man'
mkdir_p='$(MKDIR_P)'
oldincludedir='/usr/include'
pdfdir='${docdir}'
pkgconfigdir=''
prefix='NONE'
program_transform_name='s,x,x,'
psdir='${docdir}'
sbindir='${exec_prefix}/sbin'
sharedstatedir='${prefix}/com'
sysconfdir='${prefix}/etc'
target_alias=''

## ----------- ##
## confdefs.h. ##
## ----------- ##

/* confdefs.h */
#define PACKAGE_NAME "libpng"
#define PACKAGE_TARNAME "libpng"
#define PACKAGE_VERSION "1.6.32"
#define PACKAGE_STRING "libpng 1.6.32"
#define PACKAGE_BUGREPORT "png-mng-implement@lists.sourceforge.net"
#define PACKAGE_URL ""
#define PACKAGE "libpng"
#define VERSION "1.6.32"

configure: exit 77

A: As we can see from the config.log, gcc is being invoked with an additional argument /media/Data/Libs which it is interpreting as a library file that it should attempt to link:
configure:3333: gcc    conftest.c /media/Data/Libs >&5
/usr/bin/ld: cannot find /media/Data/Libs: File format not recognized

Looking further, we can see that this is being picked up from your environment via autoconf's ac_cv_env_LIBS_value :
ac_cv_env_LDFLAGS_set=
ac_cv_env_LDFLAGS_value=
ac_cv_env_LIBS_set=set
ac_cv_env_LIBS_value=/media/Data/Libs
ac_cv_env_LT_SYS_LIBRARY_PATH_set=
ac_cv_env_LT_SYS_LIBRARY_PATH_value=

This suggests you have defined an environment variable LIBS=/media/Data/Libs, and since /media/Data/Libs is presumably a directory, its format is unrecognized as a library file by ld
Likely LIBS=/media/Data/Libs is unrelated to building this software and LIBS is simply a name you have used for a variable in some other context - this is a good reminder to avoid all-caps names for such variables.
For now, you can just execute unset LIBS in the shell and then re-run ./configure


text:
Q: Print office documents without opening Hello everyone I have currently developed a windows service which gets installed on a server machine and watches a particular folder. When a .csv file is added to the folder it grabs that file, reads it and the creates Excel file for each of the records found inside .csv file. As this is OpenXML document (Excel file) i can easily create it without having office installed on the server machine. What I want to do now is to send those generated excel files to the printer which is attached to the server machine without opening them. I know it might be impossible, but are there any chances to print those files without installing office or maybe OpenXML SDK can help? I am really stacked on this as there is no chance to install anything on server except the windows service which I developed.

A: You're looking for Process.Start, setting the Verb on the ProcessStartInfo you pass in.
As long as there's an app registered as handler for the verb "Print", then the item should print.
see: ShellExecute equivalent in .NET

A: To play music at home, you inevitably need an instrument. That's a logical rule. Not only office, but any other special document format won't work until at least you install their distributed libraries. Therefore I think there is no way to achieve this without installing extra stuff on your server.


text:
Q: How can I specify a custom Cargo output directory? I put this in my Cargo.toml
[build]
target-dir = "../my-target"

However, Cargo doesn't recognize this key.
cargo run --release --bin my_project

warning: unused manifest key: build
error: failed to open: /.../project-root/target/releases/.cargo-lock

Caused by:
  Permission denied (os error 13)

The custom target dir with the environment variable works:
CARGO_TARGET_DIR=../my-target cargo run --bin my_project

but how can I specify '../my-target' in Cargo.toml?

A: [build] is a Cargo-level configuration rather than for the project:

This document will explain how Cargo's configuration system works, as well as available keys or configuration. For configuration of a project through its manifest, see the manifest format.

Put your [build] inside $PROJECT_DIR/.cargo/config or even $HOME/.cargo/config. See the above link for all the options.

A: Use the CARGO_TARGET_DIR environment variable:
CARGO_TARGET_DIR=../my-target cargo run --bin my_project

(This is stated in the question, but I wanted to highlight it for anyone that skips over that)


text:
Q: Getting SQL error when submitting form in wordpress I have a table in the database which contains 2 columns one for PLZ (zip code) and the other for Link
and I have a form that contains an input and a button.
the work required is when I type the PLZ in the form and I click on the button we will give the link corresponding to this PLZ
<?php
 require('../../../wp-blog-header.php');
 require('../../../wp-config.php');

if(isset($_POST['submit']))
{
    // WP Globals
    global $table_prefix, $wpdb;

    // Customer Table
    $customerTable = $table_prefix . 'customer';
    $PLZ = $_POST['PLZ'];
    // search in all table columns
    $query = "SELECT Link
    FROM $customerTable
    WHERE  PLZ = '$PLZ'
    ";
    $search_result = submit($query);

}
 else {
   echo 'error';
}
// function to connect and execute the query
function submit($query)
{
    global  $wpdb ;
    $search_result = $wpdb->get_results($query);
    foreach($search_result as $row){
        header('Location: '.$row['Link']);
    }

}
?>

and this is the form
<?php
function oped_postcode_form_function() {

       <form  method="get" action="<?php echo plugins_url('action.php', __FILE__ ); ?>">
   <label>Postleitzahl</label><input type="text" pattern="[0-9]{5}" title="Five digit zip code" />
   <button name="submit">submit</button>
   </form>
   <?php
       }
       // register shortcode
       add_shortcode('oped_postcode_form', 'oped_postcode_form_function');

?>

the result always gives error

A: Your form send GET request to server, so you need to use $_GET array in PHP code:
<?php
 require('../../../wp-blog-header.php');
 require('../../../wp-config.php');

if(isset($_GET['submit']))
{
    // WP Globals
    global $table_prefix, $wpdb;

    // Customer Table
    $customerTable = $table_prefix . 'customer';
    $PLZ = $_GET['PLZ'];
    // search in all table columns
    $query = $wpdb->prepare("SELECT Link FROM $customerTable WHERE  PLZ = %s", $PLZ);
    $search_result = submit($query);

}
else {
   echo 'error';
}
// function to connect and execute the query
function submit($query)
{
    global  $wpdb ;
    $search_result = $wpdb->get_results($query);
    foreach($search_result as $row){
        header('Location: '.$row['Link']);
    }

}
?>

Also you should to use prepared statements to prevent SQL Injection


text:
Q: Scroll pages horizontally Let's say, I have 3 pages. I need to build a website.
Instead of traditional vertical scrolling effect, I want to go for horizontal scrolling.
Can anyone guide my on achieving horizontal scroll keeping in mind that my website is not a single page, but it consists of multiple pages.
So, when a user scrolls the mouse, pages should change in a horizontal scroll effect, and the respective page name should appear in the URL also (it's for SEO purposes).
The scrolling effect can be achieved using AJAX/jQuery sliding effect.
How can this be achieved? Any code snippet or references?
All of the website that I have seen are of a single page. I don't want that.
For your reference, please see:
www.black5.de

A: I have specified a link below. This may help you. You may need to trigger some events when the scroll reaches particular position so that it is navigated to the next page.
https://designedbyaturtle.com/horizontal-scrolling-with-jquery/


text:
Q: Regex in powershell for getting assembly version number I am trying to create a script that will find and return the assembly version from the solution. It covers some of the test scenarios, but I cannot find the correct regex that will check is the version in correct format (1.0.0.0 is ok, but 1.0.o.0) and that contains 4 digits? Here is my code.
function Get-Version-From-SolutionInfo-File($path="$pwd\SolutionInfo.cs"){
$RegularExpression = [regex] 'AssemblyVersion\(\"(.*)\"\)'
$fileContent = Get-Content -Path $path
foreach($content in $fileContent)
{
    $match = [System.Text.RegularExpressions.Regex]::Match($content, $RegularExpression)
    if($match.Success) {
        $match.groups[1].value
    }
}

}

A: *

*Change your greedy capture group, (.*), to a non-greedy one, (.*?), so that only the very next " matches.

*

*The alternative is to use ([^"]*)

*To verify if a string contains a valid (2-to-4 component) version number, simply cast it to [version] (System.Version).
Applied to your function, with optimized extraction of the capture group via the -replace operator:
function Get-VersionFromSolutionInfoFile ($path="$pwd\SolutionInfo.cs") {
  try {
    [version] $ver =
      (Get-Content -Raw $path) -replace '(?s).*\bAssemblyVersion\("(.*?)"\).*', '$1'
  } catch {
    throw
  }
  return $ver
}


text:
Q: creating multiplie files in python I was trying to make program in python that makes multiplie files fe. from number 2 to 10 so it would make something like this ex2.py ex3.py ex4.py etc until 10, but it creates only first in this example ex2.py and i dont know how to change that
import os

x = int(input("First exercise: "))
y = int(input("Last exercise: "))

    for z in range(x, y):
        i = str(z)
        filenames = [input()]

        for filename in filenames:
            open("python/"+filename+i+".py", "a")

A: try this:
# x = int(input("First exercise: "))
x = 2
# y = int(input("Last exercise: "))
y = 10

# from x to y step 1
for i in range(x, y + 1):
    # one file name
    filename = input("filename:")

    # file path
    path = f"python/{filename}{i}.py"

    # create it and do nothing
    with open(path, "w+", encoding="utf-8") as f:
        pass

or i think you want this:
# x = int(input("First exercise: "))
x = 2
# y = int(input("Last exercise: "))
y = 10

# just one file name
filename = input("filename:")

# from x to y step 1
for i in range(x, y + 1):
    # file path
    path = f"python/{filename}{i}.py"
    print(path)

    # create it and do nothing
    with open(path, "w+", encoding="utf-8") as f:
        pass

out
filename:ex

python/ex2.py
python/ex3.py
python/ex4.py
python/ex5.py
python/ex6.py
python/ex7.py
python/ex8.py
python/ex9.py
python/ex10.py

A: You should ask for filename base (variable filenames) outside the for loop so it doesn't ask for it every time. Other than that, the script works fine.
Actually one more thing, setting x = 2 and y = 10 will produce files from 2 to 9.


text:
Q: How do I test if a conversion will result in an error? I have a string of various types including integers, *, +, and @. It is in a hashmap. When I am traversing the string, I want to be able to identify which parts are integers and which are not. For example, if I have "*12#", I want to be able to say if(string.substring(2,3)) is not an integer, return false.
Below, I am testing if converting the character into an integer will result in an error. However, this gives me a NumberFormatException.
//hm is hashmap
for(int i=hm.size()-1;i>=0;i--) {
            if(Integer.parseInt(hm.get(i))%1==0) {
                try {
                    System.out.println("integer");
                }
                catch(Exception e){
                    System.out.println("not integer");
                }
            }
        }

Here is the error log:
Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Prefix.findValue(Prefix.java:32)
    at Prefix.makeHashMap(Prefix.java:27)
    at Prefix.<init>(Prefix.java:10)
    at Prefix.main(Prefix.java:45)

What is a better way of approaching this problem?

A: The call to parseInt needs to be inside te try, and you should only be catching the exception that you intend to handle:
for(int i = hm.size() - 1; i >= 0; i--) {
    try {
        // Try to parse it
        String temp = Integer.parseInt(hm.get(i));
        System.out.println("integer");

    // And for best practice, specify the exact exception
    } catch(NumberFormatException e) {
        System.out.println("not integer");
    }
}


text:
Q: How should an akka actor be created that might throw an exception? I am migrating a project from scala actors to akka actors.  I used to have something like this where the constructor of MyActor may throw an exception if a certain system resource is unavailable:
var myActor: MyActor = null
try {
  myActor = new MyActor(3)
}
catch {
  case e: SomeUserDefinedException => println("failed!")
}

With akka, I migrated the code to this:
val someParam = 3
var myActor: ActorRef = null
try {
  myActor = context.actorOf(Props(classOf[MyActor], someParam), "myActor")
}
catch {
  case e: SomeUserDefinedException => println("failed!")
}

The problem I'm having is that it seems like in the akka case, the context.actorOf call isn't actually creating the MyActor object itself, but deferring it to another thread.  So when the constructor throws an exception, the try/catch block that I put in has no effect.
How can I migrate this scala actor code into akka actors?  Ideally I would prefer to avoid adding a lot of additional complexity.

A: You can catch the exception in the constructor of MyActor and notify other actors (e.g. the parent) about this exception. Try this:
class MyActor(val parent: ActorRef) extends Actor {
  try{
    throw new RuntimeException("failed construct")
  } catch {
    case e: Throwable =>
        parent ! e
        throw e
  }

  def receive: Actor.Receive = {case _ => }
}

class ParentActor extends Actor {
  val child = context.actorOf(Props(classOf[MyActor], self), "child")
  override def receive = {
    case e: Throwable => println(e)
  }
}


text:
Q: Adding padding for string types I have written below code to display a leading zero when the string representation of date has less than two digits?
'{}-{}-{:02d}'.format('6th', 'Jun', '1933')

But it is failing with an error:
ValueError: Unknown format code 'd' for object of type 'str'

A: str.format doesn't need format codes in most situations. You could simply use:
'{}-{}-{:02}'.format('6th', 'Jun', '1933')


text:
Q: Add Button without Visual Studio? Is it possible to add a button to the standard ribbon to SharePoint 2010 without Visual Studio 2010?
I'm trying to follow this tutorial:
http://spnotepad.blogspot.com/2012/01/overwriting-sp-2010-email-link-ribbon.html
After searching around I cannot find which files to edit, only how to do it using VS.

A: If it's in the ribbon of the forms or view of a list/document library, then you can add it though SharePoint Designer by opening the list and then use the Custom Action button in the new section of the ribbon.
Initially it may look as it's very limited what you can do in the custom action, but one of the options is to navigate to an url (with parameters like Selected Item) this can either be the url to a page with does a lot using client side object model and the supplied parameters or it can be javascript directly in the link. Another option is that the ribbon button can initiate a workflow on the selected item.
If "without Visual Studio" means "without Farm Solutions" but "Sandboxed solutions" are allowed then that's an option but of cause that would not really be "without Visual Studio".
If "without Visual Studio" means we'll not pay for that tool, then using CloudShare might be an option.

A: It should be possible to do this as simply adding a button doesn't require code but doing so means a lot of manual maintenance.  You would most likely need to do something like this :

*

*create a folder under 14/TEMPLATE/FEATURES using the feature name as
the folder name

*create a properly formed feature.xml and place it in that folder

*Create a properly defined elements.xml and place it in that folder

*Copy that folder to 14/TEMPLATE/FEATURES on all servers in your farm

*use the normal PowerShell commands (Enable-SPFeature) to activate
your feature

I've never done it that way but it should work...


text:
Q: discord.py Use select menus inside slash_commands I have this code
class DroppDownMenu(discord.ui.View):
    @discord.ui.select(placeholder="Choose one option", min_values=1, max_values=1, options=[
       discord.SelectOption(label="CPU", description="The CPUs scores list"),
        discord.SelectOption(label="GPU", description="The GPUs scores list"),
        discord.SelectOption(label="RAM", description="The RAMs scores list"),
        discord.SelectOption(label="All", description="All scores lists")
    ])
    async def callback(self, select, interaction : discord.Interaction):
        if select.values[0] == "CPU":
            await interaction.response.send_message("https://media.discordapp.net/attachments/838857610358292532/931919636461654046/CPU-Scores_Super_Dark_Mode_3.jpg")
        if select.values[0] == "GPU":
            await interaction.response.send_message("https://media.discordapp.net/attachments/838857610358292532/931919674134904982/GPU_Scores_Super_Dark_Mode_5.jpg")
        if select.values[0] == "RAM":
            await interaction.response.send_message("https://media.discordapp.net/attachments/838857610358292532/931919651070423100/RAM_scores_Super_Dark_Mode_4.jpg")
        if select.values[0] == "All":
            await interaction.response.send_message("https://media.discordapp.net/attachments/838857610358292532/931919636461654046/CPU-Scores_Super_Dark_Mode_3.jpg")
            await interaction.followup.send("https://media.discordapp.net/attachments/838857610358292532/931919674134904982/GPU_Scores_Super_Dark_Mode_5.jpg")
            await interaction.followup.send("https://media.discordapp.net/attachments/838857610358292532/931919651070423100/RAM_scores_Super_Dark_Mode_4.jpg")

@commands.slash_command(name="scores_pcc1", description="Shows charts with benchmark of CPUs, GPUs or RAM")
    async def pcc1_scores_slash(self, ctx, part : Option(DroppDownMenu)):

        #await self.scores_buttons(ctx)
        pass

So basically I want to create a select menu inside of a slash command like this
(Example)
But how to this
At the moment I only get errors

A: You're mixing two concepts here. There is the select component (discord.ui.select), this is typically sent after an interaction is invoked. What you are actually looking for is the choices parameter of the slash command Option (I'd love to link to the docs here, but they are quite empty at the moment).

Essentially, what you'll want to do is discard the entire DroppDownMenu class and move the logic from that callback to pcc1_scores_slash. You would generate the choices by changing the definition of part to something like part : Option(str, 'StackOverflow provides great parameter descriptions', choices=['CPU', 'GPU', 'RAM', 'All']) and then use the if-chain on the part variable in the slash command body something like this:
@commands.slash_command(name='scores_pcc1', description='Shows charts with benchmark of CPUs, GPUs or RAM')
async def pcc1_scores_slash(self, ctx, part: Option(str, 'StackOverflow provides great parameter descriptions', choices=['CPU', 'GPU', 'RAM', 'All'])):
    if part in ('CPU', 'All'):
        await ctx.respond("https://media.discordapp.net/attachments/838857610358292532/931919636461654046/CPU-Scores_Super_Dark_Mode_3.jpg")
    if part in ('GPU', 'All'):
await ctx.respond("https://media.discordapp.net/attachments/838857610358292532/931919674134904982/GPU_Scores_Super_Dark_Mode_5.jpg")
    if part in ('RAM', 'All'):
await ctx.respond("https://media.discordapp.net/attachments/838857610358292532/931919651070423100/RAM_scores_Super_Dark_Mode_4.jpg")


text:
Q: How to alter session with paramiko I want to write a script using python. It should connect via ssh to the server and execute few commands.
The problem is, it's required to change user during connection.
As example, it's possible in WinSCP:
http://winscp.net/eng/docs/ui_login_scp#shell (Parameter Shell: You can also make use of the option to alter session startup. For example to change the user after login (known as su))
So to connect with propper rights to my ssh server I must write following command into 'Shell' field in WinSCP:
sudo su - user

I need this very feature in paramiko.
And I can't execute sudo su - user after connection is established, cause my password isn't correct. It works only when I use this 'Shell' field.
Nevertheless, when I'm connecting to the server using PuTTY(win) or ssh(linux), I don't need to enter any options, from the start it allows me to have propper rights. Seems strange for me.
I don't know how to develop it using python/paramiko.
Help me pls.


text:
Q: I have a generic method that will not take the type I parameterized it to I would like to take the contents of the G.myUglyList list here and pass it to the Outer.send() method.  I do not understand why this gives a compiler error. ? extends Inner is the type I parameterize Outer with.  So why is it rejecting an Inner passed to it?  It wants a "? extends Inner", which isn't a type.
I want the list declared as List<Outer<? extends Inner>> so it can take subtypes of Inner.  (Please see the edit below for why this is)
interface Outer<T> {
    void send(T message);
}
interface Inner {}
interface Inner2 extends Inner {}

public class G {

    List<Outer<? extends Inner>> myUglyList;

    void foo() {
        Inner xxx = null;
        for (Outer<? extends Inner> outer : myUglyList) {
            outer.send(xxx); //error
        }
    }
}

I get this error:
error: method send in interface Outer<T#2> cannot be applied to given types;
required: CAP#1
found: Inner<T#1>
reason: actual argument Inner<T#1> cannot be converted to CAP#1 by method invocation conversion
where T#1,T#2 are type-variables:
T#1 extends Object declared in class G
T#2 extends Object declared in interface Outer
where CAP#1 is a fresh type-variable:
CAP#1 extends Inner<T#1> from capture of ? extends Inner<T#1>

edit:  I got a lot of answers saying just make the list of type List<Outer<Inner>>, but that is incorrect.  I will not be able to add subtypes of Inner if I do that.  If I try to add an Outer<Inner2>, it would fail.  So list must be of type List<Outer<? extends Inner>>.
interface Inner2 extends Inner {}
class G {
  void foo() {
    Outer<Inner2> foiled = null;
    myUglyList.add(foiled);   //this will fail if list is of type List<Outer<Inner>>
    Inner xxx = null;
    for (Outer<? extends Inner> outer : myUglyList) {
    outer.send(xxx); //error
  }

A: Change your code for:
interface Outer<T> {
    void send(T message);
}
interface Inner {}
interface Inner2 extends Inner {}

public class G {

    List<Outer<Inner>> myUglyList;

    void foo() {
        Inner2 xxx = null;
        for (Outer<Inner> outer : myUglyList) {
            outer.send(xxx); //error
        }
    }
}

And it will compile
Update:
// No matter if you put 'T extends Inner' here, the 'add' won't compile
interface Outer<T extends Inner> {
    void send(T message);
}
interface Inner {}
interface Inner2 extends Inner {}

public class G {

    List<Outer<Inner>> myUglyList;

    void foo() {
        Outer<Inner2> foiled = null;

        // This way, the 'add' invocation will compile, but it
        // breaks the generic and generates a warning.
        //
        // Casting 'foiled' to (Outer<Inner>) will also fail
        // because the compiler sees Outer<Inner2> as complete different type
        // from Outer<Inner>
        myUglyList.add((Outer) foiled);

        Inner xxx = null;
        for (Outer<Inner> outer : myUglyList) {
            outer.send(xxx); //error
        }
    }
}

A: Just declare
List<Outer<Inner>> myUglyList;

You can then add subtypes of Inner without restriction. By declaring it
List<Outer<? extends Inner>> myUglyList;

you are saying that myUglyList is "a list of Outer<some specific (but unknown) subtype of Inner>". That's not what you want.

A: outer is of type Outer<? extends Inner>, i.e. of some unknown subtype of Inner and its send method takes an object of that same subtype.
For example outer may be of type Outer<OtherInner> and then outer.send needs a OtherInner, so outer.send(xxx) would be wrong.

A:  for (Outer<? extends Inner> outer : myUglyList) {
     outer.send(xxx); //error
 }

In that, Outer<? extends Inner> outer, so the actual type is unknown (?). send takes something unknown that extends Inner, and also outer has something that extends Inner but still unknown.
Update
interface Outer<T extends Inner> {
    void send(T message); //this can take instance of subtype of Inner
}
interface Inner {}
interface Inner2 extends Inner {}

class G {

    List<Outer<Inner>> myUglyList; //you can add instances of subtypes of Inner

    void foo() {
        Inner xxx = null;
        for (Outer<Inner> outer : myUglyList) {
            outer.send(xxx); //error
        }
    }
}

A: PECS - Producer extends Consumer super
Because outer is parameterized with extends, you cannot pass anything (except null) into its send method.


text:
Q: How do you use the standard library in IronPython? I'll prefix this question with: No, Setting IRONPYTHONPATH is not the answer.
Anyway...
I was planning on using IronPython as a replacement for Powershell for a project, but I've been stumped before I've even started.
The very first thing I tried to do was use os.path, resulting in:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named os

After messing around I finally discovered I could use the standard library by adding it manually to the path:
import sys
sys.path.append(r"C:\Program Files\IronPython 2.7\Lib")
import os

However, this is a daft idea. Hard coding the path to the python library inside my scripts is a 100% guaranteed way of making them not work at some point.
I discovered this almost immediately when I tried to use the script on a windows 7 machine and the path was slightly different ('Program Files (x86)').
So, a couple of questions here:
1) Why is it so hard to use the standard library? At the very least I would have thought the interactive prompt in VS and basic ipy.exe would have this.
2) How can I determine the directory that iron python is installed in regardless of the system I'm using? (IronPython installer setting a var perhaps?)
Just a note here; yes, I have seen some other posts saying "set your IRONPYTHONPATH". This in unhelpful. If I have a blank machine that means I have to:
1) Install IronPython
2) Run some crazy powershell script to search out where-ever-the-heck the standard library was installed and set a global IRONPYTHONPATH variable to it.
3) Run python scripts
I'm looking for a better way.
--
Edit:
The fact I'm using this to do powershell like things is basically irrelevant, but I'm trying to achieve something like:
import clr
from System.Management.Automation import RunspaceInvoke
import os

scriptRoot = os.getcwd()
runSpace = RunspaceInvoke()
cmdPath64 = os.join(scriptRoot, "..\java\...")
cmdPath32 = os.join(scriptRoot, "..\java\...")
proc = runSpace.Invoke("Get-WmiObject Win32_Processor ... ")
if proc.AddressWidth == 32:
  runSpace.Invoke(cmdPath32)
else:
  runSpace.Invoke(cmdPath64)

A: I find that for ensuring that everything works for non-developer third parties, it's usually better to use pyc.py to create DLL's and and executable.  I routinely create a DLL of the python standard modules and reference that in code.  See my previous answer at this question IronPython: EXE compiled using pyc.py cannot import module "os"

A: It's a bit workaroundish but, given that the LIB directory of ironpython is installed under the x86 program files folder in 64bit systems and on the usual program files path on 32bit systems, you could do in this way:
import sys
import System
if System.IntPtr.Size * 8 == 32: # detect if we are running on 32bit process
    sys.path.append(System.Environment.GetEnvironmentVariable("ProgramFiles") + "\IronPython 2.7\Lib")
else:
    sys.path.append(System.Environment.GetEnvironmentVariable("ProgramFiles(x86)") + "\IronPython 2.7\Lib")

import os # it works !!

Here we use %ProgramFiles% and %ProgramFiles(x86)% to determine the path where IronPython is installed.
Quoting wikipedia about %ProgramFiles% variable (link):

%ProgramFiles%
This variable points to Program Files directory, which stores all the
  installed program of Windows and others. The default on
  English-language systems is C:\Program Files.  In 64-bit editions of
  Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)% which
  defaults to C:\Program Files (x86) and %ProgramW6432% which defaults
  to C:\Program Files. The %ProgramFiles% itself depends on whether the
  process requesting the environment variable is itself 32-bit or 64-bit
  (this is caused by Windows-on-Windows 64-bit redirection).

A: This is very odd, because if you run the the IronPython installer, and then run C:\Program Files\IronPython 2.7\ipy.exe or C:\Program Files (x86)\IronPython 2.7\ipy.exe, you shouldn't need to do anything to have the stdlib available.
My guess is that you have more than one IronPython and you're running the wrong one, but only because I can't think of another reason this would happen. It's supposed to Just Work.


text:
Q: fatal error: Array index out of range in swift 2 with ubuntu 14.04 i have a problem with swift and i don't know how to solve it because I have just 2 months studying swift, and I am gradually learning, so here is the code:
import Foundation

var dir = "/home/guillermo/Escritorio/";
var file = "tokens";
var path = dir.stringByAppendingPathComponent(file);

guard var archivoTokens = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding) else {
    fatalError("failed to read archivoTokens from file")
}

var lineasArchivoTokens:[String] = archivoTokens.componentsSeparatedByString("\n");

var TOKENS:[String] = [String]();
var PATRONES:[String] = [String]();
var NOMBRES:[String] = [String]();

var count = lineasArchivoTokens.count;
for index in 0..<count{
    var tmpList:[String] = (lineasArchivoTokens[index]).componentsSeparatedByString(" ");
    PATRONES.append(tmpList[1]);
    NOMBRES.append(tmpList[0]);
}

and this is the error:
fatal error: Index out of range
Current stack trace:
/usr/lib/swift/linux/libswiftCore.so(swift_reportError+0x8b) [0x7fefd171dccb]
/usr/lib/swift/linux/libswiftCore.so(_swift_stdlib_reportFatalError+0x3d) [0x7fefd172e0cd]
/usr/lib/swift/linux/libswiftCore.so(+0x28d192) [0x7fefd1681192]
/usr/lib/swift/linux/libswiftCore.so(function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded, Arg[2] = Dead, Arg[3] = Dead> of Swift._fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt, flags : Swift.UInt32) -> ()+0x34) [0x7fefd1681294]
/usr/lib/swift/linux/libswiftCore.so(+0x16f0b5) [0x7fefd15630b5]
.build/debug/lexico7() [0x40165b]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) [0x7fefcf971ec5]
.build/debug/lexico7() [0x401049]
Instrucción ilegal (`core' generado)


text:
Q: Is it possible to customize width of Picker in React Native? Im a newbie using React Native.
I jus create an application as on the screenshot.
I want to make the dropdown or Picker component a bit smaller.
But I cant do it, Im looking for a guide to solve this.
Thanks.
My application:

import React, { Component } from 'react'
import { Item, Picker, TouchableOpacity, View, ListView, Text } from 'react-native'
import { connect } from 'react-redux'
import { Icon, Header } from 'react-native-elements'
import { Button, Container, Content, Footer, Title} from 'native-base'

// For empty lists
// import AlertMessage from '../Components/AlertMessage'

// Styles
import styles from './Styles/MainRestoStyles'

class MainRestoScreen extends React.Component {
  constructor (props) {
    super(props)

    /* ***********************************************************
    * STEP 1
    * This is an array of objects with the properties you desire
    * Usually this should come from Redux mapStateToProps
    *************************************************************/
    const dataObjects = {
      first: [
        {title: 'First Title', description: 'First Description'},
        {title: 'Second Title', description: 'Second Description'},
        {title: 'Third Title', description: 'Third Description'},
        {title: 'Fourth Title', description: 'Fourth Description'},
        {title: 'Fifth Title', description: 'Fifth Description'},
        {title: 'Sixth Title', description: 'Sixth Description'},
        {title: 'Seventh Title', description: 'Seventh Description'},
        {title: 'Eighth Title', description: 'Eighth Description'},
        {title: 'Ninth Title', description: 'Ninth Description'},
        {title: 'Tenth Title', description: 'Tenth Description'}
      ],
      second: [
        {title: 'Eleventh Title', description: 'Eleventh Description'},
        {title: '12th Title', description: '12th Description'},
        {title: '13th Title', description: '13th Description'},
        {title: '14th Title', description: '14th Description'},
        {title: '15th Title', description: '15th Description'},
        {title: '16th Title', description: '16th Description'},
        {title: '17th Title', description: '17th Description'},
        {title: '18th Title', description: '18th Description'},
        {title: '19th Title', description: '19th Description'},
        {title: '20th Title', description: '20th Description'},
        {title: 'BLACKJACK!', description: 'BLACKJACK! Description'}
      ]
    }
    /* ***********************************************************
    * STEP 2
    * Teach datasource how to detect if rows are different
    * Make this function fast!  Perhaps something like:
    *   (r1, r2) => r1.id !== r2.id}
    *   The same goes for sectionHeaderHasChanged
    *************************************************************/
    const rowHasChanged = (r1, r2) => r1 !== r2
    const sectionHeaderHasChanged = (s1, s2) => s1 !== s2

    // DataSource configured
    const ds = new ListView.DataSource({rowHasChanged, sectionHeaderHasChanged})

    // Datasource is always in state
    this.state = {
      dataSource: ds.cloneWithRowsAndSections(dataObjects)
    }
  }

  /* ***********************************************************
  * STEP 3
  * `renderRow` function -How each cell/row should be rendered
  * It's our best practice to place a single component here:
  *
  * e.g.
    return <MyCustomCell title={rowData.title} description={rowData.description} />
  *************************************************************/
  renderRow (rowData, sectionID) {
    // You can condition on sectionID (key as string), for different cells
    // in different sections
    return (
      <TouchableOpacity style={styles.row}>
        <Text style={styles.boldLabel}>Section {sectionID} - {rowData.title}</Text>
        <Text style={styles.label}>{rowData.description}</Text>
      </TouchableOpacity>
    )
  }

  /* ***********************************************************
  * STEP 4
  * If your datasource is driven by Redux, you'll need to
  * reset it when new data arrives.
  * DO NOT! place `cloneWithRowsAndSections` inside of render, since render
  * is called very often, and should remain fast!  Just replace
  * state's datasource on newProps.
  *
  * e.g.
    componentWillReceiveProps (newProps) {
      if (newProps.someData) {
        this.setState(prevState => ({
          dataSource: prevState.dataSource.cloneWithRowsAndSections(newProps.someData)
        }))
      }
    }
  *************************************************************/

  // Used for friendly AlertMessage
  // returns true if the dataSource is empty
  noRowData () {
    return this.state.dataSource.getRowCount() === 0
  }

  render () {
    return (
      <Container>
        <View style={styles.toolbar}>
          <Text style={styles.toolbarButton}></Text>
          <Icon name='bowl' type='entypo' size={40} color='white'/>
          <Text style={styles.toolbarButton}></Text>
        </View>
        <Content>
        <Picker>
            <Picker.Item
              label='Hello'
              value='hello'
            />
          </Picker>
          <ListView
            contentContainerStyle={styles.listContent}
            dataSource={this.state.dataSource}
            onLayout={this.onLayout}
            renderRow={this.renderRow}
            enableEmptySections
          />
        </Content>
        <Footer style={ styles.bars }>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='location' type='entypo' color='white' size={30}/>
          </Button>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='heart' type='foundation' color='white' size={30}/>
          </Button>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='bell' type='entypo' color='white' size={30}/>
          </Button>
        </Footer>
      </Container>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    // ...redux state to props here
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(MainRestoScreen)

update:

<View>
  <Picker style={{ marginLeft: 80, marginRight: 80 }}>
    <Picker.Item
      label='Hello'
      value='hello'
    />
  </Picker>
</View>

it's just affect the text, I want to make the whole Pikcer become smaller.

A: You need to wrap your Picker inside a View Tag. Then you can add margins.  e.g.
<View style={{ marginLeft: 80, marginRight: 80 }}>
  <Picker>
    <Picker.Item
      label='Hello'
      value='hello'
    />
  </Picker>
</View>


text:
Q: How does C51 reentrant functions actually work? C51 compiler generates following subroutine for manipulating the simulated stack pointer:
                    C?ADDXBP:
        C:0x000F    E509     MOV      A,0x09
        C:0x0011    2582     ADD      A,DPL(0x82)
        C:0x0013    F582     MOV      DPL(0x82),A
        C:0x0015    E508     MOV      A,0x08
        C:0x0017    3583     ADDC     A,DPH(0x83)
        C:0x0019    F583     MOV      DPH(0x83),A
        C:0x001B    B50804   CJNE     A,0x08,C:0022
        C:0x001E    858209   MOV      0x09,DPL(0x82)
        C:0x0021    22       RET
        C:0x0022    10AF06   JBC      EA(0xA8.7),C:002B
        C:0x0025    858209   MOV      0x09,DPL(0x82)
        C:0x0028    F508     MOV      0x08,A
        C:0x002A    22       RET
        C:0x002B    858209   MOV      0x09,DPL(0x82)
        C:0x002E    F508     MOV      0x08,A
        C:0x0030    D2AF     SETB     EA(0xA8.7)
        C:0x0032    22       RET

I know it means this:
        C?ADDXBP: (add DPTR to XBP)
        {
            DPTR = DPTR + XBP    (temporarily store new XBP)
            if (only the low byte is changed)
            {
                XBPL = DPL
                return
            }
            else (both bytes changes, the write action has to be done atomically)
            {
                EA = 0
                XBPL= DPL
                XBPH= DPH

                EA = 1, if EA previously was 1.
                return
            }
        }

When a call to reentrant function happens, C51 generates a call to C?ADDXBP first to allocate simulated stack space, but we can simply construct a situation that breaks this mechanism.

*

*Process P1 calls some reentrant function, it first calls C?ADDXBP, return address of P1-C?ADDXBP is pushed onto hardware stack.

*assume that P1-C?ADDXBP didn't reach the code where it disables interrupts, and a context switch happens, now Process P2 is running.

*Process P2 also wants to call some reentrant function and calls C?ADDXBP, return address of P2-C?ADDXBP is pushed onto hardware stack.

*assume that context switched to P1 again, before P2-C?ADDXBP disables interrupts

*P1-C?ADDXBP resumes and run all the way to RET, and tries to return to where P2-C?ADDXBP should return to, and that's an error.
Cx51 documentation says "Reentrant functions can be called recursively and can be called simultaneously by two or more processes. Reentrant functions are often required in real-time applications or in situations where interrupt code and non-interrupt code must share a function.", but according to my analysis it doesn't work.
I think there might be something I'm missing, or maybe C51 will do more than that and generate more code to solve the problem I found. It really confused me a lot.


text:
Q: Redirection to div element php Hi I want that the user becomes redirected to the main div after the login. Now the problem is that it wont work. The PHP mysql connection work well but the user wont become redirected to the main div. How can the user redirected after successful login to the main div?
the error message in my browser:

ERR_TOO_MANY_REDIRECTS

login.php
<?php
if(isset($_COOKIE['username'])){
    $cookie = $_COOKIE['username'];
    header('Location: http://' . $_SERVER['HTTP_HOST'] . '/local/mainn.php');
}
else{
    $message = array();
    if (!empty($_POST)) {
        if (
            empty($_POST['f']['username'])

            ) {
                $message['error'] = 'Es wurden nicht alle Felder ausgefüllt.';
            }
            $mysqli = @new mysqli('localhost', 'root', '', '');
                if ($mysqli->connect_error) {
                    $message['error'] = 'Datenbankverbindung fehlgeschlagen: ' . $mysqli->connect_error;
                }
                $query = sprintf(
                    "INSERT INTO user (username)
                    SELECT * FROM (SELECT '%s') as new_user
                    WHERE NOT EXISTS (
                        SELECT username FROM user WHERE username = '%s'
                    ) LIMIT 1;",
                    $mysqli->real_escape_string($_POST['f']['username']),

                    $mysqli->real_escape_string($_POST['f']['username'])

                );

                $mysqli->query($query);
                if ($mysqli->affected_rows == 1) {
                    $message['success'] = 'Neuer Benutzer (' . htmlspecialchars($_POST['f']['username']) . ') wurde angelegt, weiter zur Anmeldung.';
                    header('Location: http://' . $_SERVER['HTTP_HOST'] . '/local/mainn.php');
                    $id = $mysqli->insert_id;
                } else {

                }
                $t = time() + 60 * 60 * 60 * 24 * 1000;
                setcookie("username", $_POST['f']['username'], $t);
                setcookie("userid", $id , $t);
                // cookie setzen
                $mysqli->close();
            }
    }
    ?>

        <meta charset="UTF-8" />
        <title>
            HTML Document Structure
        </title>
        <link rel="stylesheet" type="text/css" href="style.css" />

        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />

        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

        <form name="login-form" class="login-form" action="./login.php" method="post">

            <input name="f[username]" type="text" class="input username" placeholder="Username" id="username"
            />

            <input type="submit" name="submit" value="Login" class="button" data-theme="b"/>

        </form>

mainn.php:

<?php
include("login.php");
?>

<?php
include("usercoords.php");
?>

localy

        range

    <form name="login-form" class="login-form" action="./range.php" method="post" style="padding:10px 20px;">

        Select range:
<input type="range" name="slider-fill" id="slider-fill" value="5" min="0" max="100" step="1" data-highlight="true">

        <input type="submit" name="submit" value="create" class="button" data-theme="b"/>

    </form>

own posts

main

create post

A: I deleted
<?php
include("login.php");
?>

and launch the application with login.php.


text:
Q: Query for two models at once with Ajax - Eloquent - Laravel I would like to be able to list the records of two models at the same time, taking into account how I have the query set up at the moment to use it with Ajax.
Right now my query works fine, considering the rest of my project (AJAX - Laravel).
public function allData(){
        $data = Siniestro::orderBy('id','DESC')->get();
        return response()->json($data);
    }

I've tried doing it like this, but it looks like I'm doing the query wrong
public function allData(){
    $data = Siniestro::orderBy('id','DESC')->get();
    $users = User::all();
    return response()->json($data, $users);
}

Edit:
Esta es la vista que estoy refiriendo
This is the view; I want that with the eloquent query, it shows me ordered as now (orderBy), and also that it looks for a match of fields with "where"; for example $siniestros = Siniestro::where('estado', 'coordinado')->get();.
Edit 2
dd($users)
full view code
@extends('layouts.app')

@section('content')

Derivar IP

                                Inspecciones coordinadas

                                        Siniestro
                                        Fecha IP
                                        Modalidad
                                        Dirección
                                        Localidad
                                        Inspector
                                        Acciones

                                Asignar IP
                                Asignar IP

                                            Inspector
                                            <input type="text" name="inspector" class="form-control"  id="inspector" for="inspector" >

                                    Inspector
                                    <select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" for="inspector" name="inspector" >
                                            <option selected></option>

                                            <option value="Taller del asegurado">Taller del asegurado</option>

                                        </select>

                                                E-mail
                                                <input type="text" name="emailperito"  class="form-control" id="emailperito" for="emailperito">

                                                Teléfono
                                                <input type="text" name="telefonoperito"  class="form-control" id="telefonoperito" for="telefonoperito">

                                    <input type="hidden" id="id">

                                    <button type="submit" id="updateButton" class="btn btn-primary btn-sm" onclick="updateData(event)">Asignar</button>

@endsection

@section('javas')

@endsection

Edit 3
enter image description here
See, the previous capture that showed me the attributes was only from $users, now using $data = Siniestro::orderBy('fechaip','ASC')->get();$users = User::all();$combo = ['users' => $users, 'data' => $data];dd($combo); As you can see, it shows me all the users, but I can't see their "attributes", strange, right? will the problem be there?

A: json as a rule will always post an array, you can not post individual objects that way. you need to convert the objects into an array and post it.
$response_array['message'] = $data;
                $response_array['data'] = $users;
                return response()->json($response_array);

or
$data = ['users' => $users, 'content' => $contents];
return response()->json($data);
You can receive those data using :
success: function(response) {
console.log(response.content);
}

A: So when you do
$data = Siniestro::orderBy('fechaip','ASC')->get();
$users = User::all();
$combo = ['users' => $users, 'data' => $data];

return response()->json($combo);

Then you should inspect the incoming response data in your javascript. As now the data is keyed by data and users. So in your allData() function in javascript you will have to adjust as per the keys to display the data.
function allData(){
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/teacher/all",
        success: function (response){

            //Here console.log(response) to see the structure of incoming data
            console.log(response)
            // Should output something like
            // {users: [... array of user records(objects)], data: [... array of siniestro records (objects)}

            // So to generate the display markup you may have to do
            $siniestroMarkup = "";
            $.each(response.data, function(key, value){
                siniestroMarkup = siniestroMarkup + "
"
                siniestroMarkup = siniestroMarkup + ""+value.id+"	"
                siniestroMarkup = siniestroMarkup + ""+value.siniestro+"	"
                siniestroMarkup = siniestroMarkup + ""+value.fechaip+"	"
                siniestroMarkup = siniestroMarkup + ""+value.modalidad+"	"
                siniestroMarkup = siniestroMarkup + ""+value.direccion+"	"
                siniestroMarkup = siniestroMarkup + ""+value.localidad+"	"
                siniestroMarkup = siniestroMarkup + ""+value.inspector+"	"
                siniestroMarkup = siniestroMarkup + ""
                siniestroMarkup = siniestroMarkup + ""
                siniestroMarkup = siniestroMarkup + "<button class='btn btn-info btn-sm' onclick='editData("+value.id+")'>Asignar IP</button>"
                siniestroMarkup = siniestroMarkup + "	"
                siniestroMarkup = siniestroMarkup + "
"
            })
            $('tbody').html(siniestroMarkup);
        });

            // Similarly you can access the user records
         $.each(response.users, function(key, value) {
            //Here value will represent each user record
         });

}

And you may also have to adjust the DataTable ajax response if you are using it probably like below (check exact response data structure for and how to access it for DataTable)
$(document).ready(function() {
    $('.tablita').DataTable({
        "serverSide": true,
        "ajax": "/teacher/all",
        "columns": [
            // {data: 'id'},
            {data: 'data.siniestro'},
            {data: 'data.fechaip'},
            {data: 'data.modalidad'},
            {data: 'data.direccion'},
            {data: 'data.localidad'},
            {data: 'data.inspector'},
            {data: 'data.action', name: 'action', orderable: true, searchable: true},
        ],
    });
})

Check the above and see if that's how you want the data.


text:
Q: Get the first launch date of an app in Cordova How can I get the date when a Cordova app was first opened by a user on his phone?

A: They only way I can think is to save that data in some storage, server or locale.
One sample
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    if(window.localStorage.getItem("firstLaunch") == null) {
         window.localStorage.setItem("firstLaunch", date().toString());
    }
}

Now you can access that value with window.localStorage.getItem("firstLaunch")
Take in mind that some operative systems can delete localstorage, so if this is a important data, save better in a SQLite or Server Side


text:
Q: Log4j Duplicate logging with additivity set to false I'm trying to log to a file, if the logging is called from a specific package, and otherwise log to console. So I set the additivity to false for the two loggers which should be logging to file, so nothing would be logged on the console for these two packages. My log4j.xml is as follows:
<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <param name="Target" value="System.out"/>
    <param name="Threshold" value="TRACE"/>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{ISO8601} [%t] %-5p %c - %m%n"/>
    </layout>
</appender>

<appender name="file" class="org.apache.log4j.RollingFileAppender">

    <!-- Set your own log file location -->
    <param name="File" value="c:/temp/security-toolkit.log" />

    <!-- Specify the number of backup -->
    <param name="MaxBackupIndex" value="10"/>

    <!-- Specify the file size -->
    <param name="MaxFileSize" value="10MB"/>

    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%-5p[%X{event} %X{user_name}:%X{user_sid}@%X{user_last_host_address} -> /%X{application_name}/%X{module_name}] %m%n"/>
    </layout>
</appender>

<root>
    <priority value="INFO"/>
    <appender-ref ref="console"/>
</root>

<logger name="com.foo.security" additivity="false">
    <level value="INFO" />
    <appender-ref ref="file"/>
</logger>

<logger name="org.foo.esapi" additivity="false">
    <level value="WARN" />
    <appender-ref ref="file"/>
</logger>

However, logs from com.foo.security are still being logged to the console. Does anyone know what the issue could be here?


text:
Q: Removing collections/shards/etc in SolrCloud/Zookeeper Is there a way to remove a single or even all collections and their various associated settings/shards/etc in Zookeeper/SolrCloud?  I would like to start back with a fresh, clean SolrCloud, but I am not seeing any way to clean things up.  I tried running zkcli.bat -zkhost localhost:<port> -cmd clear but that didn't seem to do anything.

A: SolrCloud Collections API proivdes support for this. Did you look at
https://cwiki.apache.org/confluence/display/solr/Collections+API
Solrcloud delete collection bug?
You can use solrctl tool if you are working with CDH Solr.


text:
Q: Responsive Site Not Working In IE (Despite css3-mediaqueries.js) I'm creating a Responsive Website but cannot seem to get it to work in IE (I'm testing in IE8). Now, I know that Internet Explorer 8 and below doesn't support CSS3 media queries. But I included the css3-mediaqueries.js Javascript file (hosted by Google) and it still doesn't work.
I stripped out all the code leaving the very minimum (literally only 26 lines of HTML and a combined 34 lines of CSS). The HTML successfully validates as HTML5 and the CSS validates as CSS level 3. Here's the code:
HTML
<!DOCTYPE HTML>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, maximum-scale=1.0, minimum-scale=1.0, initial-scale=1.0" />
<title>Responsive Site</title>
<link rel="stylesheet" type="text/css" href="css/custom.css" />
<link rel="stylesheet" type="text/css" media="only screen and (min-width:50px) and (max-width: 800px)" href="css/responsive.css" />

custom.css:
@charset "UTF-8";

/*html5 display rule*/
article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary {display: block;}

body {margin: 0px; padding:0px}

.wrapper {
    width:78%;
    margin:0 auto}

#article {
    float:left;
    width:61.224489795%;
    margin:20px 0 0 0;
    padding:0;
    height:500px;
    background-color:#000}

#side {
    float:right;
    width:30.775510204%;
    margin:20px 0 0 0;
    padding:0;
    height:500px;
    background-color:#999}

responsive.css:
@charset "UTF-8";

#article {
    width:100%}

#side {
    width:100%;
    clear:left}

A: In addition to the inability to use @imported stylesheets (which is documented on the github and google code project) - there is a problem if one does not explicitly state the media query in a format similar to:
@media screen and (min-width: 666px) and (max-width: 1000px)

compared to:
@media and (min-width: 666px) and (max-width: 1000px)

please look at this issue in the github issues section for this project - after about an hour of trying to set this up - the lack of screen in my media-queries was causing them to not be recognized.

A: I finally figured it out! And only a few lines of code had to change.
A friend pointed out that the documentation for the css3-mediaqueries.js Javascript file reads:

Note: Doesn't work on @import'ed stylesheets (which you shouldn't use
  anyway for performance reasons). Also won't listen to the media
  attribute of the  and  elements.

I was using the media attribute in the link element in my HTML file. So, here's what I did to resolve the issue:
In the HTML file I removed:
<link rel="stylesheet" type="text/css" media="only screen and (min-width:50px) and (max-width: 800px)" href="css/responsive.css" />

And replaced it with:
<link rel="stylesheet" type="text/css" href="css/responsive.css" />

I then added the media attribute to my responsive.css file:
@charset "UTF-8";
@media screen and (max-width: 800px) {
#article {
    width:100%}

#side {
    width:100%;
    clear:left}
}

But it still didn't work. I then changed the ordering of the media and @charset attributes in my responsive.css file. I simply rearranged lines 1 & 2:
@media screen and (max-width: 800px) {
@charset "UTF-8";

That did the trick. Not sure exactly why the ordering of the character set makes a difference? Perhaps someone can shed some light on it.
Thanks David for the useful suggestions! It's good to have several option in the tool shed and I may turn to respond.js in the future. But for now, I am happy with the code that Google is hosting.

A: Have you tried respond.js ?
Good luck!
Update
It may be safer to combine your two CSS files into one. Add the mobile specs into your custom.css file with:
@media (min-width: 50px) and (max-width: 800px) {

  /* mobile CSS here */

} /* close @ media for mobile */

A: <meta http-equiv="X-UA-Compatible" content="IE=9">

You must place that before any other meta tags.


text:
Q: Using local database in VSTO with SQLite As my VSTO is growing up in the usage it comes harder to make it work without having a database.
To make it work I need to have a local database used by the app like the sqlite-net-pcl does in any Xamarin app.
My VSTO was fully functional and i tried to add the NuGet package and using it the same way I used to in my previous Xamarin. Unfortunately it doesn't work and keep refusing to connect throwing the missing package 'e_sqlite3'. I've been looking for a solution in the NuGet package manager re-installing and trying various version but no solution.
I am now looking for either a solution of this problem or an alternative that could be the most look-a-like to keep going on my project without having to re-learn too many stuff.

A: Are you using Microsoft.Data.Sqlite (newer, maintained by Microsoft) or System.Data.SQLite (older, maintained by the SQLite developers)?
I suspect the former; this looks like a long-standing bug with Microsoft.Data.Sqlite on .NET Framework.
I suggest switching to System.Data.SQLite, it's worked much better with .NET Framework for me. If you use ClickOnce to deploy your VSTO add-in, note that you will need to do a bit of folder setup for ClickOnce.


text:
Q: Small dataset results in regression tree with only 1 terminal node I don't understand why this decision tree has only one terminal node:
library(tree)

x1 = c(-10, -9, -11, -11, 0, 1, 0, 0)
x2 = c(-9, -11, -10, -11, 0, 0, 1, 0)
y = c(-50, -50.1, -50, -50, 8, 8, 7.9, 8)
df = data.frame(x1=x1, x2=x2, y=y)

t <- tree(y ~ ., df)
summary(t)

A: Your dataset is too small to split the nodes per the default control parameters of tree(). Admittedly, getting this out of ?tree requires digging additionally into ?tree.control. You can reduce the minimum number of data points per node and the minimum number per child node like this:
t <- tree(y ~ ., df,
    control=tree.control(nobs=nrow(df),mincut=4,minsize=8))

This gives you a tree with two terminal nodes.


text:
Q: Polarization induces alternating pairing on homology Let $A$ be an abelian variety over $\overline{\mathbb{Q}}$. We work up to isogeny (i.e., Hom sets are tensored with $\mathbb{Q}$). I am looking for a reference (and ideally, a short explanation) for the following statement (or, if wrong, for its correct version):
Claim: Let $\phi:A \to A^*$ be a polarization (in particular, a symmetric isogeny). Then $\phi$ induces a non-degenerate alternating pairing $\langle-,-\rangle:H_1(A,\mathbb{Q}) \times H_1(A,\mathbb{Q}) \to \mathbb{Q}$ on the degree $1$ singular homology of $A$.
Such a pairing is equivalent to an anti-symmetric isomorphism $\psi:H_1(A,\mathbb{Q}) \to H_1(A,\mathbb{Q})^*$. The thing that puzzles me is that $\phi^*=\phi$ but $\psi^*=-\psi$. This might have to do with the way in which $A^{**}$ is identified with $A$ or with the way in which the pairing is defined, but I am not sure: if the functor $(-)^{**}$ on abelian varieties is isomorphic to the identity, and if the functor $H_1(-,\mathbb{Q})$ from abelian varieties to $\mathbb{Q}$-vector spaces is faithful and exact and preserves duality, and if $\psi$ is the image of $\phi$ under $H_1(-,\mathbb{Q})$, then how can the symmetric morphism $\phi$ turn into an anti-symmetric morphism $\psi$? Where am I doing something wrong?


text:
Q: Cluster qsub check when job is done. python I'm building a python pipeline and in that pipeline script I call for another python script which uses qsub to submit a job to a cluster (this job consist op 70 jobs)
Now I need the output of those jobs to continue working.
How can I "Pause" the python script until all the 70 jobs are done?
I can't modify the script that submits to the server, so it has to be done in my own script.
(using an AMD64 cluster)
edit:
this is how I call the other script:
os.system("python ScriptThatQsub.py arg1 arg2")

I'm still working on this. and searching the interwebz, but I can't help but wonder... is this even possible??

A: Just use the command line flag -sync y as in qsub -sync y my_job or
from subprocess import Popen
job = Popen(["qsub", "-sync", "y", "my_job"])
job.communicate()

A: I've just put the Qstat from cluster in a variable and i checked if my jobname was found in that list. If so. sleep for a while.
Thanks for the help everyone!


text:
Q: Разделение слов и словосочетаний в параграфе Задача у меня следующая: разбить слова и словосочетания в предложении. У меня возникла сложность со словосочетаниями. Чтобы как то отделить слова от словосочетаний, я вынес словосочетания в отдельный span.
Привожу пример, что имею на данный момент.

let text = "
Привет, как твои дела? Это тестовое сообщение.
";
let myArray = text.split("
").join("").split("
");
myArray.pop(myArray.length - 1); // Тут получаю массив из параграфов (если их будет несколько)
myArray.map((item, index) => {
  let arr = item.split(/\s+/); // Тут массив слов, который получил разбиением через пробелы (именно тут надо как то учитывать словосочетания из span)
  console.log(arr)
})

В итоге надо получить на выходе следующее
['Привет,', 'как', 'твои дела?', 'Это', 'тестовое', 'сообщение.']

А у меня вот так
["Привет,", "как", "твои", "дела?", "Это", "тестовое", "сообщение."]

A: Может быть, так? Только пришлось переместить знак вопроса внутрь тега.

let text = "
Привет, как твои дела? Это тестовое сообщение.
";

let myArray = text.split("
").join("").split("
");

myArray.pop(myArray.length - 1);

myArray.map((item) => {
  let arr = item
    .split(/(?=)|(?<=<\/span>)/)
    .flatMap(str => str.startsWith('') ?
      str.replace(/^|<\/span>$/g, '') :
      str.trim().split(/\s+/)
    );
  console.log(arr)
});

A:

var text = "
Привет, как твои дела? Это тестовое сообщение.
";

var res = []

text.replace(
  /<\/?p>|([^<]*)<\/span>([^\s<]*)|([^\s<]+)/g,
  (match, span = "", tail = "", word = "") => {
    var cur = span + tail + word
    cur && res.push(cur)
  }
)

console.log(res)

A: С учётом знака вопроса после спана:

var text = "
Привет, как твои дела? Это тестовое сообщение.
";

var res = text
  .split(/\s+|<\/?p>|([^<]*<\/span>[^\s<]*)/)
  .filter(Boolean)
  .map(x => x.replace("", ""))

console.log(res)

Если знак вопроса можно поместить отдельно, то проще:

var text = "
Привет, как твои дела? Это тестовое сообщение.
";

var res = text
  .split(/\s+|<\/?p>|([^<]*)<\/span>/)
  .filter(Boolean)

console.log(res)


text:
Q: If $n^3 < |a_n| < n^4$ find the radius of convergence for $\sum_{n=2}^\infty a_nx^n$ If $n^3 < |a_n| < n^4$ find the radius of convergence for $\sum_{n=2}^\infty a_nx^n$

Could someone explain how he got inequality (1)? Theorem 4.1 stated that a power series converges if $|x| <R$.

A: The radius of convergence of the series $\sum_n b_nx^n$ is the supremum of the set $$\{t\geqslant 0, \sup_{n\geqslant 0}|b_n|t^n<+\infty\}.$$
Since
$$\{t\geqslant 0, \sup_{n\geqslant 0}n^4t^n<+\infty\}\subset
\{t\geqslant 0, \sup_{n\geqslant 0}|a_n|t^n<+\infty\}
\subset \{t\geqslant 0, \sup_{n\geqslant 0}n^3t^n<+\infty\},$$
the conclusion follows.


text:
Q: Why am i getting a straight line for exponential decay curve best-fit
Hi all,
I am trying to fit a curve of a double exponential decay function in Python. The code I have used is as follows. I am not sure why I am getting a straight line for the fit. I welcome any help and suggestions to my code, it would be of great help.
xData = np.array(xData)
yData = np.array(yData)
def double_exp(x, a1, t1, a2, t2):
    return a1*np.exp(-x/t1) + a2*np.exp(-(x-0.1) / t2)
mod=Model(double_exp)

result=mod.fit(yData,x=xData,a1=0.7,t1=0.5,a2=0.3,t2=10)
result.plot()
plt.grid()
plt.xlabel('Time')
plt.ylabel('Fluoresence Lifetime')

My sample data values for the lists xData and yData is
[![xData is \[2.50783699e-09 5.01567398e-09 7.52351097e-09 1.00313480e-08
 1.25391849e-08 1.50470219e-08 1.75548589e-08 2.00626959e-08
 2.25705329e-08... etc\]
yData is \[ 1025.  1032.  1101.  1138.  1205.  1086.  1692. 13515. 59434. 82067.64293. 52266. 43993. 35335. 30066. 29989. 33773. 30521. 26468. 26338.27233. 26276. 24109....etc\]][1]][1]

A: I apologize to all reading this for answering here a little outside the norms of StackOverflow.  This is more like a long comment than an answer, related to the fact that the poster has asked many similar questions about using the lmfit library over the past few months.
@Angela Mary You're probably getting a straight line because your initial values are not close enough to be refined.
When using lmfit, you absolutely must provide realistic initial values for all parameters to be optimized.  There are no circumstances under which this can be neglected.  If you are remotely unsure if your initial values are reasonable, plot the data and the model with the initial parameter values before trying a fit.  When doing a fit, you are asserting that you know the initial values are reasonable values for approximating your data.
A corollary: it is not a mistake of the algorithms or library that it fails to find a good solution when you give it unreasonable initial values.  This should be expected.
After a fit, always print out and read the fit report.  This contains the principle result.  A plot of the resulting fit can be useful -- a picture is worth a thousand words, as they say.  But the fit results contain the table of the fit results, and a table of numbers is worth a thousand pictures.  Let me repeat: ALWAYS PRINT OUT AND ACTUALLY READ THE FIT REPORT.  Do not post questions about the results of lmfit where this report is not included.
The emphasis on StackOverflow is on coding. Questions should emphasize how to use the library, not the results it gives.  This means that you are not likely to get very meaningful answers about why a model does not match particular data.  Pose questions about how to do things.
Since the forum is about coding, ALWAYS include a minimal, complete example that shows the problem.  If the phrase "minimal, complete example" is foreign to you, consider that your first homework assignment. The code posted here needs to be complete and runnable by someone else. Output reports need to be included. If you get an exception running code, post the full traceback.  Do not edit the results: post them verbatim.   These are not suggestions or "if you feel it is appropriate". These are requirements.
If you are fitting data (or doing any other calculation with data), then include that data, either in the code itself or as a readily available data file.  Since your example has already been made into a minimal, complete example, the data will not need to be very big.


text:
Q: Avoiding off-by-one errors when removing columns based on indices in a python list I have a target file called TARGFILE of the form:
10001000020002002001100100200000111
10201001020000120210101100110010011
02010010200000011100012021001012021
00102000012001202100101202100111010

My idea here was to leave this as a string, and use slicing in python to remove the indices.
The removal will occur based on a list of integers called INDICES like so:
[1, 115654, 115655, 115656, 2, 4, 134765, 134766, 18, 20, 21, 23, 24, 17659, 92573, 30, 32, 88932, 33, 35, 37, 110463, 38, 18282, 46, 18458, 48, 51, 54]

I want to remove every position of every line in TARGFILE that matches with INDICES. For instance, the first digit in INDICES is 1, so the first column of TARGFILE containing 1,1,0,0 would be removed. However, I am weary of doing this incorrectly due to off-by-one errors and changing index positions if everything is not removed at the same time.
Thus, a solution that removed every column from each row at the same time would likely be both much faster and safer than using a nested loop, but I am unsure of how to code this.
My code so far is here:
#!/usr/bin/env python
import fileinput
SRC_FILES=open('YCP.txt', 'r')

for line in SRC_FILES:
    EUR_YRI_ADM=line.strip('\n')
    EUR,YRI,ADM=EUR_YRI_ADM.split(' ')
    ADMFO=open(ADM, 'r')
    lines=ADMFO.readlines()
    INDICES=[int(val) for val in lines[0].split()]
    TARGFILE=open(EUR, 'r')

It seems to me that a solution using enumerate might be possible, but I have not found it, and that might be suboptimal in the first place...
EDIT: in response to concerns about memory: the longest lines are ~180,000 items, but I should be able to get this into memory without a problem, I have access to a cluster.

A: I like the simplicity of Peter's answer, even though it's currently off-by-one.  My thought is that you can get rid of the index-shifting problem, by sorting INDICES, and doing the process from the back to the front.  That led to remove_indices1, which is really inefficient.  I think 2 is better, but simplest is 3, which is Peter's answer.
I may do timing in a bit for some large numbers, but my intuition says that my remove_indices2 will be faster than Peter's remove_indices3 if INDICES is very sparse.  (Because you don't have to iterate over each character, but only over the indices that are being deleted.)
BTW - If you can sort INDICES once, then you don't need to make the local copy to sort/reverse, but I didn't know if you could do that.
rows = [
    '0000000001111111111222222222233333333334444444444555555555566666666667',
    '1234567890123456789012345678901234567890123456789012345678901234567890',
    ]

def remove_nth_character(row,n):
    return row[:n-1] + row[n:]

def remove_indices1(row,indices):
    local_indices = indices[:]
    retval = row
    local_indices.sort()
    local_indices.reverse()
    for i in local_indices:
        retval = remove_nth_character(retval,i)
    return retval

def remove_indices2(row,indices):
    local_indices = indices[:]
    local_indices.sort()
    local_indices.reverse()
    front = row
    chunks = []
    for i in local_indices:
        chunks.insert(0,front[i:])
        front = front[:i-1]
    chunks.insert(0,front)
    return "".join(chunks)

def remove_indices3(row,indices):
    return ''.join(c for i,c in enumerate(row) if i+1 not in indices)

indices = [1,11,4,54,33,20,7]

for row in rows:
    print remove_indices1(row,indices)
print ""
for row in rows:
    print remove_indices2(row,indices)
print ""
for row in rows:
    print remove_indices3(row,indices)

EDIT:  Adding timing info, plus a new winner!
As I suspected, my algorithm (remove_indices2) wins when there aren't many indices to remove.  It turns out that the enumerate-based one, though, gets worse even faster as there are more indices to remove.  Here's the timing code (bigrows rows have 210000 characters):
bigrows = []
for row in rows:
    bigrows.append(row * 30000)

for indices_len in [10,100,1000,10000,100000]:
    print "indices len: %s" % indices_len
    indices = range(indices_len)
    #for func in [remove_indices1,remove_indices2,remove_indices3,remove_indices4]:
    for func in [remove_indices2,remove_indices4]:
        start = time.time()
        for row in bigrows:
            func(row,indices)
        print "%s: %s" % (func.__name__,(time.time() - start))

And here are the results:
indices len: 10
remove_indices1: 0.0187089443207
remove_indices2: 0.00184297561646
remove_indices3: 1.40601491928
remove_indices4: 0.692481040955
indices len: 100
remove_indices1: 0.0974130630493
remove_indices2: 0.00125503540039
remove_indices3: 7.92742991447
remove_indices4: 0.679095029831
indices len: 1000
remove_indices1: 0.841033935547
remove_indices2: 0.00370812416077
remove_indices3: 73.0718669891
remove_indices4: 0.680690050125

So, why does 3 do so much worse?  Well, it turns out that the in operator isn't efficient on a list.  It's got to iterate through all of the list items to check.  remove_indices4 is just 3 but converting indices to a set first, so the inner loop can do a fast hash-lookup, instead of iterating through the list:
def remove_indices4(row,indices):
    indices_set = set(indices)
    return ''.join(c for i,c in enumerate(row) if i+1 not in indices_set)

And, as I originally expected, this does better than my algorithm for high densities:
indices len: 10
remove_indices2: 0.00230097770691
remove_indices4: 0.686790943146
indices len: 100
remove_indices2: 0.00113391876221
remove_indices4: 0.665997982025
indices len: 1000
remove_indices2: 0.00296902656555
remove_indices4: 0.700706005096
indices len: 10000
remove_indices2: 0.074893951416
remove_indices4: 0.679219007492
indices len: 100000
remove_indices2: 6.65899395943
remove_indices4: 0.701599836349

If you've got fewer than 10000 indices to remove, 2 is fastest (even faster if you do the indices sort/reverse once outside the function).  But, if you want something that is pretty stable in time, no matter how many indices, use 4.

A: The simplest way I can see would be something like:
>>> for line in TARGFILE:
...     print ''.join(c for i,c in enumerate(line) if (i+1) not in INDICES)
...
100000200020020100200001
100010200001202010110001
010102000000111021001021
000000120012021012100110

(Substituting print for writing to your output file etc)
This relies on being able to load each line into memory which may or may not be reasonable given your data.
Edit: explaination:
The first line is straightforward:
>>> for line in TARGFILE:

Just iterates through each line in TARGFILE. The second line is a bit more complex:

*

*''.join(...) concatenates a list of strings together with an empty joiner (''). join is often used with a comma like: ','.join(['a', 'b', 'c']) == 'a,b,c', but here we just want to join each item to the next.

*enumerate(...) takes an interable and returns pairs of (index, item) for each item in the iterable. For example enumerate('abc') == (0, 'a'), (1, 'b'), (2, 'c')
So the line says,

Join together each character of line whose index are not found in INDICES

However, as John pointed out, Python indexes are zero base, so we add 1 to the value from enumerate.

A: The script I ended up using is the following:
#!/usr/bin/env python

def remove_indices(row,indices):
    indices_set = set(indices)
    return ''.join(c for i,c in enumerate(row) if (i+1) in indices_set)

SRC_FILES=open('YCP2.txt', 'r')

CEUDIR='/USER/ScriptsAndLists/LAMP/LAMPLDv1.1/IN/aps/4bogdan/omni/CEU/PARSED/'
YRIDIR='/USER/ScriptsAndLists/LAMP/LAMPLDv1.1/IN/aps/4bogdan/omni/YRI/PARSED/'
i=0
for line in SRC_FILES:
        i+=1
    EUR_YRI_ADM=line.strip('\n')
        EUR,YRI,ADM=EUR_YRI_ADM.split('\t')
        ADMFO=open(ADM, 'r')

        lines=ADMFO.readlines()
        INDICES=[int(val) for val in lines[0].split()]
        INDEXSORT=sorted(INDICES, key=int)

        EURF=open(EUR, 'r')
        EURFOUT=open(CEUDIR + 'chr' + str(i) + 'anc.hap.txt' , 'a')
        for haplotype in EURF:
                TRIMLINE=remove_indices(haplotype, INDEXSORT)
                EURFOUT.write(TRIMLINE + '\n')
        EURFOUT.close()

        AFRF=open(YRI, 'r')
        AFRFOUT=open(YRIDIR + 'chr' + str(i) + 'anc.hap.txt' , 'a')
        for haplotype2 in AFRF:
                TRIMLINE=remove_indices(haplotype2, INDEXSORT)
                AFRFOUT.write(TRIMLINE + '\n')
        AFRFOUT.close()


text:
Q: Use #define macro in C++ to choose implementations from different namespaces The multiplatform engine we're developing for our game uses the EASTL to replace the STL, because of memory, performance and portability reasons. The EASTL can be found here:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html
Because Visual Studio is really good for debugging the STL we're not using the EASTL on Windows while the engine is in development. Also some STL containers as std::queue, std::deque, ... aren't available in the EASTL. Because it doesn't matter we're using the eastl::string on Windows as well, because it's fine for debugging.
What we're doing until now is
#if (GIN_USE_EASTL)
    #define ginstl eastl
#else
    #define ginstl std
#endif

and GIN_USE_EASTL is defined as 0 on windows. The engine is called Ginkgo, thats where the GIN comes from.
We're using lists, vectors, ... like this
ginstl::list myList;
ginstl::vector myVector;

which works quite fine. But when we use a string or a queue, because of reasons I explained above, we have to write
eastl::string myString;
std::queue myQueue;

which is the reason why i'm posting here, because this is not optimal! What I want to do is use the ginstl:: macro for everything in the engine, without thinking about what implementation to use. So my approach on the problem was this:
#if (GIN_USE_EASTL)
    #define ginstl::list eastl::list
    #define ginstl::vector eastl::vector
    #define ginstl::string eastl::string
    #define ginstl::queue std::queue
#else
    #define ginstl::list std::list
    #define ginstl::vector std::vector
    #define ginstl::string eastl::string
    #define ginstl::queue std::queue
#endif

But unfortunalty that's not working, because the :: is not allowed in the #define macro.
Is there any way to achieve the same thing (be able to specify which implementation I want to use for a specific datastructure) somehow different? I could go for
#define ginstl_list eastl::list

but I would prefer the structure from above! Is there a way (except writing a custom pre-processor) around the problem?

A: What about using namespace:
namespace ginstl
{
#if (GIN_USE_EASTL)
    using eastl::list
    using eastl::vector
    using eastl::string
    using std::queue
#else
    using std::list
    using std::vector
    using eastl::string
    using std::queue
#endif
}

A: Developing further on the Mark B's way (no need to list all types used):
namespace ginstl
{
#if (GIN_USE_EASTL)
    using namespace eastl;
#else
    using namespace std;
#endif
    using eastl::string
    using std::queue
}

A: If you use namespace aliases instead of macros:
#if (GIN_USE_EASTL)
    namespace ginstl = eastl;
#else
    namespace ginstl = std;
#endif

You can then do this:
using namespace ginstl;
using std::queue;
using std::deque;

list<int> x; // from eastl or std, depending on GIN_USE_EASTL
queue<int> y; // always from std