text:
Q: Are binaries portable across different CPU architectures? My goal is to be able to develop for embedded Linux. I have experience on bare-metal embedded systems using ARM.
I have some general questions about developing for different cpu targets. My questions are as below:

*

*If I have an application compiled to run on a 'x86 target, linux OS version x.y.z', can I just run the same compiled binary on another system 'ARM target, linux OS version x.y.z'?

*If above is not true, the only way is to get the application source code to rebuild/recompile using the relevant toolchain 'for example, arm-linux-gnueabi'?

*Similarly, if I have a loadable kernel module (device driver) that works on a 'x86 target, linux OS version x.y.z', can I just load/use the same compiled .ko on another system 'ARM target, linux OS version x.y.z'?

*If above is not true, the only way is to get the driver source code to rebuild/recompile using the relevant toolchain 'for example, arm-linux-gnueabi'?

A: Note that as a last resort (i.e. when you don't have the source code), you can run binaries on a different architecture using emulators like qemu, dosbox or exagear. Some emulators are designed to emulate systems other than Linux (e.g. dosbox is designed to run MS-DOS programs, and there are plenty of emulators for popular gaming consoles). Emulation has a significant performance overhead: emulated programs run 2-10 times slower than their native counterparts.
If you need to run kernel modules on a non-native CPU, you'll have to emulate the whole OS including the kernel for the same architecture. AFAIK it's impossible to run foreign code inside Linux kernel.

A: Not only are binaries not portable between x86 and ARM, there are different flavours of ARM.
The one you are likely to encounter in practice is ARMv6 vs ARMv7. Raspberry Pi 1 is ARMv6, later versions are ARMv7. So it's possible to compile code on the later ones that does not work on the Pi 1.
Fortunately one benefit of open source and Free software is having the source so that you can rebuild it on any architecture. Although this may require some work.
(ARM versioning is confusing, but if there's a V before the number it's talking about the instruction set architecture (ISA). If there isn't, it's a model number like "Cortex M0" or "ARM926EJS". Model numbers have nothing to do with ISA numbers.)

A: You always need to target a platform. In the simplest case, the target CPU directly runs the code compiled in the binary (this roughly corresponds to MS DOS's COM executables). Let's consider two different platforms I just invented - Armistice and Intellio. In both cases, we'll have a simple hello world program that outputs 42 on the screen. I'll also assume that you're using a multi-platform language in a platform-agnostic manner, so the source code is the same for both:
Print(42)

On Armistice, you have a simple device driver that takes care of printing numbers, so all you have to do is output to a port. In our portable assembly language, this would correspond to something like this:
out 1234h, 42

However, or Intellio system has no such thing, so it has to go through other layers:
mov a, 10h
mov c, 42
int 13h

Oops, we already have a siginificant difference between the two, before we even  get to machine code! This would roughly correspond to the kind of difference you have between Linux and MS DOS, or an IBM PC and an X-Box (even though both may use the same CPU).
But that's what OSes are for. Let's assume we have a HAL that makes sure that all different hardware configurations are handled the same way on the application layer - basically, we'll use the Intellio approach even on the Armistice, and our "portable assembly" code ends up the same. This is used by both modern Unix-like systems and Windows, often even in embedded scenarios. Good - now we can have the same truly portable assembly code on both Armistice and Intellio. But what about the binaries?
As we've assumed, the CPU needs to execute the binary directly. Let's look at the first line of our code, mov a, 10h, on Intellio:
20 10

Oh. Turns out that mov a, constant is so popular it has its own instruction, with its own opcode. How does Armistice handle this?
36 01 00 10

Hmm. There's the opcode for mov.reg.imm, so we need another argument to select the register we're assigning to. And the constant is always a 2-byte word, in big-endian notation - that's just how Armistice was designed, in fact, all instructions in Armistice are 4 bytes long, no exceptions.
Now imagine running the binary from Intellio on Armistice: the CPU starts decoding the instruction, finds opcode 20h. On Armistice, this corresponds, say, to the and.imm.reg instruction. It tries to read the 2-byte word constant (which reads 10XX, already a problem), and then the register number (another XX). We're executing the wrong instruction, with the wrong arguments. And worse, the next instruction will be complete bogus, because we actually ate another instruction, thinking it was data.
The application has no chance of working, and it will most likely crash or hang almost immediately.
Now, this doesn't mean that an executable always needs to say it runs on Intellio or Armistice. You just need to define a platform that's independent of the CPU (like bash on Unix), or both the CPU and OS (like Java or .NET, and nowadays even JavaScript, kind of). In this case, the application can use one executable for all the different CPUs and OSes, while there's some application or service on the target system (which targets the correct CPU and/or OS directly) that translates the platform-independent code into something the CPU can actually execute. This may or may not come with a hit to performance, cost or capability.
CPUs usually come in families. For example, all CPUs from the x86 family have a common set of instructions that are encoded in exactly the same way, so every x86 CPU can run every x86 program, as long as it doesn't try to use any extensions (for example, floating point operations or vector operations). On x86, the most common examples today are Intel and AMD, of course. Atmel is a well known company designing CPUs in the ARM family, quite popular for embedded devices. Apple also has ARM CPUs of their own, for example.
But ARM is utterly incompatible with x86 - they have very different design requirements, and have very little in common. The instructions have entirely different opcodes, they are decoded in a different manner, the memory addresses are treated differently... It might be possible to make a binary that runs on both an x86 CPU and an ARM CPU, by using some safe operations to distinguish between the two and jumping to two completely different sets of instructions, but it still means you have separate instructions for both versions, with just a bootstrapper that picks the correct set at runtime.

A: No. Binaries must be (re)compiled for the target architecture, and Linux offers nothing like fat binaries out of the box. The reason is because the code is compiled to machine code for a specific architecture, and machine code is very different between most processor families (ARM and x86 for instance are very different).
EDIT: it is worth noting that some architectures offer levels of backwards compatibility (and even rarer, compatibility with other architectures); on 64-bit CPU's, it's common to have backwards compatibility to 32-bit editions (but remember: your dependent libraries must also be 32-bit, including your C standard library, unless you statically link). Also worth mentioning is Itanium, where it was possible to run x86 code (32-bit only), albeit very slowly; the poor execution speed of x86 code was at least part of the reason it wasn't very successful in the market.
Bear in mind that you still cannot use binaries compiled with newer instructions on older CPU's, even in compatibility modes (for example, you cannot use AVX in a 32-bit binary on Nehalem x86 processors; the CPU just doesn't support it.
Note that kernel modules must be compiled for the relevant architecture; in addition, 32-bit kernel modules will not work on 64-bit kernels or vice versa.
For information on cross-compiling binaries (so you don't have to have a toolchain on the target ARM device), see grochmal's comprehensive answer below.

A: It's possible to re-cast this question into an environment that might be more familiar.  By analogy:
"I have a Ruby program that I want to run, but my platform only has a Python interpreter.  Can I use the Python interpreter to run my Ruby program, or do I have to rewrite my program in Python?"
An instruction set architecture ("target") is a language -- a "machine language" -- and different CPUs implement different languages.  So asking an ARM CPU to run an Intel binary is very much like trying to run a Ruby program using a Python interpreter.

A: gcc uses the terms ''architecture'' to mean the ''instruction set'' of a specific CPU, and "target" covers the combination of CPU and architecture, along with other variables such as ABI, libc, endian-ness and more (possibly including "bare metal"). A typical compiler has a limited set of target combinations (probably one ABI, one CPU family, but possibly both 32- and 64-bit). A cross-compiler usually means either a compiler with a target other than the system it runs on, or one with multiple targets or ABIs (see also this).

Are binaries portable across different CPU architectures?

In general, no. A binary in conventional terms is native object code for a particular CPU or CPU family. But, there are several cases where they might be moderately to highly portable:

*

*one architecture is a superset of another (commonly x86 binaries target i386 or i686 rather than the latest and greatest x86, e.g. -march=core2)

*one architecture provides native emulation or translation of another (you might have heard of Crusoe), or provides compatible co-processors (e.g. PS2)

*the OS and runtime support multiarch (e.g. ability to run 32-bit x86 binaries on x86_64), or make the VM/JIT seamless (Android using Dalvik or ART)

*there is support for "fat" binaries which essentially contain duplicate code for each supported architecture

If you somehow manage to solve this problem, the other portable binary problem of myriad library versions (glibc I'm looking at you) will then present itself. (Most embedded systems save you from that particular problem at least.)
If you haven't already, now is a good time to run gcc -dumpspecs and gcc --target-help to see what you're up against.
Fat binaries have various drawbacks, but still have potential uses (EFI).
There are two further considerations is missing from the other answers however: ELF and the ELF interpreter, and the Linux kernel support for arbitrary binary formats. I won't go into detail about binaries or bytecode for non-real processors here, though it is possible to treat these as "native" and execute Java or compiled Python bytecode binaries, such binaries are independent of the hardware architecture (but depend instead on the relevant VM version, which ultimately runs a native binary).
Any contemporary Linux system will use ELF binaries (technical details in this PDF), in the case of dynamic ELF binaries the kernel is in charge of loading the image into memory but it is the job of the ''interpreter'' set in the ELF headers to do the heavy lifting. Normally this involves making sure all the dependent dynamic libraries are available (with the help of the ''Dynamic'' section which lists the libraries and some other structures which list the required symbols) — but this is almost a general purpose indirection layer.
$ file /bin/ls
/bin/ls: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses \
shared libs), stripped
$ readelf -p .interp /bin/ls
    String dump of section '.interp':
      [     0]  /lib/ld-linux.so.2

(/lib/ld-linux.so.2 is also an ELF binary, it does not have an interpreter, and is native binary code.)
The problem with ELF is that the header in the binary (readelf -h /bin/ls) marks it for a specific architecture, class (32- or 64-bit), endian-ness and ABI
(Apple's "universal" fat binaries use an alternate binary format Mach-O instead which solves this problem, this originated on NextSTEP).
This means that an ELF executable must match the system it is to be run on.
One escape hatch is the interpreter, this can be any executable (including one that extracts or maps architecture specific subsections of the originally binary and invokes them), but you still are constrained by the type(s) of ELF your system will allow to run. (FreeBSD has an interesting way of handling Linux ELF files, its brandelf modifies the ELF ABI field.)
There is (using binfmt_misc) support for Mach-O on linux, there's an example there that shows you how to create and run a fat (32- & 64-bit) binary. Resource forks/ADS, as originally done on the Mac, could be a workaround, but no native Linux filesystem supports this.
More or less the same thing applies to kernel modules, .ko files are also ELF (though they have no interpreter set). In this case there's an extra layer which uses the kernel version (uname -r) in the search path, something that could theoretically be done instead in ELF with versioning, but at some complexity and little gain I suspect.
As noted elsewhere, Linux does not natively support fat binaries, but there
is an active fat-binary project: FatELF. It's been around for years, it was never integrated into the standard kernel partly due to (now expired) patent concerns.
At this time it requires both kernel and toolchain support.
It does not use the binfmt_misc approach, this side-steps the ELF header issues and allows for fat kernel modules too.

*

*If i have an application compiled to run on a 'x86 target, linux OS version x.y.z', can i just run the same compiled binary on another system 'ARM target, linux OS version x.y.z'?

Not with ELF, it won't let you do this.

*If above is not true, the only way is to get the application source code to rebuild/recompile using the relevant toolchain 'for example, arm-linux-gnueabi'?

The simple answer is yes. (Complicated answers include emulation, intermediate representations, translators and JIT; except for the case of "downgrading" an i686 binary to only use i386 opcodes they're probably not interesting here, and the ABI fixups are potentially as hard as translating native code.)

*Similarly, if i have a loadable kernel module (device driver) that works on a 'x86 target, linux OS version x.y.z', can i just load/use the same compiled .ko on another system 'ARM target, linux OS version x.y.z'?

No, ELF won't let you do this.

*If above is not true, the only way is to get the driver source code to rebuild/recompile using the relevant toolchain 'for example, arm-linux-gnueabi'?

The simple answer is yes. I believe FatELF lets you build a .ko that is multi-architecture, but at some point a binary version for every supported architecture has to be created. Things which require kernel modules often  come with the source, and are build as required, e.g. VirtualBox does this.
This is already a long rambling answer, there's only one more detour. The kernel already has a virtual machine built in, albeit a dedicated one: the BPF VM which is used to match packets. The human readable filter "host foo and not port 22") is compiled to a bytecode and the kernel packet filter executes it. The new eBPF is not just for packets, in theory that VM code is portable across any contemporary linux, and llvm supports it but for security reasons it's probably not going to be suitable for anything other than administrative rules.

Now, depending on how generous you are with the definition of a binary executable, you can (ab)use binfmt_misc to implement fat binary support with a shell script, and ZIP files as a container format:
#!/bin/bash

name=$1
prog=${1/*\//}      # basename
prog=${prog/.woz/}  # remove extension
root=/mnt/tmpfs
root=$(TMPDIR= mktemp -d -p ${root} woz.XXXXXX)
shift               # drop argv[0], keep other args

arch=$(uname -m)                  # i686
uname_s=$(uname -s)               # Linux
glibc=$(getconf GNU_LIBC_VERSION) # glibc 2.17
glibc=${glibc// /-}               # s/ /-/g

# test that "foo.woz" can unzip, and test "foo" is executable
unzip -tqq "$1" && {
  unzip -q -o -j -d ${root} "$1"  "${arch}/${uname_s}/${glibc}/*"
  test -x ${root}/$prog && (
    export LD_LIBRARY_PATH="${root}:${LD_LIBRARY_PATH}"
    #readlink -f "${root}/${prog}"   # for the curious
    exec -a "${name}" "${root}/${prog}" "$@"
  )
  rc=$?
  #rm -rf -- "${root}/${prog}"       # for the brave
  exit $rc
}

Call this "wozbin", and set it up with something like:
mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc
printf ":%s:%s:%s:%s:%s:%s:%s" \
  "woz" "E" "" "woz" "" "/path/to/wozbin" ""  > /proc/sys/fs/binfmt_misc/register

This registers .woz files with the kernel, the wozbin script is invoked instead with its first argument set to the path of an invoked .woz file.
To get a portable (fat) .woz  file, simply create a test.woz ZIP file with a directory hierarchy so:
i686/
    \- Linux/
            \- glibc-2.12/
armv6l/
    \- Linux/
            \- glibc-2.17/

Within each arch/OS/libc directory (an arbitrary choice) place the architecture-specific test binary and components such as .so files.
When you invoke it the required subdirectory is extracted in to a tmpfs in-memory filesystem (on /mnt/tmpfs here) and invoked.
Update: see also the Cosmopolitan project which has a similar idea, and provides a solution for multi-platform executables using a polyglot format.

A: Elizabeth Myers is correct, each architecture requires a compiled binary for the architecture in question.  To build binaries for a different architecture than your system runs on you need a cross-compiler.

In most cases you need to compile a cross compiler.  I only have experience with gcc (but I believe that llvm,  and other compilers, have similar parameters).  A gcc cross-compiler is achieved by adding --target to the configure:
./configure --build=i686-arch-linux-gnu --target=arm-none-linux-gnueabi

You need to compile gcc, glibc and binutils with these parameters (and provide the kernel headers of the kernel at the target machine).
In practice this is considerably more complicated and different build errors pop out on different systems.
There are several guides out there on how to compile the GNU toolchain but I'll recommend the Linux From Scratch, which is continuously maintained and does a very good job at explaining what the presented commands do.
Another option is a bootstrap compilation of a cross-compiler.  Thanks to the struggle of compiling cross compilers to different architectures on different architectures crosstool-ng was created.  It gives a bootstrap over the toolchain needed to build a cross compiler.
crosstool-ng supports several target triplets on different architectures, basically it is a bootstrap where people dedicate their time to sort out problems occurring during the compilation of a cross-compiler toolchain.

Several distros provide cross-compilers as packages:

*

*arch provides a mingw cross-compiler and and an arm eabi cross compiler out of the box.  Apart from other cross compilers in AUR.

*fedora contains several packaged cross-compilers.

*ubuntu provides an arm cross-compiler too.

*debian has an entire repository of cross-toolchains
In other words, check what your distro has available in terms of cross compilers.  If your distro does not have a cross compiler for your needs you can always compile it yourself.
References:

*

*ubuntu: Cross-Compile for ARM?

Kernel modules note
If you are compiling your cross-compiler by hand, you have everything you need to compile kernel modules.  This is because you need the kernel headers to compile glibc.
But, if you are using a cross-compiler provided by your distro, you will need the kernel headers of the kernel that runs on the target machine.

A: berry boot, solve some of your problems.. but it not resoplve problem how to run on arm hf , normall/regullAr linux distro for x86-32/64bit.
I think it should be built in in isolinux(boatloader linux on usb) some live converter
what could recognize regullar distro and in ride/live convert to hf.
Why?
Because if each linux can be converted by berry boot to working on arm-hf so it could be able to build in bery boot mechanism to isolinux what we boot using for exaple eacher or built in ubuntu creat start up disk.


text:
Q: Different results in the sum of a geometric sequence
Im studing the following geometric sequence:
$$a_1=1+b^2+b^4$$
$$a_2=1+b^2+b^4+b^6+b^8$$
$$a_3=1+b^2+b^4+b^6+b^8+b^{10}+b^{12}$$

This leads me to the following general term:
$$a_n=1+b^2+b^4+\cdots+b^{4n}$$
In this case, the ratio $r$ is $b^2$. The sum $s$ of $n$ terms of a geometric sequence can be calculated with $(1)$ and $(2)$, which are equivalent:
$$\tag{1} \space s=a_1*\left(\frac{r^n-1}{r-1}\right)$$
$$\tag{2}s=\frac{a_n * r-a_1}{r-1}$$
Substituting in $(1)$ leads to: $\displaystyle\frac{b^{2n}-1}{b^2-1}$
Substituting in $(2)$ leads to: $\displaystyle\frac{b^{4n+2}-1}{b^2-1}$
The correct sum is obtained substituting in $(2)$ but I don't see the mistake made by substituting in $(1)$ and it bothers me to make the mistake in other cases.
Any help will be welcome.
Thanks

A: Personally I use this formula $\displaystyle\sum\limits_{i=0}^n r^i=\dfrac{1-r^{n+1}}{1-r}$.
Also it seems to me that your $a_1$ and $a_n$ in the formulas (1) and (2) are not the same as the ones above...
Anyway $\displaystyle a_n=\sum\limits_{i=0}^{2n} b^{2i}=\dfrac{1-(b^2)^{2n+1}}{1-b^2}=\dfrac{1-b^{4n+2}}{1-b^2}$
The mistake originates from the bounds of your sum, you used $n$ while the sum actually goes up to $2n$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I use pinch zoom without calling my swipe function in webview? When I use the pinch zoom gesture, in a horizontal way, the swipe function is always called when it reached a certain difference of the pressed coordinates and the released coordinates.
How can I fix this?
This are the settings for the webview
    view.getSettings().setBuiltInZoomControls(true);
    view.getSettings().setSupportZoom(true);
    view.getSettings().setDisplayZoomControls(false);

The swipe function
    protected void swipePage(View v, MotionEvent event, int book) {
    int action = MotionEventCompat.getActionMasked(event);

    switch (action) {
    case (MotionEvent.ACTION_DOWN):
        swipeOriginX = event.getX();
        swipeOriginY = event.getY();
        break;

    case (MotionEvent.ACTION_UP):
        int quarterWidth = (int) (screenWidth * 0.3);
        float diffX = swipeOriginX - event.getX();
        float diffY = swipeOriginY - event.getY();
        float absDiffX = Math.abs(diffX);
        float absDiffY = Math.abs(diffY);

        if ((diffX > quarterWidth) && (absDiffX > absDiffY)) {
            try {
                navigator.goToNextChapter(index);
            } catch (Exception e) {
                errorMessage(getString(R.string.error_cannotTurnPage));
            }
        } else if ((diffX < -quarterWidth) && (absDiffX > absDiffY)) {
            try {
                navigator.goToPrevChapter(index);
            } catch (Exception e) {
                errorMessage(getString(R.string.error_cannotTurnPage));
            }
        }
        break;
    }
}

A: check if this work - put a if condition checking if single finger touch is there then only do the swipe. change "event" variable to your local variable.
 if(event.getPointerCount() == 1)
  {
    switch (action) {
     case (MotionEvent.ACTION_DOWN):
          swipeOriginX = event.getX();
          swipeOriginY = event.getY();
           break;

    case (MotionEvent.ACTION_UP):

    int quarterWidth = (int) (screenWidth * 0.3);
    float diffX = swipeOriginX - event.getX();
    float diffY = swipeOriginY - event.getY();
    float absDiffX = Math.abs(diffX);
    float absDiffY = Math.abs(diffY);

    if ((diffX > quarterWidth) && (absDiffX > absDiffY)) {
        x = 1;
        try {
            navigator.goToNextChapter(index);
            x = 0;
        } catch (Exception e) {
            x = 1;
            errorMessage(getString(R.string.error_cannotTurnPage));
        }
    } else if ((diffX < -quarterWidth) && (absDiffX > absDiffY)) {
        x = 1;
        try {
            navigator.goToPrevChapter(index);
            x = 0;
        } catch (Exception e) {
            x = 1;
            errorMessage(getString(R.string.error_cannotTurnPage));
        }

    break;
    }
  }
}
else if(event.getPointerCount()==2)
 {
   // code for pinch zoom
 }


text:
Q: Is there a JavaScript equivalent to "string" . "string" in PHP? I am currently learning a little bit of JavaScript and had a question.
In PHP, I am used to binding text and strings together with a simple dot like this:
echo "Text" . $String . "anotherText" . $anotherString

Is this possible in JavaScript? (Not the echo, but the binding of the strings and text.)

A: The + is the concatenation operator in JavaScript:
"Text" + somestring + "anotherText" + anotherString;

A: Yes just, add:
'Text' + str + 'anotherText' + anotherString;

A: In JavaScript it's + instead of .
Example 1:
document.write("Text" + somestring + "anotherText" + anotherString);

Example 2:
alert("Text" + somestring + "anotherText" + anotherString);

Example 3:
var john = "Text" + somestring + "anotherText" + anotherString;


text:
Q: Ubuntu 16.04: appstreamcli error while get-update I am trying to enable WiFi. I tried sudo apt-get update. But I am getting this error:
The AppStream system cache was updated, but some errors were detected, which might lead to missing metadata. Refer to the verbose log for more information.
Reading package lists... Done
E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/cache/app-info -a -e /usr/bin/appstreamcli; then appstreamcli refresh-cache > /dev/null; fi'
E: Sub-process returned an error code

How can I complete sudo apt-get update and enable Wifi in Ubuntu-16.04?

A: A similar bug was reported here
This answer suggested the below in order to solve it (a few people said that it helped them):

Removing /usr/bin/appstreamcli is fine if you install the fixed package afterwards.
To install this manually, please do (for amd64, adjust URLs for other architectures):
cd /tmp && mkdir asfix
cd asfix
wget https://launchpad.net/ubuntu/+archive/primary/+files/appstream_0.9.4-1ubuntu1_amd64.deb
wget https://launchpad.net/ubuntu/+archive/primary/+files/libappstream3_0.9.4-1ubuntu1_amd64.deb
sudo dpkg -i *.deb

A: I have had the same problem and the problem was that there was (in my case) an inappropriately escaped character in file /var/cache/app-info/xmls/fwupd.xml in line 265 which broke the xml, hence the error. In line <checksum filename="Firmware_SF30&SN30_Pro_V1.26.dat" target="content" type="sha1">3ef2bdee8aca2a45b9f53b4d4cce9722523f57f8</checksum> the & symbol must be encoded & for this to be a valid xml.

A: While this is not backported to xenial, one can upgrade libappstream-glib8 to the version in bionic and set up to receive upgrades for this package (but not the rest) from bionic.
Procedure
If you find yourself in one of the cases marked ABORT, just undo all the steps you did so far and run sudo apt update at the end (I don't expect that to happen though, they are just there as a safeguard).

*

*save a file called (say) future.list in dir /etc/apt/sources.list.d (you'll need sudo) with the following content:
deb mirror://mirrors.ubuntu.com/mirrors.txt bionic main
deb mirror://mirrors.ubuntu.com/mirrors.txt bionic-updates main
deb mirror://mirrors.ubuntu.com/mirrors.txt bionic-security main

*save a file called (say) future.pref in dir /etc/apt/preferences.d (you'll need sudo again) with the following content:
Package: *
Pin: release a=bionic*
Pin-Priority: 50

*sudo apt update

*apt list -u and confirm it returns only "Listing... Done". If it returns more stuff, ABORT (see above).

*sudo apt install -assume-no -t=bionic libappstream-glib8. If, at this stage, apt claims that more is needed to satisfy dependencies than just replacing the old version with the new one, ABORT (see above).

*sudo mv /var/cache/app-info/xmls/fwupd.xml ~/fwupd.xml.bck

*restart (I found this was required, probably to load the new shared library version, maybe restart some service)

*sudo fwupdmgr refresh

*sudo appstreamcli refresh


text:
Q: hibernate createSQLQuery doesn't have addEntity method I'm trying to use the addEntity method of a hibernate Query, but it only has a "setEntity" method?
  Query query = session.createSQLQuery("...");
  query.addEntity(MyClass.class); // doesn't exist, but setEntity method does?

A: Turns out you either have to use the right class, this works:
  SQLQuery sqlQuery = session.createSQLQuery("...");
  sqlQuery.addEntity(MyClass.class);

Or chain it, this works:
  Query query = session.createSQLQuery("...").addEntity(MyClass.class);


text:
Q: Curve translation in Python does not reach expected value Suppose I have two curves, f(x) and g(x), and I want to evaluate if g(x) is a translation of f(x).
I used Sympy Curve to do the job with the function translate. However, I need help to reach the correct result. Consider the two functions:
f(x) = -x^2 and g(x) = -(x+5)^2 + 8
Notice that g is vertically translated by 8 and horizontally translated by 5. Why at is not equal to b in the following Python code?
from sympy import expand, Symbol, Curve, oo

x = Symbol('x')
f = -x**2
g = -(x+5)**2+8

a = Curve((x, f), (x, -oo, oo))
at = a.translate(5,8)
b = Curve((x, g), (x, -oo, oo))

a, at, b, at == b

>>> (Curve((x, -x**2), (x, -10, 10)),
 Curve((x + 5, 8 - x**2), (x, -10, 10)),
 Curve((x, 8 - (x + 5)**2), (x, -10, 10)),
 False)

How could I make this analysis work using this or any other method?

A: Curve is probably not the right way to do this. If you have univariate functions for which you want to know a x and y translation will make them equal, you could use something like the following:
>>> dx,dy = Symbols('dx dy')
>>> eq = Eq(f.subs(x,x-dx)+dy)
>>> solve_undetermined_coeffs(eq,g),(dx,dy),x)
[(-5, 8)]

If there are no values of dx and dy that will solve the equality, then an empty list will be returned.

A: Thanks to @smichr for the reference about solve_undetermined_coeffs. Here you can find a full answer to my initial problem in Python 3.8.10 and Sympy 1.11.1.
from sympy import symbols, Eq, solve_undetermined_coeffs

x, dx, dy = symbols('x dx dy')
f = -x**2
g = -(x+5)**2+8

eq = Eq(f.subs(x,x-dx)+dy,g)
solve_undetermined_coeffs(eq,[dx,dy],x)


text:
Q: How to get top 2 customers from customer table using mysql? In customer table:
ID|   Name   |   Cost
-------------------------
 1|   name1  |   1000
 2|   name2  |   200
 3|   name3  |   700
 4|   name2  |   700
 5|   name3  |   800

I need to find out Top 2 customers name & ID & cost from customer table who buy .
Can anyone help me ?
My expected Output :
ID|   Name   |   Cost
----------------------
 1|   name1  |   1000
 2|   name2  |   900

A: SELECT
    GROUP_CONCAT(ID) as payment_ids,
    Name,
    SUM(Cost) as total_cost
FROM
    Customer
GROUP BY
    Name
ORDER BY
    total_cost DESC
LIMIT 2


text:
Q: Sending numbers from Processing to Arduino this is my first question so i try my best to explain it good enough.
My Goal is to gather a number via processing from my website and send it to my arduino. I try to turn my led on when the number 1 comes in or turn it off when the number 0 comes in.
So far i managed to gather the number from my website.
And when i send a number with the arduino serial monitor to the arduino the arduino code works, too.
The part that is not working is the sending of the number from processing to the arduino. The led just flickers once.
Here is my processing code:
import processing.serial.*;
Serial ComPort;
String input[];
void setup(){

    String portName = Serial.list() [0];
    ComPort = new Serial(this, portName, 9600);
    ComPort.bufferUntil('\n');
    input = loadStrings("website-adresse");
    if(input.length != 0){
        String s_current = input[0];
        int current = Integer.parseInt(s_current);
        println(current);
        delay(2000);
        ComPort.write(current);
    }
}

Here is my arduino code:
void setup() {
    Serial.begin(9600);  // Baudrate, muss mit PC übereinstimmen
    pinMode(13,OUTPUT);
}
void loop() {
int c = Serial.read();
switch (c) {
case -1: return; // nichts neues gekommen, loop sofort beenden
case '0' :
  digitalWrite(13, LOW);
  break;
case '1' :
  digitalWrite(13, HIGH);
  break;
 }
 }

Iam new to programming and my english is not that good so i apologize for that.
Thanks for your help
Greetings Jenni

A: The main problem is sending values 0 (0x00) and 1 (0x01) over the ComPort but you are expecting '0' (0x30) and '1' (0x31).
If you change cases to expect 0 and 1 instead of '0' and '1' it will work (but these values won't work in Serial Monitor unless you'll have both variants)


text:
Q: Python web application with OpenCV in Heroku I am building a web application that uses OpenCV in its back-end. I have built the application on Ubuntu (and I tried it on Windows, too) and it works fine. Currently, I am trying to configure OpenCV to work on Heroku. As OpenCV is not possible to be loaded using pip, I read about using heroku buildpacks which provide customization for the server environment.
The following is my attempt to test two of OpenCV buildpacks:

*

*I build simple web server with Flask that tries to import OpenCV:
#hello.py
import os
from flask import Flask

app = Flask(__name__)
@app.route("/")
def hello():
    text = ''
    try:
        import cv2
        text = 'success'
    except:
        text = 'fail'
        pass
    return text + ' to load openCV'

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)

The above code should return either success or fail in loading OpenCV.

*Then I configured Heroku to use (heroku multi buildpack) by running the following command:
heroku buildpacks:set https://github.com/ddollar/heroku-buildpack-multi

*In the .buildpacks file (that is required by multi buildpack) I put the https://github.com/heroku/heroku-buildpack-python and https://github.com/slobdell/heroku-buildpack-python-opencv-scipy buildpacks.
The first one is for compiling a python application and for installing other modules (e.g., Flask) through pip. The second buildpack is the one that is supposed to load OpenCV.
After all, the whole application did not work!
I got (Application Error) page in Heroku as following screenshot:

I tried to use other buildpack (https://github.com/diogojc/heroku-buildpack-python-opencv-scipy) but I got the same result.
My questions are:
What is wrong in the steps I did?
How should I call (or use) OpenCV within my application in heroku?Should I use import statement or some other commands?

A: I could install by doing as follows:

*

*cd /path/to/your/dir && git init

*heroku create MYAPP (start from scratch)

*heroku config:add BUILDPACK_URL=https://github.com/ddollar/heroku-buildpack-multi.git --app MYAPP

*create .buildpacks as follows:
https://github.com/heroku/heroku-buildpack-python
https://github.com/diogojc/heroku-buildpack-python-opencv-scipy#cedar14

*git add . && git commit -m 'MESSAGE' && git push heroku master

A: For anyone seeing this today and having the same issue, switch opencv-python in your requirements.txt to opencv-python-headless. This sidesteps the problem with the problematic library file.

A: The following steps should solve the problem of openCV which you are facing -

*

*Add the heroku-buildpack-apt to the BuildPack by pasting - https://github.com/heroku/heroku-buildpack-apt to add buildpack in dasboard.
ScreenShot -
Adding through Dashboard -> Settings -> Add BuildPacks

*Then add the Aptfile in your Github base directory which contains -

libsm6
libxrender1
libfontconfig1
libice6
- one library in each line. See Example Github Link
Now build and deploy and you are ready to go!


text:
Q: How to extract data from a HTML table? I recently downloaded HtmlAgilityPack but I haven't found any real instructions on how to use it.  I have attempted to piece together some code based on some various discussion board posts and other sources.  Here is what I have so far:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim document As New HtmlAgilityPack.HtmlDocument
    document.LoadHtml("www.reuters.com/finance/stocks/overview?symbol=GOOG")

    Dim tabletag = document.DocumentNode.SelectSingleNode("//table[@class='data']/tr[1]/td[2]")
End Sub

As you can see I am working with the HTML from www.reuters.com/finance/stocks/overview?symbol=GOOG.
I am trying to extract the Beta value from this page.  This value is currently 1.04.
When I run the code above my immediate window shows this repeated 100 times:
1.04
$243,156.41
328.59
--
--
Trading Report for (GOOG). A detailed report, including free correlated market analysis, and updates.
ValuEngine Detailed Valuation Report for GOOG
GOOGLE INC CL A (GOOG)  12-months forecast
GOOGLE INC CL A (GOOG)  2-weeks forecast
Google Inc: Business description, financial summary, 3yr and interim financials, key statistics/ratios and historical ratio analysis.

I only want the first number (1.04) returned.  What am I doing wrong?  Any suggestions?

A: You need to use cookies and a proxy. The below works great for me. Let me know your thoughts:
Imports System.Net
Imports System.Web

Public Class Form1

    Public cookies As New CookieContainer

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim wreq As HttpWebRequest = WebRequest.Create("http://www.reuters.com/finance/stocks/overview?symbol=GOOG")

        wreq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5"

        wreq.Method = "get"

        Dim prox As IWebProxy = wreq.Proxy

        prox.Credentials = CredentialCache.DefaultCredentials

        Dim document As New HtmlAgilityPack.HtmlDocument
        Dim web As New HtmlAgilityPack.HtmlWeb

        web.UseCookies = True
        web.PreRequest = New HtmlAgilityPack.HtmlWeb.PreRequestHandler(AddressOf onPreReq)

        wreq.CookieContainer = cookies

        Dim res As HttpWebResponse = wreq.GetResponse()

        document.Load(res.GetResponseStream, True)

        'just for testing:
        '   Dim tabletag = document.DocumentNode.SelectNodes("//table")
        '  MsgBox(tabletag.Nodes.Count.ToString)

        'returns your field
        Dim tabletag2 = document.DocumentNode.SelectSingleNode("//td[@class='data']")
        MsgBox(tabletag2.InnerText)

    End Sub

    Private Function onPreReq(req As HttpWebRequest)

        req.CookieContainer = cookies
        Return True

    End Function
End Class


text:
Q: Multiple divs that wrap down, span 100% width across the page, are dynamic in width, and that equally wrap Ok I thought this was going to be easy... but I cannot seem to wrap my head around it.
div.Navigation {
width:9.090909090909091%;
float: left;
border:1px solid #333;
text-align:center;
}

Here is my jsfiddle with further insight into what I am trying to do. Hope it makes sense.
http://jsfiddle.net/ufntosrn/1/
Hoping this does not get crazy... be kind to me lol

A: CSS can't do this, by itself, as while it has a calc() function, it lacks any means by which the number of elements could be found, which is required for any dynamic solution. That said, if you can set the width of the elements using JavaScript then this becomes relatively easy:

// gets all the
 elements with the class of 'Navigation':
var navigationElems = document.querySelectorAll('div.Navigation'),
    // determines the percentage (of the appropriate parent element):
    width = 100/navigationElems.length;

// iterates over the array-like navigationElems NodeList, using
// Array.prototype.forEach():
Array.prototype.forEach.call(navigationElems, function (div) {
  // div is the current
 element, here
  // setting its width to that of the width variable, in percent:
    div.style.width = width + '%';
});
body {
  margin: 0px;
}
div.Navigation {
  float: left;
  border: 1px solid #333;
  text-align: center;
  /* ensures that the sizing of the element includes
     the padding-, and border-, width: */
  box-sizing: border-box;
}

    Text

    Text

    Text

    Text Long

    Text Longer

    Text Really Long

    1

    Text

    Text

    Text

    Text

References:

*

*CSS:

*

*calc()compatibility.

*JavaScript:

*

*Array.prototype.forEach().

*document.querySelectorAll().

*Function.prototype.call().

*HTMLElement.style.


text:
Q: Grails: 404 and lazy initialization If you visit a page that does not exist, and a 404 is "thrown" and Grails goes to try to render my custom 404 error page, I get lazy initialization errors from some taglibs I have that are executed in the error layout.
The taglib does in fact try to access a domain object inside of another domain object that is a has-many relationship.  It is able to get the initial object, but when accessing the relationship, it throws this lazy initialization error.
However, this does not happen when any other page is accessed properly. Even if I try to access my custom error page directly.  Only when a 404 error is thrown.
Is there something different about the hibernate session during this time that causes the lazy initialization error?
Is it possible that accessing something that is lazily initialized in a taglib is not a good idea in Grails?

A: I've seen this before, and my usual solution would be to move the querying to the controller.  I believe this is due to the fact that the controller and GSP sessions are not one and the same - hence, it's a good idea to do most database reads within a controller.
In this case, there is no controller.
As far as hacks to get around this problem ...
I a wondering if you can't start a session/end a session within your GSP and/or taglib to force the behavior for now.  Another idea is to force a read of the relationship at the same time you access the original (parent) object - this will initialize the lazy relationship.


text:
Q: Bootstrap/Datatables CSS shows in chrome but not firefox having a problem getting CSS to show in firefox. I have a bootstrap site with datatables and all is fine and dandy in chrome but a lot of the CSS is missing in firefox, and the datatables don't show at all. In the developer console for firefox I get a lot of "declaration dropped' which I'm assuming is affecting my output. Is three a setting I'm missing on my page that allows firefox to interpret things correctly?
Error in parsing value for '-webkit-text-size-adjust'.  Declaration dropped.  bootstrap.min.css:5:132
Unknown pseudo-class or pseudo-element '-webkit-inner-spin-button'.  Ruleset ignored due to bad selector.  bootstrap.min.css:5:1544
Unknown pseudo-class or pseudo-element '-webkit-search-cancel-button'.  Ruleset ignored due to bad selector.  bootstrap.min.css:5:1778
Unknown property 'orphans'.  Declaration dropped.  bootstrap.min.css:5:2691
Unknown property 'widows'.  Declaration dropped.  bootstrap.min.css:5:2700
Unknown property '-moz-osx-font-smoothing'.  Declaration dropped.  bootstrap.min.css:5:3676
Expected color but found 'auto'.  Expected color but found '-webkit-focus-ring-color'.  Expected end of value but found '-webkit-focus-ring-color'.  Error in parsing value for 'outline'.  Declaration dropped.  bootstrap.min.css:5:15709
Error in parsing value for 'margin-top'.  Declaration dropped.  bootstrap.min.css:5:35740
Expected color but found 'auto'.  Expected color but found '-webkit-focus-ring-color'.  Expected end of value but found '-webkit-focus-ring-color'.  Error in parsing value for 'outline'.  Declaration dropped.  bootstrap.min.css:5:35987
Unknown pseudo-class or pseudo-element '-ms-input-placeholder'.  Ruleset ignored due to bad selector.  bootstrap.min.css:5:36918
Unknown pseudo-class or pseudo-element '-webkit-input-placeholder'.  Ruleset ignored due to bad selector.  bootstrap.min.css:5:36966
Unknown pseudo-class or pseudo-element '-ms-expand'.  Ruleset ignored due to bad selector.  bootstrap.min.css:5:37018
Expected media feature name but found '-webkit-min-device-pixel-ratio'.  bootstrap.min.css:5:37352
Error in parsing value for 'margin-top'.  Declaration dropped.  bootstrap.min.css:5:38465
Unknown property 'user-select'.  Declaration dropped.  bootstrap.min.css:5:45511
Expected color but found 'auto'.  Expected color but found '-webkit-focus-ring-color'.  Expected end of value but found '-webkit-focus-ring-color'.  Error in parsing value for 'outline'.  Declaration dropped.  bootstrap.min.css:5:45712
Expected 'none', URL, or filter function but found 'alpha('.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:46058
Expected color but found 'solid\9 '.  Expected end of value but found 'solid\9 '.  Error in parsing value for 'border-top'.  Declaration dropped.  bootstrap.min.css:5:54984
Expected 'none', URL, or filter function but found 'progid'.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:56351
Expected color but found 'solid\9 '.  Expected end of value but found 'solid\9 '.  Error in parsing value for 'border-bottom'.  Declaration dropped.  bootstrap.min.css:5:56896
Error in parsing value for 'background-image'.  Declaration dropped.  bootstrap.min.css:5:85273
Error in parsing value for 'background-image'.  Declaration dropped.  bootstrap.min.css:5:86178
Error in parsing value for 'background-image'.  Declaration dropped.  bootstrap.min.css:5:86804
Error in parsing value for 'background-image'.  Declaration dropped.  bootstrap.min.css:5:87436
Error in parsing value for 'background-image'.  Declaration dropped.  bootstrap.min.css:5:88066
Unknown property 'zoom'.  Declaration dropped.  bootstrap.min.css:5:88502
Expected 'none', URL, or filter function but found 'alpha('.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:105745
Expected 'none', URL, or filter function but found 'alpha('.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:105854
Expected 'none', URL, or filter function but found 'alpha('.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:107063
Expected 'none', URL, or filter function but found 'alpha('.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:107116
Expected 'none', URL, or filter function but found 'alpha('.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:108266
Unknown property 'line-break'.  Declaration dropped.  bootstrap.min.css:5:108303
Expected 'none', URL, or filter function but found 'alpha('.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:108328
Unknown property 'line-break'.  Declaration dropped.  bootstrap.min.css:5:110310
Expected media feature name but found 'transform-3d'.  bootstrap.min.css:5:112148
Expected 'none', URL, or filter function but found 'alpha('.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:113485
Error in parsing value for 'background-image'.  Declaration dropped.  bootstrap.min.css:5:113641
Expected 'none', URL, or filter function but found 'progid'.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:113900
Error in parsing value for 'background-image'.  Declaration dropped.  bootstrap.min.css:5:114184
Expected 'none', URL, or filter function but found 'progid'.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:114443
Expected 'none', URL, or filter function but found 'alpha('.  Error in parsing value for 'filter'.  Declaration dropped.  bootstrap.min.css:5:114668
Expected color but found '#\30 00\9 '.  Error in parsing value for 'background-color'.  Declaration dropped.  bootstrap.min.css:5:115617
Expected 'none', URL, or filter function but found 'progid'.  Error in parsing value for 'filter'.  Declaration dropped.  metisMenu.min.css:10:299
Error in parsing value for 'width'.  Declaration dropped.  timeline.css:153:15
Error in parsing value for 'width'.  Declaration dropped.  timeline.css:154:15
Unknown property 'user-select'.  Declaration dropped.  bootstrap-datepicker3.css:83:13
Unknown property '-moz-osx-font-smoothing'.  Declaration dropped.  font-awesome.min.css:4:594
Expected 'none', URL, or filter function but found 'progid'.  Error in parsing value for 'filter'.  Declaration dropped.  font-awesome.min.css:4:1615
Expected 'none', URL, or filter function but found 'progid'.  Error in parsing value for 'filter'.  Declaration dropped.  font-awesome.min.css:4:1778
Expected 'none', URL, or filter function but found 'progid'.  Error in parsing value for 'filter'.  Declaration dropped.  font-awesome.min.css:4:1944
Expected 'none', URL, or filter function but found 'progid'.  Error in parsing value for 'filter'.  Declaration dropped.  font-awesome.min.css:4:2115
Expected 'none', URL, or filter function but found 'progid'.  Error in parsing value for 'filter'.  Declaration dropped.

edit: since it was asked for here is my header, it's just a standard bootstrap implementation.
<head>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

<title>IMS</title>

<!-- Bootstrap Core CSS -->
<link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

<!-- MetisMenu CSS -->
<link href="../bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">

<!-- Timeline CSS -->
<link href="../dist/css/timeline.css" rel="stylesheet">

<!-- Touchspin CSS -->
<link href="../dist/css/jquery.bootstrap-touchspin.css" rel="stylesheet">

<!-- DataTables CSS -->
<link href="../bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" type="text/css">

<!-- DataTables Responsive CSS -->
<link href="../bower_components/datatables-responsive/css/responsive.dataTables.scss" rel="stylesheet" type="text/css">

<!-- Datepicker3 CSS -->
<link href="../dist/css/bootstrap-datepicker3.css" rel="stylesheet">

<!-- Morris Charts CSS -->
<link href="../bower_components/morrisjs/morris.css" rel="stylesheet">

<!-- TypeAhead CSS -->
<link href="../dist/css/typeaheadjs.css" rel="stylesheet">

<!-- Custom Fonts -->
<link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

<!-- Custom CSS -->
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->

<!-- jQuery -->
<!-- <script src="../bower_components/jquery/dist/jquery.js"></script> -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>

<!-- Metis Menu Plugin JavaScript -->
<script src="../bower_components/metisMenu/dist/metisMenu.min.js"></script>

<!-- Morris Charts JavaScript -->
<script src="../bower_components/raphael/raphael-min.js"></script>
<script src="../bower_components/morrisjs/morris.min.js"></script>
<script src="../dist/js/morris-data.js"></script>

<!-- Touchspin JavaScript -->
<script src="../dist/js/jquery.bootstrap-touchspin.js"></script>

<!-- DatePicker3 JavaScript -->
<script src="../dist/js/bootstrap-datepicker.js"></script>

<!-- Typeahead JavaScript -->
<script src="../dist/js/typeahead.js"></script>

<!-- Bloodhound JavaScript -->
<script src="../dist/js/bloodhound.js"></script>

<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
<script src="../dist/js/ioma.js"></script>

edit: added chromegodo and fireboxbad. and on second look it looks like my one monitor is so old it isn't showing greys at all, I just saw that bootstrap shows up just fine but its now just the datatables not working.

A: You might want to try putting some moz as an alternative to webkit in the CSS to give the browser a different read option
https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-appearance


text:
Q: How to split a CLI command in Azure Devops over multiple lines? (Running on Windows) I am running the following in a CLI task on Azure Devops (inline)
rem Create the Service Plan
call az appservice plan create --resource-group %RESOURCE_GROUP% --name %SERVICE_NAME% --sku B1

Whch works just fine. However, I'm having to scroll to see the whole thing and I have other commands which are even longer. So I'm trying to split it over multiple lines so I can see more clearly what is going on.
Looking at Microsoft Docs it looked like the solution was to put a backslash on the end of each line. So I tried:
I've tried:
rem Create the Service Plan
call az appservice plan create \
--resource-group %RESOURCE_GROUP% \
--name %APP_SERVICE_NAME% \
--sku B1

Which didn't work. I then read something that recommended the back-tick/back-quote at the end of each line:
rem Create the Service Plan
call az appservice plan create `
--resource-group %RESOURCE_GROUP% `
--name %APP_SERVICE_NAME% `
--sku B1

This also didn't work. Any help greatly appreciated.

A: Never mind. Worked it out. Turns out you need to use '^'
rem Create the Service Plan
call az appservice plan create ^
--resource-group %RESOURCE_GROUP% ^
--name %APP_SERVICE_NAME% ^
--sku B1

A: For me the ` character is working.   I posted earlier that it wasn't but I was inadvertently using the wrong character.
(That post seems to have been deleted by a moderator though I'm not sure why - perhaps because it was more of a "me too" than an answer, but it did add that the above "^" solution doesn't work for me).
In case it was the same issue as I had, ensure the "Backtick" you use is the correct one (it's immediately to the left of "1" on my microsoft keyboard).  I was trying to use a ' in the failed attempt as the CLI docs were reading made it hard to distinguish.

A: The character that you need to use to specify that the command is split over multiple lines, depends on the environment in where the CLI command is run.
In other words, it depends on the scriptType property of the AzureCLI@2 command.

*

*Powershell/Powershell Core:  use a backtick `

*bash: use backslash \

*batch: use accent circonflexe ^

A: from azure cloud shell, type AZ, then copy paste the az command with \ for multiple line will not work.
but there is a fix, you click on the + sign like a adding a folder sign, it will bring a full page Azure Cloud Shell window, change to Bash from the pull down (default is Poweshell), then you see prompt changed to name@Azure:~$, now you can use az commend with \ for multiple lines.


text:
Q: Including header, menu, and footer in controllers I'm creating my own primitive MVC (or MVP as some may call it) framework, and I would like to know a best practice way of including a header, footer and anything else in my controllers.
Currently I'm doing it like the following at the end of every controller:
class Index extends Controller
{
    public function index()
    {
        $hData = array(
            'title'       => 'Home',
            'stylesheets' => array(
                'style1.css',
                'style2.css'
            ),
            'javascripts' => array(
                'script1.js',
                'script2.js'
            )
        );

        $cData = array(
            'heading' => 'My first PHP application',
            'message' => 'Hello, world!'
        );

        //HTML Output
        $header  = new View('/views/header.php');
        $html    = $header->fetch($hData);

        $menu    = new View('/views/menu.php');
        $html   .= $header->fetch();

        $content = new View('/views/index.php');
        $html   .= $content->fetch($cData);

        $footer  = new View('/views/footer.php');
        $html   .= $footer->fetch();

        echo $html;
    }
}

Am I doing it correctly or is there a better way of doing it? If so, I would highly appreciate an example.

A: In general, building MVC framework on your own, will force you to accept some compromises. But here is what I think:

*

*You should have some templating engine (ideally, potentially replaceable). It can be either just PHP, or some already existing (Twig, Smarty)

*Controllers should only know about particular view that would be rendered by the templating engine. As such, views should probably be available by names rather than by concrete paths to the template files.

*Templating engine should know how to resolve the template name to the real template files.

*Templating engine should be able to accept variables for the template, that can be passed to it from the controller.

*Including header, footer, etc., should be considered either by your templating engine or within your templates, but not within your controller. For example, your code may support AJAX-calls showing some partial inner-html. In this case, the name for the template can be the same, but according to some var, passed from the controller, the templating engine (or the template itself) can show header and footer for normal requests and omit them for ajax requests.

*And definitely, it's not controller's task to define in a hard-coded way, which css files to load in the template. However, there may be some system setting that could be read within the controller and then passed to the template as a variable.
2 and 3 can be optional, if you don't need extra flexibility or you are pretty sure that you won't need to switch to Smarty or Twig later.

A: MVC is designed specifically to separate functions.
Model - Think of this as your application layer. When you are designing your model it is the application itself. What content will you need? This typically is returned in raw form. Arrays, objects, JSon, etc.
View - The view is how you serve data. PHP makes a great templating engine, but there are others, like Smarty or Twig, that are based on PHP and are designed exclusively for templates. Look them up, see what you think. I personally use Smarty and am looking at Symfony (an MVC framework that uses Twig for views) for a potential future project. But many say PHP alone works just fine. There are definitely pros and cons to each.
Controller - Controllers tell the program what to do and where to go. This is your business logic layer. Your Front Controller sits in between your Model and your View in order to put the right content into the right places.
Therefore, when thinking about headers and footers, consider where they belong. In the end because it is a question of templating and images it is probably best suited in a View.
Edit: An Example of a View
If you choose to use PHP as your template, you can go from very basic (hard to scale) all the way up to a highly dynamic object oriented template engine from scratch. Depending on the scope of your project, I will once again highly recommend that you at least look at Smarty or Twig as an option.
Simple Template: User Profile
Templates can be as simple as this:
<?php include("header.html.php");
 /*I am using .html because you can also create .xml views.
      The beauty of MVC is you can create multiple views with
      the same model, just having your controller direct
      to the correct view. */ ?>

<img src="<?php echo $userPictureLocation; ?>">

            Name:
            <?php echo $userNameValue; ?>

            Bio:
            <?php echo $userBioValue; ?>

<?php include ("footer.html.php"); ?>

Using this very simple and hard-to-maintain template system, you can simply use include $file; in your Front Controller.
If you want to create an object oriented view and not use a templating engine like Smarty or Twig, then you'll be looking to create your own object classes. You can probably take a look at the functionality of Smarty and/or Twig to get an idea of what would be required. It is reinventing the wheel, but reinventing the wheel is a great learning tool. A very simple initial thing you could do, however, is add a Template class that had the functions setValue(), getValue(), and load(). load() and setValue() could be used in your template, and getValue() can be used in your template.
class template {
    private $values;

    public function __construct() {
        $this->values = array();
    }

    public function setValue($key, $value) {
        $this->values[$key] = $value;
    }

    public function getValue($key) {
        return $this->values[$key];
    }

    public function load($file) {
        //The APPLOCATION constant below would be under a configuration
        //file define('APPLOCATION','/var/www/html/'); or whatever your app location
        //is. A Registry Class is probably a better bet for a large application and is
        //the best practices way to do it.
        include APPLOCATION . "template/{$file}";
    }
}

This class is very lightweight but also can be added to. It prevents some of the more egregious replication and can be extended with limited effort.
So once again, the template we looked at before, this time with the Template object.
<?php
//In this example I am assuming you declared a new Template
//in your Controller and assigned it the value of $template.
$template->load("header.html.php");
?>

<img src="<?php echo $template->getValue('userPictureLocation'); ?>">

            Name:
            <?php echo $template->value('userNameValue'); ?>

            Bio:
            <?php echo $template->value('userBioValue'); ?>

<?php $template->load("footer.html.php"); ?>

A: Have you considered creating a printView method that takes your two params and wraps this away? If you really wanted to there's no reason you need to specify the scripts if they're not going to change. Something like:
class Controller {

    // Protected makes it visible to children, but not to callers
    protected function printHTML($bodyPage, $bodyData = array(), $altHeaders = array()){
        $defaultHeaders = array(
            'title'       => 'Home',
            'stylesheets' => array(
                'style1.css',
                'style2.css'
            ),
            'javascripts' => array(
                'script1.js',
                'script2.js'
            )
        );
        $trueHeaders = array_merge_recursive($defaultHeaders, $altHeaders);

        $header  = new View('/views/header.php');
        $html    = $header->fetch($trueHeaders);

        $menu    = new View('/views/menu.php');
        $html   .= $header->fetch();

        $content = new View($bodyPage);
        $html   .= $content->fetch($bodyData);

        $footer  = new View('/views/footer.php');
        $html   .= $footer->fetch();

        echo $html;
   }
}

class Index extends Controller {
    public function index() {
        $this->printHTML(
            '/views/index.php',
            array(
                'heading' => 'My first PHP application',
                'message' => 'Hello, world!'
            ),
            array(
                'title' => 'My Index Page',
                'stylesheets' => array(
                    'style3.css'// Will use styles 1, 2 and 3 because we merge the array recursively.
                )
            )
        );
    }
}

A: Create a folder called layout and place a file named Header and a file named footer and put all tags until your content div and then require the view file from the View.php after the header.php then put your footer.php and require after the file and close all the tags. That's how I do it.


text:
Q: Is Cross Validation useless unless the Hypotheses are nested? If I generate many random models (without considering the data at all) in a regression setting simply by randomly assigning coefficient values and then evaluating these models over the dataset with an error metric and choosing the best model based on this error metric would I still run into overfitting?
Eventually we will end up with the OLS solution (see comments). If this is the case how is Cross Validation different than this procedure? For example in a Ridge or Lasso regression setting I am still generating a bunch of models (indexed by $\lambda$) and evaluating them on unseen data segment and choosing the best one.
It seems to me that CV works well with standard regularization methods like Ridge and Lasso is because the tried models are somewhat nested (i.e. Ridge is ordered by Rademacher complexity). Hence the Structural Risk Minimization principle kicks in. Otherwise CV looks like a dead end effort. If we use cross validation to compare bunch of unrelated models we will end up with the random model generation scenario that I described above.
Under the Structural Risk Minimization framework, for example in SVM, one bounds the error and reduces the model complexity. So how does CV actually achieve the same effect when applied in conjunction with regularization methods? What to do when compared models are not nested?

A:
My logic tells me the answer is yes.

And, as @amoeba pointed out: your logic is right.

how is Cross Validation different than this procedure?
  CV in itself has nothing to do with your overfitting. CV is just a scheme how to retain independent cases to test some model.

Note that if you select a model based on the CV results, this model selection procedure (including the CV) is actually part of your training.
You need to do an independent validation (rather, verification) of that final model (for which you can again use another CV as a strategy to retain cases independent of the training - see nested cross validation) in order to obtain a reliable estimate of its generalization performance.
To reiterate: the problem is not the CV, the problem is the data-driven model optimization (selection).

From this perspective random model generation should in theory overfit less than a penalized regression as my evaluation is on a bigger unseen data segment.

This I don't understand: why would the unseen data size differ?

Is there something in CV procedure that somehow mitigates the multiple testing problem?

No.
The only property of CV that slightly helps with multiple testing compared to a single split is that CV eventually tests all available cases, and is thus subject to somewhat smaller variance uncertainty due to the limited number of tested cases. This won't help much compared to limiting the search space (i.e. restricting the number of comparisons), though.

A: EDIT:
Tuning or selecting a model based on cross-validation is essentially trying to minimize the prediction error (e.g., mean-squared prediction error). You select a model conditional on some subset of input data and predict the output at the left out locations. Intuitively, it is a prediction because you are evaluating the model at out of sample locations. Your question is what happens if your set of candidate models are independent of the input data (i.e., you don't use any data when randomly generating models).
This assumption is not that different than any other model fitting procedure. For example, if I start with a parameterized model, and the parameters could be any real number, then I also have an infinite set of candidate models. We both still need to select the best model from the set of possible models by minimizing some error metric. Therefore, both of our model choices are conditional on some training data (perhaps a subset of all the training data if using cross-validation). You don't specify an error metric so lets assume it is mean-squared error (MSE). I pick model parameters and thereby my model using some black box procedure assuming MSE metric conditional on training data. You pick your model from your set of random models assuming MSE metric conditional on training data.
Do we choose the same model? It depends on if you started with different sets of candidate models.
Do we overfit the data? It depends on the set of candidate models we started with and the training data.
Do we know we overfit the data? If we do cross-validation then we can check the prediction error.
ORIGINAL RESPONSE:
In a broad sense, there is some signal in the data and some noise. When we overfit we are essentially fitting the noise.
In cross-validation, we leave out portions of the data when fitting and assess the error when predicting the left out points. It is similar to having training and test data in that we are measuring an out of sample error. The model must generalize well regardless of what points are omitted. If we fit the noise the model will not generalize well. The set of models we are comparing likely does not include those that try to interpolate a data point when it is omitted from the training data. If the model behaves this way (e.g., random behavior to improve fit) then it is likely we do not have a reasonable general model fitting procedure and cross-validation can't help us.
If you have an infinite set of models and an infinite amount of time then I guess in theory you could generate a model that was as good or better than any model that was generate through any other procedure. How will you know which model from your infinite set it is though? If it is the model that interpolates the training data, then yes it will overfit when the training data is noisy.


text:
Q: Triggering data acquisition in Arduino with Python I would like to trigger data acquisition on my Arduino UNO with connected accelerometer (MPU 6050) by using Python.
The idea is that when the command is given in Python, the Arduino would start saving data on its SRAM and when a certain number of measurements would be saved, the data would be sent in a package back to Python.
This is my current Arduino code:
#include<Wire.h>
#define MPU6050_DLPF_94HZ     MPU6050_DLPF_CFG_2

const int MPU_addr_1 = 0x68; // I2C address of the first MPU-6050
const int baudrate = 19200;
int16_t AcX1; // definition of variables

const int len = 200; // Buffer size
float analogDataArray[len];
int count = 0;

void setup() {
  Wire.begin();
  Wire.beginTransmission(MPU_addr_1);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(baudrate);
}

void loop() {
  Wire.beginTransmission(MPU_addr_1);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr_1, 8, true); // request a total of 14 registers
  float AcX1 = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)

  if (Serial.available())
  {
    if (Serial.read() == 'Y') {
      analogDataArray[count] = AcX1;
      count = count + 1;
      if (count >= len) {
        for (int i; i <= len; i = i + 1) {
          Serial.println(analogDataArray[i] / 16384);
        }
      }
      count = 0;

    }
  }
  delay(5);
}

and this is my Python code:
import serial
arduinoData = serial.Serial('COM3', 19200)
com = input('Press "Y":' )
arduinoData.write(bytes(com, 'utf-8'))

vec = []

run = True
while run is True:
    while (arduinoData.inWaiting() == 0):
        pass
    arduinoString = arduinoData.readline()
    vec.append(float(arduinoString))
    if len(vec) >= 100:
        run = False
print(vec)

I've managed to get it working for 1 measurement but as soon as I defined an array inside Arduino to save multiple measurements, the code doesn't work. I'm sure that it is close to working, but I can't find the detail that is stopping me from that.
Thank you for any provided help.
Kind regards,
L

A: I got it working, the problem was in my Arduino code, as expected.
#include<Wire.h>
#define MPU6050_DLPF_94HZ     MPU6050_DLPF_CFG_2

const int MPU_addr_1 = 0x68; // I2C address of the first MPU-6050
const int baudrate = 9600;
int16_t AcX1; // definition of variables

const int len = 200; // Buffer size
float analogDataArray[len];
int count = 0;

int ans;

void setup() {
  Wire.begin();
  Wire.beginTransmission(MPU_addr_1);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(baudrate);
}

void loop() {
  Wire.beginTransmission(MPU_addr_1);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr_1, 8, true); // request a total of 14 registers
  float AcX1 = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)

  if (Serial.available() && Serial.read() == 'Y') {
    ans = 1;
  }
  if (ans == 1) {
    analogDataArray[count] = AcX1;
    count = count + 1;
    if (count >= len) {
      for (int i; i <= len; i = i + 1) {
        Serial.println(analogDataArray[i] / 16384);
      }
      ans = 0;
    }
  }
  delay(5);
}


text:
Q: The number of solutions to $x^2-xy+y^2=n$ is finite and a multiple of 6. Let be $n$ a positive integer. Show that the number of integers solutions $(x,y)$ of the following equation $$x^2-xy+y^2=n$$ Is finite and multiple of 6.
My approach: If $(x,y)$ is a integer solution of  $x^2-xy+y^2=n$ ,then also is $\{(-x,-y),(y-x,-x),(-y,x-y),(x-y,x),(y,y-x)\}$; But this solutions was find only by the simetry of equation. So, I can't ensure these solutions are all integers solutions for the problem. Can give me some hint. Thanks!

A: Any solution $(x,y)$ can be transformed into a different solution $(x-y, x)$. Applying this transform repeatedly gives:
$$\begin{align}
 (x &,y) \\
(x-y &, x)\\
(-y &, x-y) \\
(-x &, -y) \\
(y-x &, -x) \\
(y &, y-x)\\
\end{align}$$
and back to the original - thus the divisibility by $6$.
Clearly the solutions are finite; for example $(x-y)^2 = x^2-2xy+y^2\ge 0$ and thus as $x^2-xy+y^2 > xy$ and since the same-sign case is smaller than the mixed-sign case, we need $|xy|\le n$

A: Let's multiply the equation by $2$ to get
$$
2x^2-2xy+2y^2=x^2+y^2+(x-y)^2=2n.
$$
Clearly $x^2$ and $y^2$ are bounded by $2n$, thus the number of solutions is finite.
Consider the triple $(x,y,z=x-y)$. If all three numbers are different then we can get 6 different solutions by doing all permutations of those and possibly adjusting one sign to negative to satisfy the relation "the last is the first minus the second". Besides those we can get another 6 solutions by changing all the signes. It gives 12 solutions in this group. A special case is when not all three are different, but in this case the number of unique solutions reduces by factor two, and we get a group of only 6 solutions.

A: I prefer, as suggested by @Daniel Fisher, to do arithmeic in the so called ring of Eisenstein integers $\mathbf Z[j]$, where $j$ is a primitive cubic root of $1$. It is known that this ring is a UFD. Recall that division in a domain is defined up to units (= invertible elements), which are here the obvious $6$-th roots of $1$ in $\mathbf Q[j]$.
Now let $N$ be the norm map of the extension $\mathbf Q[j] / \mathbf Q$. Your diophantine equation can be written ($E_n)$ $N(x+jy) =n$ (necessarily positive). Because the norm is multiplicative, and  $\mathbf Z$ and $\mathbf Z[j]$ are UFD's, it is obviously sufficient to solve only equations of the type ($E_p$) $N(x+jy) =p$, where $p$ is a prime factor of $n$ . Note that the existence of a solution of ($E_p$) means that the prime $p$ splits as a product of 2 non associated irreducible elements in $\mathbf Z[j]$, and this is known to happen iff $p\equiv 1$ mod $3$. Anyway, the number of solutions $(x,y)$ of ($E_n)$ is readily $\equiv 0$ mod $6$ because of the $6$-th roots of $1$ in $\mathbf Q[j]$.


text:
Q: Why `python3 -m project` generates error while `python3 __main__.py` works? Why do I get ModuleNotFoundError with command python3 -m project while calling python3 __main__.py inside project directory works perfectly fine? Here is screenshot from my terminal:
About files organization: there is only one directory named "memorizeIT" with all .py files. Import which I use is just: import gui. I have tried to add __init__.py file with content:
import subprocess
import sys

path = subprocess.call('pwd', shell=True)
sys.path.append(path)

It doesn't changes anything. Still cant' run python3 -m memorizeIT. What is issue and how can i resolve it?

A: I have found solution to use python3 -m project_name. In case above it was problem with imports. All I needed to add was from project_name.module import class. In my code it would be from memorizeIT.gui import Gui for example. Now running python3 __main.__py doesn't work, but that's not something necessary. From beginning I wanted to run code as package and now it is possible. Here is link to documentation which helped.


text:
Q: Sending XmlData in soap request using spring Integration ws I have requirement to send XmlData in CDATA to soap request,format of xml is,
<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header/>
    <soapenv:Body>
        <java:Request>
            <string>
                <?xml version="1.0" encoding="UTF-8" standalone="yes"?  <UserName>CJI</UserName>           <PhoneNumber>1234987456</PhoneNumber>
            </string>
        </java:Request>
    </soapenv:Body>
</soapenv:Envelope>

Am using Spring Integration ws outbound-gateway to call service, and I am getting below exception,
org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize.
But this xml is tested in SOAPUI it's working.
Updated,
NOTE: the service am calling implemented using Axis1.2.
Am having some custom header tags.like  .
my exact xml will bind to tag ....
org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize.
    at org.apache.axis.encoding.ser.SimpleDeserializer.onStartChild(SimpleDeserializer.java:145)
    at org.apache.axis.encoding.DeserializationContext.startElement(DeserializationContext.java:1035)
    at org.apache.axis.message.SAX2EventRecorder.replay(SAX2EventRecorder.java:165)
    at org.apache.axis.message.MessageElement.publishToHandler(MessageElement.java:1141)
    at org.apache.axis.message.RPCElement.deserialize(RPCElement.java:345)
    at org.apache.axis.message.RPCElement.getParams(RPCElement.java:384)
    at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:148)
    at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:323)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:453)
    at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281)
    at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
    at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:346)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:243)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3432)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3402)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
    at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
    at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2285)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2201)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1572)
    at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)

2017-08-17 12:34:24,524 INFO  Found SoapFaultDetailElement {http://xml.apache.org/axis/}hostname


text:
Q: How to keep only words with specific text between in Regex? i want to keep only words contain specific text between in my document and give separator for each word. For Example:
Before:
4Sampledocument test suct.doc hxtp://domain.com/AB/sample.doc ON tuesday 2 A.M
2Sampledocus test sub.doc hxtp://domain.com/EA/samples.doc ON monday 1 A.M
4Sampledocssss test suect.doc hxtp://domain.com/LW/simple.doc ON wednesday 5 P.M
2Ssjxiw92 test ssct.doc hxtp://domain.com/LC/bro.doc ON friday 8 A.M

After:
hxtp://domain.com/AB/sample.doc|hxtp://domain.com/EA/samples.doc|hxtp://domain.com/LW/simple.doc|hxtp://domain.com/LC/bro.doc

| = separator
Thanks

A: Considering you have a line break in the last line, the best bet using a regex replace is as follows. But there will be trailing pipe symbol which you need to remove.
Assuming you are using PHP
preg_replace('/.*?(hxtp:.+?)\s+.*\s+/im', '$1|', $full_string);

OR
You can loop through each line and parse the hxtp urls only and then implode using |
preg_match('/.*?(hxtp:.+?)\s+.*/', $line_string, $matches);
var_dump($matches);

A: I think the easiest way to achieve the result is to find all urls and implode them into one string, although it needs a little bit of extra PHP-Code
Also assuming you are using PHP:
$strings = …; // Your text before

// Match each url
preg_match_all('/.*(\S{4,}\:\/\/.+\.doc)\S*/', $strings, $matches);
echo implode("|", $matches[1]);  // Concat


text:
Q: How to cancel all the unsaved data in the context? when using EF6 Hello I have a UI like this

so What I want to do is: If I press the x button and close the form I want to undo all the changes on this record.
If you take a closer to the UI you can see that there is a another form for the browsing purpose. Both forms use the same context.
so what happens is this. when I close and reopen the same record I get the above UI
below Is how I fill the BindingSource dynamically.
Base4Data = ((dynamic)(IQueryable)Context.GetPropValue(TableName)).Find(MyPkValue);

things I tried on FormClosing event:
1- Setting the current context to a new dbcontext instance on formclose
2- Create new transaction in form handlecreate and rollback transaction on formclose
3-  ((IObjectContextAdapter)Context).ObjectContext.Refresh(RefreshMode.StoreWins, Base4Data);
4- Context.Entry(Base4Data).Reload();
non of the above work, so any suggestions are very appreciated


text:
Q: Capture an image of a dynamic chart My requirements:

*

*draw dynamic charts (pie, bars, etc.) from data provided by the user

*display a save button that allows the user to save the result as an image

*support IE 8

With modern browsers, I can use canvas for the charts, then the convenient toDataURL method to save the resulting chart as image. But what is the fallback for browsers like IE 8 that don't support canvas?


text:
Q: Protractor Test with oracle Db I requirement to test the DB alongside my angular app. The scenario is such that I do something on UI and see if the value persists in the DB(Oracle)
For this purpose, I installed node oracle DB package and was able to run a simple SELECT statement using the command "Node filename.js". The config and the select statement were present in the filename.js
Next, I tried to include the same steps in my step definition. The first step of my test case navigates to the application home page and the next step is to run a simple select statement. I have no asserts as I wanted to first get a basic query working
Here is my step def
let oracledb = require('oracledb');
let dbConfig = require('../configs/dbConfig');

Given(/^I run a random select query$/, function() {

    let sql2 = "Select * from tablename Where columname  = 8888901";
    oracledb.getConnection(dbConfig).then(function(connection) {
        //return console.log('Connected to database');
        return connection.execute(sql2).then(function(result, err) {
            return console.log(result.rows.toString());
        });
    });

});

When the test runs the browser opens and the home page is loaded and then the test is passed. I don't think the 2nd step is even run as the query result is not printed in the console.
Could someone please point me in the right direction. Can protractor work with OracleDB? have I written the test correct? I have so many questions regarding this and there is not a single online sample for a protractor test with oracledb. Any inputs here will be helpful, thanks


text:
Q: SSRS Page Break on a grouping In SSRS within a matrix you can page break by a group easily.
What if you have multiple tables and matrix on the same report, but wanted each to page break by the same group?
So you select multiple retailers, and you want to display each table for that retailer and then page break to show the next retailer in the same matrix.
So the three tables below need to page break after every retailer, is this possible?

A: If your three tables have the same dataset, simply add them into a parent table, which has a retailer group handling the page break.
If your tables have different datasets I'm sorry that I don't have a solution for you.


text:
Q: scrapy: Can I extract request formdata from response? I am using scrapy to scrape some data, I am wondering how much data of Request the Response stores.
My specific question is shown in the following code:
def parse(self,response):
    r = FormRequest(url=url1, formdata={somedata}, callback=parse2)

    #is this line necessary if I want the formdata being attached?
    r.meta['formdata'] = formdata

    yield r

def parse2(self,response):
    #can I access to the formdata here without that line of code?

Any suggestion would be appreciated.

A: Yes, however formdata is already converted into body and won't be the dictionary but a string as far as I remember.
so try r.body also quick reminder you can check the attributes of an object by:
dir(r)


text:
Q: how to disable horizontal scroll-view? I'm using original Gallery app from the ICS source code. And Now the thing is, I want to disable the horizontal scroll and implement it by vertical scroll in Grid. How to do this ?

A: try this
Add android:screenOrientation="portrait" to the activity in the AndroidManifest.xml. For example:
    <activity android:name=".SomeActivity"
          android:label="@string/app_name"
          android:screenOrientation="portrait">

Or try like this...
One programmatic way of doing this, that I can think of, is to create a super class that extends activity and extend all your classes from there.
Have the below setting in the super class in a protected method and call super.xxx() to initiate this:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

In case you what a specific activity in a different way you can simply override this.
[I have not tried this yet, but by the knowledge of OOP this works]

A: try this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<ScrollView android:id="@+id/ScrlView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<Gallery android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom"/>

</ScrollView>
</LinearLayout>


text:
Q: How to get upload progress percentage in retrofit mulitpart request? Following is the multipart request that i am performing using retrofit2.
What i want is to somehow get a callback of the upload percentage. But i cannot a find a suitable method for doing this. I have saw few methods but they are only playing with single file. What i want is to achieve is get a upload progress percentage of combine all files sent in the request.

    @Multipart
    @POST("post/vehicle/detail")
    Call<SuccessModel> uploadVehicle(

            @Part("user_id") int userId,
            @Part("name") String vehicleName,
            @Part("number") int stockNumber,
            @Part MultipartBody.Part mainImage,
            @Part MultipartBody.Part hoodsImage,
            @Part MultipartBody.Part bumperImage,
            @Part MultipartBody.Part interiorImage,
            @Part MultipartBody.Part frontSeatImage,
            @Part MultipartBody.Part backSeatImage,
            @Part MultipartBody.Part dashboardImage,
            @Part MultipartBody.Part headLampsImage,
            @Part MultipartBody.Part tailLightsImage,
            @Part MultipartBody.Part backEngineImage
    );

Edit
Some more code about How i am creating Request.

File mainImage = new File(vehicleEntity.mainImage);

            RequestBody requestMainFile = RequestBody.create(MediaType.parse("multipart/form-data"), mainImage);

            MultipartBody.Part main = MultipartBody.Part.createFormData("main_image", mainImage.getName(), requestMainFile);

            File hoodImage, bumperImage, interiorImage, frontSeatImage, backSeatImage, dashboardImage, headLampsImage, tailLightImage, backEngineImage;

            MultipartBody.Part hood = null, bumper = null, interior = null, frontSeat = null, backSeat = null, dashboard = null, headLamps = null, tailLights = null, backEngine = null;

            if (vehicleEntity.hoodsImage != null) {

                hoodImage = new File(vehicleEntity.hoodsImage);
                RequestBody requestHoodFile = RequestBody.create(MediaType.parse("multipart/form-data"), hoodImage);
                hood = MultipartBody.Part.createFormData("hoods", hoodImage.getName(), requestHoodFile);

            }

            if (vehicleEntity.bumperImage != null) {

                bumperImage = new File(vehicleEntity.bumperImage);
                RequestBody requestBumperFile = RequestBody.create(MediaType.parse("multipart/form-data"), bumperImage);
                bumper = MultipartBody.Part.createFormData("bumpers", mainImage.getName(), requestBumperFile);

            }

            if (vehicleEntity.interiorImage != null) {

                interiorImage = new File(vehicleEntity.interiorImage);
                RequestBody requestInteriorFile = RequestBody.create(MediaType.parse("multipart/form-data"), interiorImage);
                interior = MultipartBody.Part.createFormData("interiors", mainImage.getName(), requestInteriorFile);

            }

            if (vehicleEntity.frontSeatImage != null) {

                frontSeatImage = new File(vehicleEntity.frontSeatImage);
                RequestBody requestFrontSeatFile = RequestBody.create(MediaType.parse("multipart/form-data"), frontSeatImage);
                frontSeat = MultipartBody.Part.createFormData("front_seat", mainImage.getName(), requestFrontSeatFile);

            }

            if (vehicleEntity.backSeatImage != null) {

                backSeatImage = new File(vehicleEntity.backSeatImage);
                RequestBody requestBackSeatFile = RequestBody.create(MediaType.parse("multipart/form-data"), backSeatImage);
                backSeat = MultipartBody.Part.createFormData("back_seat", mainImage.getName(), requestBackSeatFile);

            }

            if (vehicleEntity.dashboardImage != null) {

                dashboardImage = new File(vehicleEntity.dashboardImage);
                RequestBody requestDashboardFile = RequestBody.create(MediaType.parse("multipart/form-data"), dashboardImage);
                dashboard = MultipartBody.Part.createFormData("dashboard", mainImage.getName(), requestDashboardFile);

            }

            if (vehicleEntity.headLampsImage != null) {

                headLampsImage = new File(vehicleEntity.headLampsImage);
                RequestBody requestHeadLampsFile = RequestBody.create(MediaType.parse("multipart/form-data"), headLampsImage);
                headLamps = MultipartBody.Part.createFormData("headlamps", mainImage.getName(), requestHeadLampsFile);

            }

            if (vehicleEntity.tailLightsImage != null) {

                tailLightImage = new File(vehicleEntity.tailLightsImage);
                RequestBody requestTailsLightFile = RequestBody.create(MediaType.parse("multipart/form-data"), tailLightImage);
                tailLights = MultipartBody.Part.createFormData("tail_light", mainImage.getName(), requestTailsLightFile);

            }

            if (vehicleEntity.backEngineImage != null) {

                backEngineImage = new File(vehicleEntity.backEngineImage);
                RequestBody requestBackEngineFile = RequestBody.create(MediaType.parse("multipart/form-data"), backEngineImage);
                backEngine = MultipartBody.Part.createFormData("tail_light", mainImage.getName(), requestBackEngineFile);

            }

            int userId = Integer.parseInt(sharedPreferences.getString(USER_ID, null));

            String vehicleName = vehicleEntity.vehicleName;

            int stockNumber = Integer.parseInt(vehicleEntity.stockNumber);

            Call<SuccessModel> call = apiInterface.uploadVehicle(

                    userId, vehicleName, stockNumber, main,
                    hood, bumper, interior, frontSeat, backSeat,
                    dashboard, headLamps, tailLights, backEngine

            );


text:
Q: How to use the value of a global variable to determine the control flow of a function running in separate thread? In my first project with serial communication I am trying to implement a procedure where a function in a background thread listens on the serial port for a ready signal. When a ready signal is received it updates a global variable to a True value so that another function will start.
Below is a simplified version of the logic, but I cant get it to work. Instead of running concurrently the two threads it seems like it is still running consecutively
import threading
import time

global CONS
CONS = False
print(CONS)

def timeout(state,my_timeout):
    _time = 0
    while _time < my_timeout:
        if state:
            print(state)
                    print('Signal received, returning True to start another function')
            return bool(state)
        _time += 1
        time.sleep(1)
        print(_time)
    else:
        print('Timeout occured: Ready signal not received within %s seconds', _time)
        return False

def smallmeth():
    time.sleep(2)
    global CONS
    CONS = True
    print(CONS)
    return CONS

t1 = threading.Thread(target=timeout(CONS,5))
t2 = threading.Thread(target=smallmeth)
threading.enumerate()
# t1.setDaemon()
t1.start()
t2.start()

The output I get when running this is this:
False
1
2
3
4
5
Timeout occured: Ready signal not received within 5 seconds
True

A: t1 = threading.Thread(target=timeout(CONS,5))

Here you call the function timeout and then you pass the result as target for the new Thread. So timeout is executed before t1 is created. If you want to pass arguments to the thread target, do it like this:
t1 = threading.Thread(target=timeout, args=(CONS,5))

Also you never use the global variable in timeout. So the result will still be the same even after you make the correction mentioned above.