text:
Q: Spark is throwing UnsatisfiedLinkError error I'm running a clustered vagrant setup where I have ubuntu 14.04 and java 8 installed on my master and slave machines. My cluster successfully starts up with the slaves able to connect, however I'm not running hadoop. Instead I'm running the standalone version of spark 1.2.1.
I then copied the basic SparkPi example and compiled it with this pom:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>dev.quant</groupId>
  <artifactId>neural-spark</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>${project.artifactId}</name>
  <description>My wonderfull scala app</description>
  <inceptionYear>2010</inceptionYear>
  <licenses>
    <license>
      <name>My License</name>
      <url>http://....</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <encoding>UTF-8</encoding>
    <scala.tools.version>2.10</scala.tools.version>
    <scala.version>2.10.4</scala.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
    </dependency>

    <!-- Test -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.specs2</groupId>
      <artifactId>specs2_2.10</artifactId>
      <version>3.0-M1</version>
    </dependency>
    <dependency>
      <groupId>org.scalatest</groupId>
      <artifactId>scalatest_2.10</artifactId>
      <version>3.0.0-SNAP4</version>
    </dependency>
      <dependency>
          <groupId>org.apache.spark</groupId>
          <artifactId>spark-core_2.11</artifactId>
          <version>1.2.0</version>
      </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <testSourceDirectory>src/test/scala</testSourceDirectory>
    <plugins>
        <plugin>
            <groupId>net.alchim31.maven</groupId>
            <artifactId>scala-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>scala-compile-first</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>add-source</goal>
                        <goal>compile</goal>
                    </goals>
                </execution>
                <execution>
                    <id>scala-test-compile</id>
                    <phase>process-test-resources</phase>
                    <goals>
                        <goal>testCompile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.13</version>
        <configuration>
          <useFile>false</useFile>
          <disableXmlReport>true</disableXmlReport>
          <!-- If you have classpath issue like NoDefClassError,... -->
          <!-- useManifestOnlyJar>false</useManifestOnlyJar -->
          <includes>
            <include>**/*Test.*</include>
            <include>**/*Suite.*</include>
          </includes>
        </configuration>
      </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>dev.quant.App</mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </plugin>
    </plugins>
  </build>
</project>

Which works -> mvn -U clean scala:compile assembly:single
The program I run is:
package dev.quant

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.SparkContext._

import scala.math._

/**
 * @author ${user.name}
 */

object App {

  def foo(x : Array[String]) = x.foldLeft("")((a,b) => a + b)

  def main(args : Array[String]) {
    val conf = new SparkConf().setAppName("Spark Pi").setMaster("spark://10.0.0.2:7077").set("spark.executor.memory",".5g")
    val spark = new SparkContext(conf)
    val slices = 20
    val n = math.min(100000L * slices, Int.MaxValue).toInt // avoid overflow
    val count = spark.parallelize(1 until n, slices).map { i =>
        val x = random * 2 - 1
        val y = random * 2 - 1
        if (x*x + y*y < 1) 1 else 0
      }.reduce(_ + _)
    println("Pi is roughly " + 4.0 * count / n)
    spark.stop()
  }

}

So basically after running -> mvn scala:run -DmainClass=dev.quant.App I get the following error bellow...
15/03/04 22:46:15 INFO SecurityManager: Changing view acls to: dev
15/03/04 22:46:15 INFO SecurityManager: Changing modify acls to: dev
15/03/04 22:46:15 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(dev); users with modify permissions: Set(dev)
15/03/04 22:46:16 INFO Slf4jLogger: Slf4jLogger started
15/03/04 22:46:16 INFO Remoting: Starting remoting
15/03/04 22:46:16 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriver@192.168.0.2:50662]
15/03/04 22:46:16 INFO Utils: Successfully started service 'sparkDriver' on port 50662.
15/03/04 22:46:16 INFO SparkEnv: Registering MapOutputTracker
15/03/04 22:46:16 INFO SparkEnv: Registering BlockManagerMaster
15/03/04 22:46:16 INFO DiskBlockManager: Created local directory at /tmp/spark-b8515bff-2915-4bc2-a917-fdb7c11849b5/spark-3527d111-3aac-4378-b493-17c92b394018
15/03/04 22:46:16 INFO MemoryStore: MemoryStore started with capacity 265.1 MB
Exception in thread "main" java.lang.ExceptionInInitializerError
    at org.apache.spark.util.Utils$.getSparkOrYarnConfig(Utils.scala:1873)
    at org.apache.spark.storage.BlockManager.<init>(BlockManager.scala:105)
    at org.apache.spark.storage.BlockManager.<init>(BlockManager.scala:180)
    at org.apache.spark.SparkEnv$.create(SparkEnv.scala:308)
    at org.apache.spark.SparkEnv$.createDriverEnv(SparkEnv.scala:159)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:240)
    at dev.quant.App$.main(App.scala:18)
    at dev.quant.App.main(App.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:358)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:131)
    at org.apache.hadoop.security.Groups.<init>(Groups.java:64)
    at org.apache.hadoop.security.Groups.getUserToGroupsMappingService(Groups.java:240)
    at org.apache.hadoop.security.UserGroupInformation.initialize(UserGroupInformation.java:255)
    at org.apache.hadoop.security.UserGroupInformation.setConfiguration(UserGroupInformation.java:283)
    at org.apache.spark.deploy.SparkHadoopUtil.<init>(SparkHadoopUtil.scala:44)
    at org.apache.spark.deploy.SparkHadoopUtil$.<init>(SparkHadoopUtil.scala:214)
    at org.apache.spark.deploy.SparkHadoopUtil$.<clinit>(SparkHadoopUtil.scala)
    ... 15 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:129)
    ... 22 more
Caused by: java.lang.UnsatisfiedLinkError: org.apache.hadoop.security.JniBasedUnixGroupsMapping.anchorNative()V
    at org.apache.hadoop.security.JniBasedUnixGroupsMapping.anchorNative(Native Method)
    at org.apache.hadoop.security.JniBasedUnixGroupsMapping.<clinit>(JniBasedUnixGroupsMapping.java:49)
    at org.apache.hadoop.security.JniBasedUnixGroupsMappingWithFallback.<init>(JniBasedUnixGroupsMappingWithFallback.java:38)
    ... 27 more

I've also tried just submitting the jar via ./spark-submit /path/to/my-jar but no avail. I have never seen this error before, but my first impression is that JniBasedUnixGroupsMappingWithFallback is some java library that my binary spark distribution depends on, but java 8 doesn't have it. Anyway, let me know if you guys have any idea what it might be.

A: Caused by: java.lang.UnsatisfiedLinkError: org.apache.hadoop.security.JniBasedUnixGroupsMapping.anchorNative()V

might be the cause of your problem. You might need to use the correct and compatible version of hadoop.
Relative thread: HBase Cluster: org.apache.hadoop.security.JniBasedUnixGroupsMapping.anchorNative()V


text:
Q: I'm getting this error when I'm intsalling tensorflow-gpu version. How to solve this?
This is the error I'm getting in command prompt when I'm trying to import tensorflow into python3.5:
File "<stdin>", line 1, in <module>
File "D:\S7\ml_spl\Anaconda2\envs\tensorflowGPU\lib\site-
packages\tensorflow\__init__.py", line 24, in <module>
from tensorflow.python import *
File "D:\S7\ml_spl\Anaconda2\envs\tensorflowGPU\lib\site-
packages\tensorflow\python\__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow
File "D:\S7\ml_spl\Anaconda2\envs\tensorflowGPU\lib\site-
packages\tensorflow\python\pywrap_tensorflow.py", line 52, in <module>
raise ImportError(msg)
ImportError: Traceback (most recent call last):
File "D:\S7\ml_spl\Anaconda2\envs\tensorflowGPU\lib\site-
packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in
swig_import_helper
return importlib.import_module(mname)
File "D:\S7\ml_spl\Anaconda2\envs\tensorflowGPU\lib\importlib\__init__.py",
line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 985, in _gcd_import
File "<frozen importlib._bootstrap>", line 968, in _find_and_load
File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
File "<frozen importlib._bootstrap>", line 577, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 938, in create_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
ImportError: DLL load failed: The specified module could not be found.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\S7\ml_spl\Anaconda2\envs\tensorflowGPU\lib\site-
packages\tensorflow\python\pywrap_tensorflow.py", line 41, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "D:\S7\ml_spl\Anaconda2\envs\tensorflowGPU\lib\site-
packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in
<module>
_pywrap_tensorflow_internal = swig_import_helper()
File "D:\S7\ml_spl\Anaconda2\envs\tensorflowGPU\lib\site-
packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in
swig_import_helper
return importlib.import_module('_pywrap_tensorflow_internal')
File "D:\S7\ml_spl\Anaconda2\envs\tensorflowGPU\lib\importlib\__init__.py",
line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: No module named '_pywrap_tensorflow_internal'

I'm seeing the above error when I'm trying to install tensorflow gpu version in an anaconda environment with python3.5 and other dependencies installed. Can someone tell me how to solve this problem?

A: Did you install cudnn 6.0 and cuda 8? This issue suggests that either those are not properly installed or you have the wrong version.
Instructions on what version and steps for installation for gpu support are on the tensorflow site

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I add a click event to popup in Elementor? Using WordPress and Elementor page builder I created a navmenu popup template. I want to fade-in submenu items and hide the menu when clicking a menu item that has a sub menu in it.
When I add JavaScript code to the popup (using add-ons), eventlistener function doesn't work, but my code works fine. I use it in simple pages but not in the popup itself; I tried (custom CSS and JS) plugin it didn't work either. Is it a bug in Elementor or can't addevenlistener work for an element in the popup in the usual way?
Code :
const element = document.querySelector('.element');

console.log(element);  < ------------------------------here is working!!!

element.addEventListener('click', function(){
    any code in here <---------------------------------------not working !
});

A: I think the problem might be, that you are using querySelector. It returns the first Element within the document that matches the specified selector, or group of selectors.
With wordpress, you are able to use jQuery instead of pure javascript. So you are able to use .click. Might be worth a try using another way to achieve what you want:
( function( $ ) {
    $(document).ready(function () {
      $(".element").click(function (e) {
        e.preventDefault();
        // any code here
      });
    });
}( jQuery ) );

Here is some more information: https://api.jquery.com/click/
But if you like to use pure javascript, you can use for every element like:
window.onload = function () {
  element = document.querySelectorAll(".element");
  for (var i = 0; i < element.length; i++) {
    element[i].addEventListener("click", function (e) {
        e.preventDefault();
        // any code here
    });
  }
};


text:
Q: How to call Live Template's select menu in PhpStorm? I'm watching some video course. An author of the course uses Live Templates in PhpStorm. It looks like pretty comfortable. I have never used it before. See, how it looks like (it's a screen from the video):

If the author press Enter, the string You are on a Category/Index page will be wrapped on a special construction.
I have prepared the same for myself. This is my settings:

But I can't find hotkey to call context menu like in the previous screen. Please, tell me how to call this Select template menu?

A: The shortcut is simple: use whatever you have got there for Code | Surround with... -- it will list ALL applicable stuff which includes Live Templates.

For Live Templates alone, that would be Ctrl + Alt + J on Windows keymap. You can check and change that via Settings/Preferences | Keymap -- look for Other | Surround with Live Template... action (you may use search field to quickly narrow it down):

More on Live Templates: https://www.jetbrains.com/help/phpstorm/using-live-templates.html

P.S. You have not defined "applicable contexts" on your last screenshot (with the actual Live Template).


text:
Q: Export VM from Proxmox I want to export the vm from proxmox to virtualbox or vmware.
Is it possible? and how?

A: You may not be able to export an entire VM to another hypervisor, but you can at least export the disk(s):
With VirtualBox:
First, if the disk is not a "raw" type, then run the following on the KVM hypervisor/server:
qemu-img convert -f qcow2 kvm_source.img -O raw kvm_destination.img

Then, from VirtualBox:
VBoxManage convertfromraw   <filename> <outputfile>
                            [--format VDI|VMDK|VHD]
                            [--variant Standard,Fixed,Split2G,Stream,ESX]
                            [--uuid <uuid>

With KVM:
qemu-img convert -O vdi kvm_source.img vbox_destination.vdi

No promises because I've never had to do this myself, but they should work.  Also, I would put my money on the KVM solution, personally...
http://www.krisbuytaert.be/blog/converting-kvm-virtualbox

A: Proxmox supports two kinds of virtualization technologies, namely full virtualization and container. There are several well known full virtualization productions such as KVM, Xen, and Vmware while container prodcutions includes lxc and OpenVZ. Proxmox only supports KVM and OpenVZ at the moment. So I think your problem is the same as "how to convert a KVM VM to virtualbox or vmware VM". As far as I know, there is not a easy way to convert a KVM vm to a vmware VM. Just Google it by yourself.

A: This answer is incomplete, but it should help get you started.

I want to export the vm from proxmox to virtualbox or vmware. Is it possible ?

Yes

How ?

The exact method really depends on how your VM is stored.
Assuming you have a simple setup with 1 computer acting as both the hypervisor and the storage.

*

*ssh to the hypervisor (or otherwise get a shell). You will probably need to be root for commands later

*Determine how your VM is stored

*

*File on disk, eg qcow, vmdk etc will typically be in /var/lib/vz/images

*On a logical volume use lvs to list the logical volumes

You can now copy the files somewhere else and convert them using qemu-img convert per Soviero's response.
If you're behind a firewall you might need to pipe data in reverse via ssh
As an example I needed to move some VM's from one hypervisor to another. Both were using logical volumes to store the raw images so I did the following
source# lvs --units b  2>/dev/null | grep vm-111
  vm-111-disk-1 vglocal01  -wi-ao---  17179869184B

destination# lvcreate -L 17179869184b -n vm-111-disk-1 vg_vms

source# dd if=/dev/vglocal01/vm-111-disk-1 | ssh destination dd of=/dev/vg_vms/vm-111-disk-1


text:
Q: post values to rest API with jQuery The code is not posting data to my API and I need to post vales from register form
I tried to post the data using this method but seems not to be working can anyone point me to the right direction here, also some different ways I can get data from the form efficiently
$(function (){
      console.log("Hellows");
      var $businessname = $('#businessname');
      var $email = $('#email');
      var $address = $('#address');
      var $cellphone = $('#cellphone');
      var $username = $('#username');
      var $password = $('#password');
      var $re_password = $('#re_password');

      $('#submit').on('click', function(){
     $.ajax({

        url: 'http://slimapp/api/business/add',
        method: 'POST',
        dataType:'json',
            data:{
               BusinessName: ''+$('#businessname').html($('input:textbox').val())+'',
              email: ''+$('#email').html($('input:textbox').val())+'',
              Address: ''+$('#address').html($('input:textbox').val())+'',
              cellphone: ''+$('#cellphone').html($('input:textbox').val())+'',
              username: ''+$('#username').html($('input:textbox').val())+'',
              password: ''+$('#password').html($('input:textbox').val())+''
            },
            success: function(data){
                console.log('success!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
            }
        })
      })

    });

A: What is this $('#businessname').html($('input:textbox').val()). It's worng syntext to get value of textbox.
Here is correct ajax request.
$('#submit').on('click', function(){
     $.ajax({
            url: 'http://slimapp/api/business/add',
            method: 'POST',
            dataType:'json',
            contentType: 'application/json',
            data:{
              BusinessName: $('#businessname').val(),
              email: $('#email').val(),
              Address: $('#address').val(),
              cellphone: $('#cellphone').val(),
              username: $('#username').val(),
              password: $('#password').val()
            },
            success: function(data){
                console.log('success!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
            }
        });
    })


text:
Q: ImageIO and URLs Having some annoying issues with loading images into a BufferedImage (image in the example) with the use of ImageIO.read, due to there being spaces in the Image name;
image = ImageIO.read(new File(getClass().getResource("/Pictures/H ello.jpg").getPath()));

If I rename the url(?) "/Pictures/H ello.jpg" to "/Pictures/Hello.jpg" and the source image to Hello.jpg it works just fine.
I've tried replacing the spaces with %20 as found on other questions and also a replace char of ' ' to '+'. So what am I doing wrong? Would encoding solve my problem and how would I do that?
Thanks,

A: The following possibly works.
image = ImageIO.read(getClass().getResourceAsStream("/Pictures/H ello.jpg"));

A: java.net.URL path = getClass().getResource("/Pictures/H ello.jpg");
ImageIO.read(new File(path.toURI()));

Does this work? I think it should. URL will decode space as %20 and File constructor should process it properly as an URI

A: if you want this way, then you need to decode the url:
image = ImageIO.read(new File(URLDecoder.decode(getClass().getResource("/Pictures/H ello.jpg").getPath(), "UTF-8")));

but, if I need to work with resources, I'd use overloaded method ImageIO.read(URL) or ImageIO.read(InputStream) :
image = ImageIO.read(getClass().getResource("/Pictures/H ello.jpg"));
image = ImageIO.read(getClass().getResourceAsStream("/Pictures/H ello.jpg"));

see apidoc


text:
Q: unity 2D player movement parameters do not exist I've managed to make a little top down shooter now I'm going over animations. I have followed a couple tutorials by pixelnest.io but strangly I'm getting an error saying "parameter 'moveRight' does not exist. animation in unity is completely new to me and have been trying to read up as much as I can. any suggestions to fix the animation so it plays when I move right? below are some pictures and my code.

using UnityEngine;

using System.Collections;
public class playerMove : MonoBehaviour {
public float maxSpeed = 5f;
Animator animator;
bool isRight;

void Awake(){
    animator = GetComponent<Animator>();
}

void Update(){
    Vector3 posMove = transform.position;
    Vector3 velocityH = new Vector3 (Input.GetAxis ("Horizontal") * maxSpeed * Time.deltaTime, 0, 0);
    //this is just test a before i add it to the right movement
    animator.SetBool ("moveRight", isRight);

    Vector3 velocityV = new Vector3 (0, Input.GetAxis ("Vertical") * maxSpeed * Time.deltaTime, 0);
    posMove += velocityH + velocityV;
    transform.position = posMove;
}

}

A: This is  because you don't have a boolean called "moveRight" in your animator.
Look at the first screenshot you posted. In the bottom left corner, you've declared a single boolean named "isRight".
While using Animator.SetBool(yourBool, boolValue), you first parameter you need to pass is the name of the boolean declared in the animator (in this case, it's "isRight").
Change the following line of code in your script
Change this line
animator.SetBool ("moveRight", isRight);

to read
animator.SetBool ("isRight", isRight);


text:
Q: LiveData vs Observable data object According to the LiveData documentation, one of the features has been designed to notify data changes using observable pattern.
(Along with this,LiveData offers a number of other promising features)
On the other hand, the Observable data object based on its documentation is capable of notifying others about changes in its data.
As a result, these two features seem are same.
The question is:
isn't it better to use LiveData with its other features?

A: According to LiveData documentation:

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

So it is essentially a lifecycle-aware observable, now it is an advantage, isn't it?
However, there is really no restriction about using only RxJava or LiveData, the two can be used along with each other.
Actually, it better to use RxJava when there is no lifecycle available like Repository in the data layer and keep LiveData in layers that lifecycle is important like the Presentation layer.

A: LiveData is like an observable but like unlike an observable, it is lifecycle aware. So this means that the live data will only update app component observers that are in an active state. However, you don't always need to use livedata. I would say livedata comes in handy when there are lifecycle components involved such as activities and fragments. For more information look at When to use RxJava in Android and when to use LiveData from Android Architectural Components?

A: The observable in the question is ObservableFields, not RxJava Obervervable like the other answers mentioned.
It's a good question to compare between LiveData and ObservableFields. Because live data is lifecycle aware, it can do a lot of things. You can observe the live data from the view model and update the UI from the code. You can also extend the live data and use it like an event bus to notify the data change between 2 Android components and you don't need to worry about the lifecycle issue.
But does that mean it is not necessary to use ObservableFields at all? No. Because data binding itself is lifecycle aware, it already checks when the view is active. You can use LiveData or ObservableFields or even Stateflow
In one-way data binding, you can use any of them, but in 2-way data binding, I still prefer observable fields, because it's more flexible, and you can easily write custom logic in the observable field setter, and when the UI changes, it can call the setter to do some additional stuff.
class LoginViewModel : BaseObservable {
    // val data = ...

    @Bindable
    fun getRememberMe(): Boolean {
        return data.rememberMe
    }

    fun setRememberMe(value: Boolean) {
        // Avoids infinite loops.
        if (data.rememberMe != value) {
            data.rememberMe = value

            // React to the change.
            saveData()

            // Notify observers of a new value.
            notifyPropertyChanged(BR.remember_me)
        }
    }
}

And in xml file.
<CheckBox
    android:id="@+id/rememberMeCheckBox"
    android:checked="@={viewmodel.rememberMe}"
/>


text:
Q: How to change a file type and run that file using a batch file? I am currently trying to use a file downloaded from the internet but run it as a different file. I have written:
cscript.exe /NoLogo "https://somesite.net/personal/me/Shared%%20Documents/filetorun.vbr" >"numbers.txt""

but I actually wanted to run filetorun.vbr as a .vbs file. For security reasons, I could not upload the .vbs version so I had to settle for .vbr.
What can I do to run the vbr file as a vbs file?
Thank you for helping!

A: According to this article http://technet.microsoft.com/en-us/library/bb490887.aspx
Cscript.exe only support *.vbs and *.js

Cscript.exe is a command-line version of the Windows Script Host that
  provides command-line options for setting script properties. With
  Cscript.exe, you can run scripts by typing the name of a script file
  at the command prompt. Like Microsoft Internet Explorer, Windows
  Script Host serves as a controller of Windows Script compliant
  scripting engines, but Windows Script Host has very low memory
  requirements. Windows Script Host is ideal for both interactive and
  non-interactive scripting needs, such as logon scripting and
  administrative scripting. Windows Script Host supports scripts written
  in VBScript or JScript. When you start a script from your desktop or
  from the command prompt, the script host reads and passes the
  specified script file contents to the registered script engine. The
  script engine uses file extensions (that is, .vbs for VBScript and .js
  for JScript) to identify the script. As a result, you do not need to
  know the exact programmatic identifier (that is, the ProgID) of the
  script engine. The script host maintains a mapping of script
  extensions to programmatic identifiers, and uses the Windows XP
  association model to start the appropriate engine for a given script.
  For more information about Windows Script Host, see Windows Script
  Host For more information about CScript.exe, see To run scripts using
  the command-line-based script host (cscript.exe)

A: You can specify the scripting language with the /E option:
cscript.exe /E:VBS myfile.vbr

A: Yes. It will run vbr. It is your URL that is wrong. You have two percent signs. But in script just use a space, as we aren't a browser and don't have to follow their silly rules.
wscript //e:vbs "C:\Users\A User\Desktop\CreateTextFile.vbr"

A: Windows Script Host cannot run scripts directly from Internet (from HTTP/HTTPS links). You need to download the script to your computer first.
For example, using VBScript:
strURL = "https://somesite.net/personal/me/Shared%%20Documents/filetorun.vbr"
strFileName = "C:\filetorun.vbs" ' Note the VBS extension - you can rename files when downloading

DownloadFile strURL, strFileName

Dim oShell : Set oShell = CreateObject("WScript.Shell")
oShell.Run "cscript """ + strFileName + """"

Sub DownloadFile(URL, LocalFileName)
  Dim oHttp : Set oHttp = CreateObject("Microsoft.XMLHTTP")
  Dim oStream : Set oStream = CreateObject("ADODB.Stream")

  oHttp.Open "GET", URL, False
  oHttp.Send

  oStream.Type = 1 ' adTypeBinary
  oStream.Open
  oStream.Write oHttp.responseBody
  oStream.SaveToFile LocalFileName, 2 ' adSaveCreateOverWrite
End Sub


text:
Q: angular-google-maps , undefined is not a function I'm having some issues to put angular-google-maps working on my website.
After include the needed libraries (googleapis/ lodash.js/ angular-google-maps.min.js), I'm unable to configure the app.
I added 'google-maps' to the app module, like this:
var app = angular.module('app', ['iso.directives', 'ngSanitize', 'ui.select', 'facebook', 'google-maps'.ns()]);

And I received, "undefined is not a function" error.
I'm following the tutorial in https://angular-ui.github.io/angular-google-maps/#!/use
I've seen this (.ns() undefined in google angular maps directive) thread, but doesn't help.
Can anyone help me?
Thanks!

A: It looks like they've gotten rid of the ns() function, but haven't updated the documentation yet:
https://github.com/angular-ui/angular-google-maps/pull/872/
https://github.com/angular-ui/angular-google-maps/issues/821
Update all instances of 'string'.ns() to 'uiGmapstring' in your code and you should be good.


text:
Q: Paging controls not showing in Mage2 listing page (ui_component) Here's the relevant portion of the XML to create a listing page. For some reason the paging component won't show. I've been looking over this for hours, any idea where I need to look next to enable pagination?
<listingToolbar name="fulfillment_code_grid_top">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="template" xsi:type="string">ui/grid/toolbar</item>
        </item>
    </argument>

    <bookmark name="bookmarks">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/controls/bookmarks/bookmarks</item>
                <item name="displayArea" xsi:type="string">dataGridActions</item>
                <item name="storageConfig" xsi:type="array">
                    <item name="namespace" xsi:type="string">fulfillment_code_grid</item>
                </item>
            </item>
        </argument>
    </bookmark>

    <paging name="fulfillment_code_grid_paging">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="storageConfig" xsi:type="array">
                    <item name="provider" xsi:type="string">fulfillment_code_grid.fulfillment_code_grid.fulfillment_code_grid_top.bookmarks</item>
                    <item name="namespace" xsi:type="string">current.paging</item>
                </item>
                <item name="selectProvider" xsi:type="string">fulfillment_code_grid.fulfillment_code_grid.fulfillment_columns.ids</item>
                <item name="options" xsi:type="array">
                    <item name="20" xsi:type="array">
                        <item name="value" xsi:type="number">20</item>
                        <item name="label" xsi:type="string" translate="true">20</item>
                    </item>
                    <item name="30" xsi:type="array">
                        <item name="value" xsi:type="number">30</item>
                        <item name="label" xsi:type="string" translate="true">30</item>
                    </item>
                    <item name="50" xsi:type="array">
                        <item name="value" xsi:type="number">50</item>
                        <item name="label" xsi:type="string" translate="true">50</item>
                    </item>
                    <item name="100" xsi:type="array">
                        <item name="value" xsi:type="number">100</item>
                        <item name="label" xsi:type="string" translate="true">100</item>
                    </item>
                    <item name="200" xsi:type="array">
                        <item name="value" xsi:type="number">200</item>
                        <item name="label" xsi:type="string" translate="true">200</item>
                    </item>
                </item>
            </item>
        </argument>
    </paging>
</listingToolbar>

A: I finally figured it out, by installing a sample plugin and hacking on its <paging> tag.
I discovered it can be as simple as <paging name="listing_paging">, however the catch seems to be the name="listing_paging" part. Originally had name="fulfillment_code_grid_paging"; changing it brought the control onto the page.


text:
Q: Pod file not being initialized? When i try to initialize pod file to use cocoapods via terminal, it gives me this error. How to fix it.
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command.rb:128:in `verify_minimum_git_version!': [!] You need at least git version 1.8.5 to use CocoaPods (Pod::Informative)

A: I encounter the same problem and solve it by using the following command:
sudo xcode-select --switch /Applications/Xcode.app

As the error message in terminal shows, something with my git goes wrong. And, it has to do with the command line tool.

A: You need to set command line tool version, in Xcode:
You can download latest command line tool from Apple Download Portal, if you have paid apple developer account/id.
Here are current beta and stable Xcode Tool and supporting command line tool download link. (Ensure you'are logged in using premium developer account on Apple Developer Account to access these links)

Xcode 11

*

*Xcode 11.2 beta 2
 - (Command Line Tool (Xcode 11.2 beta 2) - for macOS 10.14)

*Xcode 11
 - (Command Line Tool (Xcode 11) - for macOS 10.14)
Xcode 10

*

*Xcode 10.2.1
 - (Command Line Tool (Xcode 10.2.1) - for macOS 10.14)

*Xcode 10.2
 - (Command Line Tool (Xcode 10.2) - for macOS 10.14)

*Xcode 10.1
 - (Command Line Tool (Xcode 10.1) - for macOS 10.14)
 - (Command Line Tool (Xcode 10.1) - for macOS 10.13)

*Xcode 10
 - (Command Line Tool (Xcode 10) - for macOS 10.14)
 - (Command Line Tool (Xcode 10) - for macOS 10.13)

Once you've latest command line tool installed in your system, set it from Xcode Menu.

(Xcode Menu Items) Xcode ▶ Preferences ▶ Location ▶ Command Line Tool ▶ Select appropriate command line tool

A: I was having an issue while trying to install packages using cocoapods. I have tried  "sudo xcode-select --switch /Applications/Xcode.app" still getting wrong path error
To fix this
I opened Xcode.
Preferences
Locations
Selected the Command Lin Tools: Xcode 9.0

Now when installing packages with cocoapods I no longer get errors.

A: If you have upgraded your MAC from the App Store, then you need to run: xcode-select --install
When I ran git --version before running the command above, it didn't find git at all. It displayed this error: missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun. So, I'm guessing when I upgraded my machine somehow I lost git. Regardless, running the above command worked.
I then ran git --version and it showed the git version that was installed.
Reference: http://tips.tutorialhorizon.com/2015/10/01/xcrun-error-invalid-active-developer-path-library-developer-commandline-tools-missing-xcrun/

A: After installing OS Mojave and installed new Xcode tools i just had to check again the tools in:

Xcode > Preferences > Locations > Command Line tools = Xcode 10.0

A: Sometimes its version issue.
Installing CoacoaPods 1.7.5 did the trick.
sudo gem uninstall cocoapods
sudo gem install cocoapods -v 1.7.5
pod setup

A: Hey this might help you!!! I followed this link
https://stackoverflow.com/a/16664135/7905401
After installing command line tools i closed it and opened terminal again now when i checked version git --version it gave me update version 2.10.0 then i ran other commands for cocoapod!! its working!!!!!!!!! yeeeii!!!!

A: I fixed the problem with next steps:
sudo gem install cocoapods --source http://rubygems.org

after command finish entering new command
pod install

and work for me  on xCode 11.2

A: I followed this
After installing command line tools, I closed it and opened terminal again. Now when I checked version git --version, it gave me update version 2.10.0 then I ran other commands for cocoapod.
Now it is working.


text:
Q: Pass multiple numbers into an Add method that uses a params modifier? Refer to this answer: Pass multiple optional parameters to a C# function
Question about Params (to a point).  What I want to know is, how (if possible) can this be used to take user input rather than predefined numbers?
So, I understand that I can do Console.Write(calculator.Add(1, 43, 23)) but would like to deal with user input.
class Program
{
    static void Main(string[] args)
    {
        var calculator = new Calculator();
        var input = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine(calculator.Add(input));
    }
}

public class Calculator
{
    public int Add(params int[] numbers)
    {
        var sum = 0;
        foreach (var number in numbers)
        {
            sum += number;
        }
        return sum;
    }
}

A: You can store all the user inputs in an array and pass the array to Add.
var calculator = new Calculator();
var input = Array.ConvertAll<int>(Console.ReadLine().Split(' '));
calculator.Add(input);

A: Something along these lines should work. I might have made syntax errors :D
using System;
class Program
{
    static void Main(string[] args)
    {
        var calculator = new Calculator();
        var input = GetNumbers();
        calculator.Add(input);
        Console.WriteLine(calculator.Add(input));
    }

    public static int[] GetNumbers()
    {
      Console.WriteLine("Enter Numbers Seperated With a Space");
      string input = Console.ReadLine(); //Get user input with this
      string[] arr = input.Split(' '); //Split the input at spaces
      int[] output = new int[arr.Length]; //create in array of same length

      for(int i = 0; i < output.Length; i++)
      {
          output[i] = Int32.Parse(arr[i]); //parse every value and add to int array
      }
      return output;
    }
}

public class Calculator
{
    public int Add(params int[] numbers)
    {
        var sum = 0;
        foreach (var number in numbers)
        {
            sum += number;
        }
        return sum;
    }
}


text:
Q: Split one column into two columns based on the row is odd or even I am currently looking for a way in which I can split a column in excel into two column.
The way I want to split is all data in the odd rows (1,3,5,…) should be in column A and all the data in the even rows (0,2,4,6,…) should be in column B…  how can this be done in excel, without having me to create the columns, and fill them up.

A: In B1 enter:
=INDEX(A:A,2*ROW()-1)

and copy downward and in C1 enter:
=INDEX(A:A,2*ROW())

and copy downward:

A: Or one formula in B1:
=INDEX($A:$A,(ROW(1:1)-1)*2+COLUMN(A:A))

Copy/drag over one column and down till you run out of data.


text:
Q: JQuery toggleClass not working in React.js when i try to click on the element If i try to toggle the class(active) nothing hapens just flashing in the dev tools.
Here is the picture.
And here is my code:
let usercontainer = document.querySelector(".user-container")
let user = document.querySelector(".user")

$(user).on('click', function() {
    $(usercontainer).toggleClass(".active")
})

Here is how i render:

                F4||1ng

Kijelentkezés

Jegyzeteim

A: Few tips here:

*

*Use the $ shortcut instead of document.querySelector

*When using toggleClass, use the class name without the dot in front.

Something like this:
let usercontainer = $(".user-container")
$(".user").on('click', function() {
  usercontainer.toggleClass("active")
})

See https://codepen.io/jr-duboc/pen/NWXepRG


text:
Q: How do I add a delay on a button click in react? I'm attempting to delay a button click so that the library I'm using can make a quick api call for validation. I'm currently using an arrow function in react and attempting setTimeout. However it appears this is triggering a call on page load for some reason. Here's my code.
  onClick={this.handleCardSubmit}

handleCardSubmit = setTimeout(() => {
    this.setState({ showLoaderForPayment: true });
    const { collectJs } = this.state;
    collectJs.startPaymentRequest();
    this.setState({ isPaymentRequestCalled: true });
  }, 500);

A: Hi you need to change you function declaration and definition as follows
handleCardSubmit = ()=>{
setTimeout(() => {
    this.setState({ showLoaderForPayment: true });
    const { collectJs } = this.state;
    collectJs.startPaymentRequest();
    this.setState({ isPaymentRequestCalled: true });
  }, 500);
}

In you code snippet, you are just passing the settimeout function reference to handeCardSubmit , so there is not binding of this. In order to execute it properly, you will have to write setTimeout function inside an arrow function, then it will work as with delay of 500ms.

A: You can use e.preventDefault(), and try the below code.
handleCardSubmit = (e) => {
    e.preventDefault();
    setTimeout(() => {
    this.setState({ showLoaderForPayment: true });
    const { collectJs } = this.state;
    collectJs.startPaymentRequest();
    this.setState({ isPaymentRequestCalled: true });
  }, 500);
};

Or you can use async-await.
handleCardSubmit = async (e) => {
    e.preventDefault();
    await setdata();

    setdata() {
    this.setState({ showLoaderForPayment: true });
    const { collectJs } = this.state;
    collectJs.startPaymentRequest();
    this.setState({ isPaymentRequestCalled: true });
}
};


text:
Q: sql data query, How to get results from Sql when executing SELECT sex, COUNT(*) AS count FROM SinhVien WHERE sex =0 GROUP BY sex; in java language How to get results from Sql when executing SELECT  sex, COUNT(*) AS count FROM SinhVien WHERE sex =0 GROUP BY sex; in java language
please help me i really need to understand it now


text:
Q: printing slowly (Simulate typing) I am trying to make a textual game in python. All goes well however, I would like to make a function that will allow me to print something to the terminal, but in a fashion hat looks like typing.
Currently I have:
def print_slow(str):
    for letter in str:
        print letter,
        time.sleep(.1)

print_slow("junk")

The output is:
j u n k

Is there a way to get rid of the spaces between the letters?

A: Try this:
def print_slow(str):
    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(0.1)

print_slow("Type whatever you want here")

A: This is my "type like a real person" function:
import sys,time,random

typing_speed = 50 #wpm
def slow_type(t):
    for l in t:
        sys.stdout.write(l)
        sys.stdout.flush()
        time.sleep(random.random()*10.0/typing_speed)
    print ''

A: In Python 2.x you can use sys.stdout.write instead of print:
for letter in str:
    sys.stdout.write(letter)
    time.sleep(.1)

In Python 3.x you can set the optional argument end to the empty string:
print(letter, end='')

A: Try this:
import sys,time

def sprint(str):
   for c in str + '\n':
     sys.stdout.write(c)
     sys.stdout.flush()
     time.sleep(3./90)

sprint('hello world')


text:
Q: Performance degrade with Mongo when using bulkwrite with upsert I am using Mongo java driver 3.11.1 and Mongo Version 4.2.0 for my development.I am still learning mongo. My application receives data and either have to do insert or replace the existing document i.e. do an upsert.
Each document size is 780-1000 bytes as of now and each collection can have more than 3 millions records.
Approach 1: I tried using findOneandreplace for each document and it was taking more than 15 minutes to save the data.
Approach-2 I changed it to bulkwrite using below, which resulted in ~6-7 minutes for saving 20000 records.
List<Data> dataList;
dataList.forEach(data-> {
    Document updatedDocument = new Document(data.getFields());
    updates.add(new ReplaceOneModel(eq("DataId", data.getId()), updatedDocument, updateOptions));

  });
final BulkWriteResult bulkWriteResult = mongoCollection.bulkWrite(updates);

3) I tried using collection.insertMany which takes 2 seconds to store the data.
As per driver code, insertMany also Internally InsertMany uses MixedBulkWriteOperation for inserting the data similar to bulkWrite.
My queries are -
a) I have to do upsert operation, Please let me know where i am doing any mistakes.
 - Created the indexes on DataId field but resulted in <2 miliiseconds difference in terms of performance.
- Tried using writeConcern of W1, but performance is still the same.
b) why insertMany's performance is faster than bulk write. I could understand in terms of few seconds difference but unable to figure out the reason for 2-3 seconds for insertMany and 5-7 minutes for bulkwrite.
c) Are there any approaches that can be used to solve this situation.

A: This problem was solved to greater extent by adding index on DataId Field. Previously i had created index on DataId field but forgot to create index after creating collection.
This link How to improve MongoDB insert performance helped in resolving the problem


text:
Q: Check some permission is enabled among assigned permission sets of User I need to check if a permission is enabled among assigned permission sets of Logged in User.
Lets say I have 3 permission sets named as PSet1, PSet2 and PSet3 assigned to a User. Need to find out if 'Manage External Users' permission is set as true among these three permission sets.
Can you please guide me the way to achieve this.

A: If it's just a one-off, you can:
Boolean canManageExternalUsers = [
    SELECT COUNT()
    FROM PermissionSetAssignment
    WHERE AssigneeId = :UserInfo.getUserId()
    AND PermissionSet.PermissionsManagePartners = TRUE
] > 0;

If you need this in bulk, you'd have to optimize this to return the individual values and fields, and then loop through the results to determine which users have this permission.

A: Although you asked for an apex solution, here's a handy (free) Permission Set Helper app from SFDC Labs that can find users with a given permission using a UI. Note: LEX only


text:
Q: 301 redirect for url containing underscores I want to
redirect /directsystems/education/index/name/system_one
TO
http://www.mysite.com/directsystems/education/index/name/system-one
Can you please show me the 301 redirect rule for htaccess? As i want to redirect undescores with hypens

A: To replace all underscores _ with hyphen - in URI, use following rules in your .htaccess file:
Options +FollowSymlinks -MultiViews
RewriteEngine on

RewriteRule ^([^\_]+)_([^\_]+)(_.*)$ /$1-$2$3 [N,DPI]
RewriteRule ^([^\_]+)_(.*)$ /$1-$2 [L,R=301,DPI]

This redirects a URL of:
http://localhost/directsystems/education/index/my_name/system_one
to
http://localhost//directsystems/education/index/my-name/system-one

A: Try this:
RewriteRule ^([^_]*)_([^_]*)$ $1-$2


text:
Q: Cassandra query with index Imagine I have a table like this:
CREATE TABLE test(
  name  TEXT,
  tag   TEXT,
  id    UUID,
  parameter INT,
  PRIMARY KEY((name, tag, id), parameter)
);

and an index
CREATE INDEX parameter_idx on test(parameter);

With a query like this:
SELECT * FROM test WHERE name = 'name'
                     AND tag = 'tag'
                     AND parameter = value;

Is it correct that the index will be used, returns many partitions and that these partitions will then be filtered, thus requiring ALLOW FILTERING?
On the contrary a query like this one:
SELECT * FROM test WHERE name = 'name'
                     AND tag = 'tag'
                     AND id = some_id,
                     AND parameter = value;

will not use the index, a single partition will be found and only some rows corresponding to parameter = value will be returned.
Is this all correct?

A: You understanding sounds correct. Of course using a secondary index like that would be very inefficient. Usually it's better to design your schema so that a secondary index isn't needed for any of your queries.


text:
Q: My encryption algorithm I was bored and made up an encryption algorithm using Python. I'm just curious to find out if anyone would be interested in trying to break it, or maybe point me in the right direction of a forum or website where I could test the strength of my algorithm. If you can help me with this please respond to this question. Thanks

A: First, read this:
http://en.wikipedia.org/wiki/Brute_force_attack
Then follow the links.
Specifically, read this one: http://www.sciengines.com/copacobana/
Now that you've done some reading, you can download a brute-force encryption
breaker and break your code.
It's that easy.  We don't need to do it for you.  You can do it yourself.


text:
Q: Finding the names and the year of the movies that have at least 5 actors Given database of the website "eMovies" that manage data about cinema movies.

Write in SQL query that finds the names and the year of the movies that have at least 5 actors.

My attempt:
The idea: to do a natural joint between "Movies" and "ActorsMovies" tables, and then to count the rows with the same MovieID, and then to check if count>5
I succeded to count the rows thank's to @Phil's advice, but still I need the name of the movies and the year,
Here is my start:
SELECT DISTINCT Year, MovieName
FROM Movies, ActrorsMovies
SELECT Count(ActorsMovies.MovieID)
FROM ActorsMovies
GROUP BY ActorsMovies.MovieID
HAVING (((Count(ActorsMovies.ActorID))>5));

This code does not work

EDIT: another attempt
 SELECT DISTINCT Movies.Year, Movies.MovieName
 FROM Movies, ActorsMovies
 GROUP BY ActorsMovies.MovieID
 HAVING Count(ActorsMovies.ActorID)>5;

A: This code works in T-SQL and should work in Ms Access:
SELECT COUNT(M.MovieID) as 'Count', M.MovieName, M.Year FROM Movies M
INNER JOIN ActorsMovies AM ON AM.MovieID = M.MovieID
INNER JOIN Actors A ON AM.ActorID = A.ActorID
GROUP BY M.MovieID, M.MovieName, M.Year
HAVING COUNT(M.MovieID) > 5

I also recommend not to use Year as a field name because it's a reserverd keyword in Ms Access and may cause problems:
https://msdn.microsoft.com/en-us/library/bb208875(v=office.12).aspx

A: You were close
SELECT M.MovieID, M.MovieName, M.Year
  FROM Movies M
 INNER JOIN ActorsMovies AM
         ON AM.MovieID = M.MovieID
 GROUP BY M.MovieID, M.MovieName, M.Year
HAVING COUNT(AM.ActorID) > 5

You could probably just use count(*) > 5


text:
Q: Process only works from Web Application when using Local System Application Pool Identity I have a command line Process that I am attempting to run from my ASP.Net web application.
When the IIS7.5 Application Pool Identity is set to "Local System", the command line code executes.  When it is set as ApplicationPoolIdentity, it does not.  Since using the "Local System" is a security risk, I would simply like to grant the required permissions to the ApplicationPoolIdentity rather than using Local System.
If I understand this answer corretly: IIS AppPoolIdentity and file system write access permissions, the User "IIS AppPool[my app pool]" needs to be given permissions to whatever folders that my command line process will be modifying.  I have tried giving full permissions to this user for that folder, but it still does not work.  I have also tried full permissions for IUSR and IIS_USRS.  Please see my code below:
using (Process process = new Process())
        {
            process.StartInfo.FileName = fileToExecute;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;

            StringBuilder output = new StringBuilder();
            StringBuilder error = new StringBuilder();

            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
            using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
            {
                process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        output.AppendLine(e.Data);
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        error.AppendLine(e.Data);
                    }
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                int timeout = 1000;
                if (process.WaitForExit(timeout) &&
                    outputWaitHandle.WaitOne(timeout) &&
                    errorWaitHandle.WaitOne(timeout))
                {
                    Logs logs = new Logs("Finished! - Output: " + output.ToString() + " | Error: " + error.ToString());
                    logs.WriteLog();
                }
                else
                {
                    // Timed out.
                    Logs logs = new Logs("Timed Out! - Output: " + output.ToString() + " | Error: " + error.ToString());
                    logs.WriteLog();
                }
            }
        }

Thanks in advance for any help!!!

A: It turns out that the setting "Load User Profile" under the Advanced Settings in the Application Pool had to be set to true.  By doing this the PGP encryption program was able to use the profile for temporary data storage, etc.

A: Try giving permissions to the IIS_IUSRS account.
Also, make sure the account has execute permissions on the file you're calling and any libraries it references.
I created some test code (below), the folder secret was given system and admin permissions only (not user). This means IIS could not view it by default (tested). I then gave IIS_IUSERS read permissions and it worked fine.
(results was displayed on screen)
Dim compiler As New Process()
compiler.StartInfo.FileName = "C:\Windows\System32\cmd.exe"
compiler.StartInfo.Arguments = "/C dir c:\Secret"
compiler.StartInfo.UseShellExecute = False
compiler.StartInfo.RedirectStandardOutput = True
compiler.Start()
Dim results As String = compiler.StandardOutput.ReadToEnd()
compiler.WaitForExit()

If your not sure what files need permissions, there is a program called process explorer that should enable you to see exactly what's in use.
http://technet.microsoft.com/en-gb/sysinternals/bb896653.aspx

A: What you can do is to create new windows account and assign rights that are required.
Type "mmc" inside start menu, this will open Management Console.
Go to "File" menu and select "Add/Remove Snap-in...".
Select "Local Users and Groups" then "Add".

Next add "Group Policy Object" in the same way as previous snap-in. You will endup with something like this:

Now create new windows user. Since you most likely dont want to allow this new user to be able to login localy we need to set aditional settings. Navigate to User Rights Assigment, you should see something like this:

Double click "Deny log on locally" and add your new user. Make sure you will also set apropriate file system rights.
In the end just open IIS Manager and assign new user to your application pool.
Best regards

A: I had a similar issue a while back while deploying a few web applications. In the end we solved our permissions issue by granting permission to:IIS_USRS,IUSR, LocalMachineName\Users, LocalMachineName$,SYSTEM, (and if your application is within a domain DomainName\IIS_WPG, DomainName\Domain Users)
NOTE: Within the Web.config
 <authentication mode="Windows" />
        <authorization>
            <deny users="?" />
            <allow users="*"/>
        </authorization>
<identity impersonate="false" />


text:
Q: Passport authenticate callback is not passed req and res this authenticate works fine and I get a redirect:
server.post(authPostRoute, passport.authenticate(
    'local'
    , { successRedirect: '/', failureRedirect: '/login' }
));

this authenticate hangs after the call back is called:
server.post(authPostRoute, passport.authenticate(
    'local'
    , function(){ console.log('Hitting the callback'); console.log(arguments)}
));

this logs the following piece:
{ '0': null,
  '1':
   { id: [Getter/Setter],
     firstName: [Getter/Setter],
     lastName: [Getter/Setter],
     email: [Getter/Setter],
     addedOn: [Getter/Setter],
     active: [Getter/Setter],
     password: [Getter/Setter] },
  '2': undefined }

But throughout the documentation (http://passportjs.org/guide/authenticate/)  it looks as though it shuold be passed req and res, but it obviously isn't.  Then the code that calls the callback:
node_modules\passport\lib\middleware\authenticate.js
  strategy.success = function(user, info) {
    if (callback) {
      return callback(null, user, info);
    }

doesn't pass those parameters.  What am I doing wrong?

A: OK, I was working on ripping out my custom authentication and replacing it with passport for 9 hours yesterday.  Between getting the node-orm to expos the model outside of the request and dealing with the flow of ordering things I was a little burned out.  THe code examples are accurate, I just needed to read more carefully:
// traditional route handler, passed req/res
server.post(authPostRoute, function(req, res, next) {

  // generate the authenticate method (the anonymous method) and
  //     associate it with the 'local' strategy
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/'); }

    // req / res held in closure
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.send(user);
    });

  })(req, res, next);

});

A: Enable passReqToCallback to get the request in callback. Like this:
passport.use(new FacebookStrategy({
    clientID: '555555555555555',
    clientSecret: '555555555555555555555',
    callbackURL: "http://localhost:3000/auth/facebook/callback",
    enableProof: false,
    passReqToCallback: true
  },
  // The request will be provided as 1st param
  function(req, accessToken, refreshToken, profile, done) {
  });...


text:
Q: Changing the font for "alert" in beamer I would like to change the behaviour of \alert so that the text is still red but now boldfaced, say.  How can I do this?  I have Googled, but all I can find is how to change the colour, as in Changing style of alert environment in beamer.

A: After some digging, I located the definition of \alert in beamerbaselocalstructure.sty. The rest was easy. ;-)
EDIT: There's also a more "beamer-like" way. :-)
\documentclass{beamer}

% \renewcommand<>{\alert}[1]{\begin{alertenv}\bfseries#2#1\end{alertenv}}
\setbeamerfont{alerted text}{series=\bfseries}

\begin{document}

\begin{frame}
\alert{Some text.}
\end{frame}

\end{document}


text:
Q: Is there a good template or project for a python package using Click and holding to the PEP517 standard? Building some packages with Click and using the old python setup.py install method for installing and then distributing my packages. I was wondering though if anyone had any projects or details on Click enabled python CLI tools that conform to the PEP517 standard? I did some googling and found https://pybit.es/articles/how-to-package-and-deploy-cli-apps/ but the authors don't actually seem to be building a CLI tool, and the GitHub is a little lacking.
Thanks!


text:
Q: Error when trying to start Flink job from retained checkpoint As I understand from the documentation, it should be possible to resume a Flink job from a checkpoint just as from a savepoint by specifing the checkpoint path in the "Savepoint path" input box of the web UI (e.g. /path/to/my/checkpoint/chk-1, where "chk-1" contains the "_metadata" file).
I've been trying this out but the I get the following exception:
2020-09-04 10:35:11
java.lang.Exception: Exception while creating StreamOperatorStateContext.
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.streamOperatorStateContext(StreamTaskStateInitializerImpl.java:191)
    at org.apache.flink.streaming.api.operators.AbstractStreamOperator.initializeState(AbstractStreamOperator.java:255)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.initializeStateAndOpen(StreamTask.java:1006)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.lambda$beforeInvoke$0(StreamTask.java:454)
    at org.apache.flink.streaming.runtime.tasks.StreamTaskActionExecutor$SynchronizedStreamTaskActionExecutor.runThrowing(StreamTaskActionExecutor.java:94)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.beforeInvoke(StreamTask.java:449)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:461)
    at org.apache.flink.runtime.taskmanager.Task.doRun(Task.java:707)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:532)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.flink.util.FlinkException: Could not restore keyed state backend for LegacyKeyedProcessOperator_632e4c67d1f4899514828b9c5059a9bb_(1/1) from any of the 1 provided restore options.
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:135)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.keyedStatedBackend(StreamTaskStateInitializerImpl.java:304)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.streamOperatorStateContext(StreamTaskStateInitializerImpl.java:131)
    ... 9 more
Caused by: org.apache.flink.runtime.state.BackendBuildingException: Caught unexpected exception.
    at org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackendBuilder.build(RocksDBKeyedStateBackendBuilder.java:336)
    at org.apache.flink.contrib.streaming.state.RocksDBStateBackend.createKeyedStateBackend(RocksDBStateBackend.java:548)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.lambda$keyedStatedBackend$1(StreamTaskStateInitializerImpl.java:288)
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.attemptCreateAndRestore(BackendRestorerProcedure.java:142)
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:121)
    ... 11 more
Caused by: java.nio.file.NoSuchFileException: /tmp/flink-io-ee95b361-a616-4531-b402-7a21189e8ce5/job_c71cd62de3a34d90924748924e78b3f8_op_LegacyKeyedProcessOperator_632e4c67d1f4899514828b9c5059a9bb__1_1__uuid_ae7dd096-f52f-4eab-a2a3-acbfe2bc4573/336ed2fe-30a4-44b5-a419-9e485cd456a4/CURRENT
    at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
    at sun.nio.fs.UnixCopyFile.copy(UnixCopyFile.java:526)
    at sun.nio.fs.UnixFileSystemProvider.copy(UnixFileSystemProvider.java:253)
    at java.nio.file.Files.copy(Files.java:1274)
    at org.apache.flink.contrib.streaming.state.restore.RocksDBIncrementalRestoreOperation.restoreInstanceDirectoryFromPath(RocksDBIncrementalRestoreOperation.java:483)
    at org.apache.flink.contrib.streaming.state.restore.RocksDBIncrementalRestoreOperation.restoreFromLocalState(RocksDBIncrementalRestoreOperation.java:218)
    at org.apache.flink.contrib.streaming.state.restore.RocksDBIncrementalRestoreOperation.restoreFromRemoteState(RocksDBIncrementalRestoreOperation.java:194)
    at org.apache.flink.contrib.streaming.state.restore.RocksDBIncrementalRestoreOperation.restoreWithoutRescaling(RocksDBIncrementalRestoreOperation.java:168)
    at org.apache.flink.contrib.streaming.state.restore.RocksDBIncrementalRestoreOperation.restore(RocksDBIncrementalRestoreOperation.java:154)
    at org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackendBuilder.build(RocksDBKeyedStateBackendBuilder.java:279)
    ... 15 more

Anyone has an idea of what's causing this?
UPDATE: After some tests, I noticed that this behavior depends on the state backend used. In this case I'm using RocksDBStateBackend with incremental checkpointing enabled. When I switched to FsStateBackend, the error disappeared.
Come to think of it, that would make sense since, from what I understand, checkpoints taken with incremental checkpointing enabled only record the changes compared to the previous completed checkpoint instead of the full job state, so it would not be possible to restore the job from this kind of checkpoint.
If that's correct, I think it would be useful to add a notice on the documentation (https://ci.apache.org/projects/flink/flink-docs-stable/ops/state/checkpoints.html#resuming-from-a-retained-checkpoint)


text:
Q: What are used to construct the isometric circle? I'm having confusion on what is being used to construct the isometric circle. My professor gave me 4 choices: Line, circle, ellipse, and semi-circle. I'm all new to isometric figures. Thanks for help

A: Ellipse.Because in isometric projection the visualization of circle converts to the shape of an ellipse.


text:
Q: Spring boot War file not running in websphere 8.5 I devoloped simple spring boot application with spring and generated WAR file deployed on Webspher but it is not working.
The same code working on Tomcat or other server wokring fine.If posible please provide the code github repository.I tried with all posible case but still i am facing the issues.
this is my Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.demo</groupId>
    <artifactId>ClientDemo4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ClientDemo4</name>
    <description>nSure Validation Service</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
        <!-- <start-class>com.demo</start-class> -->
    </properties>

    <dependencies>

            <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

<!--        <dependency> -->
<!--            <groupId>com.oracle</groupId> -->
<!--            <artifactId>ojdbc7</artifactId> -->
<!--            <version>12.1.0.2</version> -->
<!--        </dependency> -->

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
        </dependency>

        <!-- swagger -->
        <dependency>
            <groupId>com.mangofactory</groupId>
            <artifactId>swagger-springmvc</artifactId>
            <version>0.8.8</version>
        </dependency>

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.4.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <finalName>ClientDemo4</finalName>
    </build>

</project>

this is my main class
 @ComponentScan
    @SpringBootApplication(scanBasePackages = { "com.kgisl" })
    @OpenAPIDefinition(info = @Info(title = "Towing App", version = "v1", description = "Towing Application", license = @License(name = "MIT License", url = "https://github.com/bchen04/springboot-swagger-rest-api/blob/master/LICENSE"), contact = @Contact(url = "https://in.linkedin.com/company/kgislgss", name = "")))
    //@SpringBootApplication
    public class CommonValidationsApplication {

        public static void main(String[] args) {
            SpringApplication.run(CommonValidationsApplication.class, args);
        }

    }

This is servel class
public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(CommonValidationsApplication.class);
    }

}

This is my controller
@RestController
    public class BasicController {

        @GetMapping(value="/test")
        public String testMethod(String str)
        {
            return "You are input is:"+str;
        }

    }


text:
Q: Are IDs guaranteed to be unique across indices in Elasticsearch 6+? With mapping types being removed in Elasticsearch 6.0 I wonder if IDs of documents are guaranteed to be unique across indices?
Say I have three indices, all with a "parent" field that contains an ID. Do I need to include which index the ID belongs to or can I just search through all three indices when looking for a document with the given ID?

A: Explicit IDs
If you explicitly set the document ID when indexing, nothing prevents you from using the same ID twice for documents going in different indices.
Autogenerated IDs
If you don't set the ID when indexing, ES will generate one before storing the document.
According to the code, the ID is securely generated from a random number, the host MAC address and the current timestamp in ms. Additional work is done to ensure that the timestamp (and thus the ID sequence) increases monotonically.
To generate the same ID, when the JVM starts a specific random number has to be picked and the document ID must be generated in a specific moment with sub-millisecond precision. So while the chance exists, it's so small that I wouldn't care about it. (just like I wouldn't care about collisions when using an hash function to check file integrity)
Final note: as a code comment notes, the implementation is opaque and could change at any time, so what I wrote might not hold true in future versions.

A: IDs are not unique across indices.
If you want to refer to a document you need to know both the index name and the ID.


text:
Q: Python 3 installation I installed python3 to my my late 2014 iMac through brew.sh and my terminal is still defaulting to an older version of python unless I specifically prompt it with the command python3.  Is there any way I can fix this so that the terminal just automatically defaults to python3, without me having to type in python3 every single time?  I really need to run django, and the fact that my system is still defaulting to python 2.7 is really getting in the way.  Is there perhaps any way I can uninstall the older version of python?

A: Yes, you should set up virtual environments for python 2.7.13 and python 3.6. when you want to run python2, just activate the python 2 environments. Same for python3.
If you installed python using Anaconda, there are instructions in the Anaconda documentation for creating virtual environments.
If you did not use Anaconda, you can find instructions for creating virtual environments by googling on 'virtual environment python' and there are many hits.
I would advise against deleting any version of python. Macs come with a version of python installed that it uses and should not be removed.


text:
Q: How to identify whether the face is in the frames while detecting by ml kit? I'm doing an Android project that uses google ml kit to detect faces. I am having a problem is how to know when a face appears in the frame when FaceDetection works. I tried a few ways to display the results but it always stopped and did not return anything from the processor.
Is there any way to do that?


text:
Q: How to count all previous 'li' element width on hover? I have list and I'm trying to write jQuery code to count previous li width than I hover on some element. For example if I hover third element I need to get first + second elements width.

First

Second

Third

Fourth

Code at the moment:
jQuery('ul li').each(function() {
    jQuery(this).hover(function () {
        jQuery(this).prevAll().width();
    });
});

But I get only one previous element width. Can anyone help, please?

A: If you want sum of width:
jQuery('ul li').each(function() {
    jQuery(this).hover(function () {
        var prevWidth = 0
        jQuery(this).prevAll().each(function(){prevWidth  += $(this).width();});
        alert(prevWidth );
    });
});

A: jQuery('ul li').on('mouseenter', function () {
    var width = 0;
    jQuery(this).prevAll().each(function() {
        widht = width + $(this).width();
    });
    console.log(width);
});

A: Try this -
jQuery(this).prevAll().each(function(){
  $(this).width();
});


text:
Q: Extracting highlighted content in pdf automatically as images I have a pdf file in which some text and images are highlighted using highlight text(U) tool. Is there a way to automatically extract all the highlighted content as separate images and save it to a folder? I dont want readable text. I just want all the highlighted content as images. Thanks

A: You would need to use PDF library to iterate through all the Annotation objects and their properties to see which ones are using a highlight annotation.  Once you have found the highlight annotation you can then extract the position and size (bounding box) of the annotation.
Once you have a list of the annotation bounding boxes you will need to render the PDF file to an image format such as PNG/JPEG/TIFF so that you can extract / clip the rendered image of the annotation text you want.  You could use GDI+ or something like LibTIFF
There are various PDF libraries that could do this including
http://www.quickpdflibrary.com  (I consult for QuickPDF) or
http://www.itextpdf.com
Here is a C# function based on Quick PDF Library that does what you need.
    private void ExtractAnnots_Click(object sender, EventArgs e)
    {
        int dpi = 300;
        Rectangle r;
        List<Rectangle> annotList = new List<Rectangle>();

        QP.LoadFromFile("samplefile.pdf", "");

        for (int p = 1; p <= QP.PageCount(); p++)
        {
            QP.SelectPage(p);  // Select the current page.
            QP.SetOrigin(1);   // Set origin to top left.

            annotList.Clear();

            for (int i = 1; i <= QP.AnnotationCount(); i++)
            {
                if (QP.GetAnnotStrProperty(i, 101) == "Highlight")
                {
                    r = new Rectangle((int)(QP.GetAnnotDblProperty(i, 105) * dpi / 72.0),  // x
                                      (int)(QP.GetAnnotDblProperty(i, 106) * dpi / 72.0),  // y
                                      (int)(QP.GetAnnotDblProperty(i, 107) * dpi / 72.0),  // w
                                      (int)(QP.GetAnnotDblProperty(i, 108) * dpi / 72.0)); // h

                    annotList.Add(r); // Add the bounding box to the annotation list for this page.

                    string s = String.Format("page={0}: x={1} y={2} w={3} h={4}\n", p, r.X, r.Y, r.Width, r.Height);
                    OutputTxt.AppendText(s);
                }
            }

            // Now we have a list of annotations for the current page.
            // Delete the annotations from the PDF in memory so we don't render them.

            for (int i = QP.AnnotationCount(); i >= 0;  i--)
                QP.DeleteAnnotation(i);

            QP.RenderPageToFile(dpi, p, 0, "page.bmp");   // 300 dpi, 0=bmp
            Bitmap bmp = Image.FromFile("page.bmp") as Bitmap;

            for (int i=0;i<annotList.Count;i++)
            {
                Bitmap cropped = bmp.Clone(annotList[i], bmp.PixelFormat);

                string filename = String.Format("annot_p{0}_{1}.bmp", p, i+1);
                cropped.Save(filename);
            }

            bmp.Dispose();
        }

        QP.RemoveDocument(QP.SelectedDocument());
    }

A: Do you want each piece of text as a separate highlight or all the higlhights on a separate pane?


text:
Q: Indian claims finding new cube root formula Indian claims finding new cube root formula

It has eluded experts for centuries, but now an Indian, following in the footsteps of Aryabhatt, one of the earliest Indian mathematicians, claims to have worked out a simple formula to find any number's cube root.
Nirbhay Singh Nahar, a retired chemical engineer and an amateur mathematician, claims he has found a formula that will help students and applied engineers to work out the cube roots of any number in a short time.
"Give me any number - even, odd, decimals, a fraction...and I will give you the cube root using a simple calculator to just add and subtract within a minute and a half. We do have methods and patterns, but no formula at the moment. Even the tables give cube roots of 1 to 1,000, not of fractions or of numbers beyond 1,000, for which people have to use scientific calculators," Nahar, who retired as an engineer from Hindustan Salts Ltd at Sambhar (Rajasthan), said.

Is there any sense to this claim? Is it possible to have an algorithm that gives the cube root which uses only additions and subtractions?

A: Unless there is something lost in translation, the claims in the article are inconsistent...

Even the tables give cube roots of 1 to 1,000, not of fractions or of numbers beyond 1,000, for which people have to use scientific calculators," Nahar, said.
While Newton's formula arrives at an approximation, Nahar claims his formula leads to direct and perfect value, and no approximation.

So, he claims to be able to do this for any number, including fractions, and get the perfect value, not an approximation.... Great, so he is able to calculate all the digits of  $\sqrt[3]{2}$....
Judging by this, I have big doubts.
Of course it matters what he means by a formula; technically a formula of the type $x=10^{\frac{\log_{10} x}{3}}$ is simple enough and easy to use if one uses a logarithmic scale for the real numbers...

A: If by "formula", Nirbhay (the former engineer featured in the article) means "closed form formula", then the answer is obviously not; because the answers would all have to be rational, whereas e.g the cube root of 2 is not. However, if by "formula" Nirbhay means "algorithm which computes the digits in sequence, which converges on the answer and terminates in the case of integers and other terminating fractions which are perfect cubes", then the answer is yes, if you allow either simple multiplications, or perform it in base 2. (Of course, you can reduce multiplication to addition if you like, but beyond small integers or shifting numbers by place values, that feels like cheating.)
No innovation is required; it's a simple modification of the digit-by-digit algorithm for computing square roots. The intuition behind this algorithm is that at each point, you are trying to get better and better approximations to X by constructing rational numbers Y1, Y2, Y3, ... having more and more digits,
whose cubes approximate X from below. We chip away at the error between X and the cubes of these approximations by trying to "complete the cube". Each new digit of X that we consider allows us to try to chip away more of the difference between Yj ³ and X, by defining Yj+1 = Yj + δ for a suitable increment δ; we then determine the error involved in the new approximation by computing Yj+1³ = Yj ³ + 3δYj ² + 3δ²Yj  + δ³. The trick is how to do this with simple arithmetic operations; but it's not too difficult.
I demonstrate the algorithm in binary, because that's the base where it would be easiest in practise to compute the cube roots.
The generalization to arbitrary bases (e.g. decimal) is an exercise for the reader.
To simplify the presentation, we may assume without loss of generality that the number X whose cube-root we compute is less than 8. We may repeatedly divide by 8 until this is the case; when we have obtained the square root, simply multiply the answer the same number of times by 2. This is just observing that $\sqrt[3]{8^{-n} \cdot X\;} = 2^{-n} \cdot \sqrt[3]{X\;}$, and allows me to emphasize that the algorithm works just as well for fractions as for integers.
Because of how the algorithm works, it looks somewhat as though it's starting with a number in octal, and obtaining a root in binary (for square roots it looks like it produces a binary root from a number in quartal); but of course we can represent the base 8 "digits" by groups of three binary digits.
Let X = x0 + x1/81 + x2/82 + ... , where each xj ranges from 0 to 7. We compute binary digits yj representing Y = y0 + y1/21 + y2/22 + ...  such that Y3 = X, as follows.

*

*If x0 = 0, set y0 = 0; otherwise, set y0 = 1. Let R := x0 − y0.

*Set A = B = C = y0 .

*Set j = 1, and repeat the following until the desired number of digits is obtained (or until R = 0 and only if all the remaining digits xj , xj+1 , ... are also zero):

*

*Set D = 8R + xj , and consider the largest binary digit yj such that
$$ D \;\;\geqslant\;\; y_j^3 + 6Ay_j^2 + 12By_j + 8C.$$
Of course, we're working with binary digits; all the powers of yj are either zero or one. So what we're really testing is whether or not
$$ D \;\;\geqslant\;\; 1 + 2A + 4A + 4B + 8B + 8C,$$
where multiplication by 2, 4, and 8 can be realized by shifting integers one, two, or three places (tacking on zeros). If the inequality above holds, set yj = 1; otherwise set yj = 0.

*The integer A will actually be the number whose binary representation is the bit-sequence y0 y1 ... yj−1 in order; B is equal to A², and C is equal to A³. To maintain this invariant for the next iteration j, we compute new values A', B', and C' as updated values. For A, we define
$$ A' = 2A + y_j \;. $$
For B', we take advantage of the fact that we have B and A:
$$\begin{align*} B' &= (A')^2 = (2A + y_j)^2 = 4A^2 + 4Ay_j + y_j^2 \\&= 4B + 4Ay_j + y_j^2 \;. \end{align*}$$
Similarly, for C':
$$\begin{align*} C' &= (A')^3 = (2A + y_j)^2 = 8A^3 + 12A^2y_j + 6Ay_j^2 + y_j^3 \\&= 8C + 8By_j + 4By_j + 4Ay_j^2 + 2Ay_j^2 + y_j^3 \;. \end{align*}$$
Again, multiplications by zero, one, or powers of two are trivial inbinary representation. We then update A := A', B := B', and C := C'.

*We update R, which is meant to represent the error of C as an approximation to the integer formed by the first j digits (in octal) of X: we set $$ R' = \bigl(8R + x_j\bigr) - C' = D - C' \;,$$ and then set R := R'.

*If ever we obtain R = 0 and with all of the remaining digits of X equal to zero, we stop (with an exact solution).
In fact, it is not very difficult to modify this algorithm to obtain a procedure for extracting fourth roots, fifth roots, or nth roots for any constant n (though the number of parameters you have to carry around with you, and the sizes of the additions you have to carry out, will grow as you work harder and harder to avoid explicitly performing any multiplications).

A: Is it possible to have an algorithm that gives the cube root which uses only additions and subtractions?
Yes, if binary shifts are allowed. The algorithm is described in Henry S. Warren's
"Hacker's Delight" (11-2 Integer Cube Root), also on line: icbrt2.

A: To put things in context I'll first expose a straightforward method inspired by the classical evaluation of square roots (shortly : "if we know that $a^2 \le N <(a+1)^2$ then the next digit $d$ will have to verify  $(10a+d)^2 \le 10^2 N <(10a+d+1)^2$. This means that we want the largest digit $d$ such that $(20a+d)d\le 10^2(N-a^2)$") :
To evaluate the cubic root of $N$ let's suppose that
 $a^3 \le N <(a+1)^3$ then the next digit $d$ will have to verify  $(10a+d)^3 \le 10^3 N <(10a+d+1)^3$.
So that we want the largest digit $d$ such that $\left(30a(10a+d)+d^2\right)d \le 10^3(N-a^3)$.
To get a feeling of this method let's evaluate $\sqrt[3]{2}$ starting with $N=2,\ a=1$ :
$
\begin{array} {r|l}
2.000.000 & 1\\
\hline \\
-1.000.000 & 1.25\\
1.000.000 & \\
-728.000 & \\
272.000 & \\
-225.125 & \\
46.875 & \\
\end{array}
$
$a=1$ so that the first decimal must verify $(30(10+d)+d^2)d \le 1000$ that is $d=2$.
$a=12$ and the second decimal must verify $(360(120+d)+d^2)d \le 272000$ so that $d=5$.
(let's notice that this is 'nearly' $360\cdot 120\cdot d \le 272000$ so that $d=5$ or $d=6$ : we don't really need to try all the digits!)
I could have continued but observed that for $d=6$ the evaluation returned $272376$ so that the relative error on $d$ is $\epsilon_1 \approx \frac{376}{272376+360\cdot 6^2}\approx 0.001318$ giving $d\approx 5.9921$  and the solution $\sqrt[3]{2}\approx 1.259921$.

Now let's give a chance to Nirbhay Sngh Nahar's method exposed here.
Let's consider $N=2000$ then $x=1\cdot 10=10$
The NAHNO approximative formula is :
$$A= \frac 12\left[x+\sqrt{\frac{4N-x^3}{3x}}\right]= \frac 12\left[10+\sqrt{\frac{4\cdot 2000-10^3}{3\cdot 10}}\right]\approx 12.6376$$
Doesn't look very good... Let's give the formula a second chance by providing a much better value of $x=12.5$ then the formula returns $A=12.5992125$ not so far from $2^{\frac 13}= 12.59921049894873\cdots$ but $x=12.5$ is really near the solution so let's compare this method with Newton's iterations $\displaystyle x'=x-\frac{x^3-N}{3x^2}$
$x_0=12.5\to x_1=12.6\to x_2=12.599210548\cdots \to x_3=12.5992104989487318\cdots$
EDIT: I missed the 'Precise Value of Cube Root' using following formula :
$$P=A\frac{4N-A^3}{3N}$$ (I updated the picture and added this formula as well as the third Newton iteration)
The NAHNO approximative formula is better than the first Newton iteration but weaker than the second. The precise NAHNO formula is beaten only by the third Newton approximation as you may see in this picture (the curves are from top to bottom : first Newton iteration, Approximative NAHNO, second Newton iteration, Precise NAHNO, third Newton iteration ; the NAHNO curves are darker, the vertical scale is logarithmic and 'lower is better') :

The vertical axis shows $\ \log \left| \frac {A(N)}{N^{\frac 13}}-1\right|$ for $N$ in $(1000,50000)$. The vertical lines are values $N$ such that $2\sqrt[3]{N}$ is integer (when the initial estimation is nearly the solution).
So that, considered as approximate formulas, NAHNO formulas are rather good and could be made more precise with a better first approximation (especially for $x$ between $1$ and $2.5$ more values should be provided in the table). Avoiding extravagant claims could be an advantage too! :-)


text:
Q: delete folders with the same name as the parent folders recursively in bash? Some file copying went wrong in one of my machines and I'm wasting a ludicrous amount of space by having a copy of each folder inside of the parent with the same name, and I want to delete them all.
Example:
 /mnt/test/files/foo
 \_ /mnt/test/files/foo/file1 (etc)
 |__ /mnt/test/files/foo/foo
 \_ /mnt/test/files/foo/foo/file1 (etc)
 |_ /mnt/files/foo/foo2
  \_ /mnt/files/foo/foo2/file1 (etc)
 |_ /mnt/files/foo/foo2/foo2
  \_ /mnt/files/foo/foo2/foo2/file1 (etc)

So obviously I want to delete /mnt/files/foo/foo, /mnt/files/foo/foo2/foo2 and its contents (and so on) entirely and stop wasting space. What would be a good way to script it in bash?

A: If your find supports the -regex predicate, you can list the directories with:
find . -type d -regex '.*/\([^/]*\)/\1' -prune -print

to remove them, you can change -print to:
-exec rm -rf {} +

But be sure to check the list first so you don't delete any files you need.

A: Using non-GNU find (but still some implementation that supports -mindepth, such as find on BSD systems):
find top-dir -depth -mindepth 1 -type d -exec sh -c '
    for pathname do
        subdir=$pathname/${pathname##*/}
        if [ -d "$subdir" ]; then
            printf "Would remove directory %s\n" "$subdir"
            # rm -rfi "$subdir"
        fi
    done' sh {} +

This would do a depth-first traversal of the directory hierarchy rooted at top-dir.  For batches of found directory pathnames, a short shell script would be called.  In each iteration of the loop in the short shell script, the pathname for a subdirectory within the $pathname directory that has the same name as the directory itself is constructed.  If that subdirectory exists, it is reported (the deletion is currently commented out for safety).
The -depth option causes a depth-first traversal.  This is usually what you want when you delete directories with find as find would otherwise potentially try to enter directories that you have already deleted.
The -mindepth 1 option ensures that the top directory is not deleted, as it would be would you use . as the start search path.
Related:

*

*Understanding the -exec option of `find`


text:
Q: Grouping and aggregating twice I have a dataframe that looks like this:
City     State     Hour   Score     Percentage
DEN      CO        1      0         0
DEN      CO        1      0         0
DEN      CO        2      2         99
DEN      CO        3      0         0
NYC      NYC       1      0         0

I want it to look like this:
City     State     total_hours  total_scores  total_perct.   total_volume
DEN      CO        [1,2,3]      [0,2,0]       [0,99,0]       [2,1,1]
NYC      NYC       [1]          [0]           [0]            [1]

For total_hours I'm just doing a collect_set for the City and State for the total_scores I'm doing a collect_set for each specific hour and then collect all the scores for all hours. Ex: There are 2 scores for hour 1 Den CO, 0 and 0, I only take one of them and then hour 2 has 1, so it becomes [0,2]. Same thing with total_perct. For total_volume, I'm taking the count for each hour and I do collect_list for all hours of the same city and state.
This is basically what I'd like to achieve. If I do a groupBy like so:
df.groupBy("city", "state", "hour")
  .agg(collect_set("Hour").alias("total_hours"), collect_set("Score").alias("total_scores"),
       collect_set("Percentage").alias("total_perct."), count("hour").alias("total_volume"))

I'll get the following dataframe:
City     State     total_hours  total_scores  total_perct.   total_volume
DEN      CO        [1]          [0]           [0]            2
DEN      CO        [2]          [2]           [99]           1
DEN      CO        [3]          [0]           [0]            1
NYC      NYC       [1]          [0]           [0]            1

I don't understand what to do from here. How can I get what I have now and achieve the final result? I'm using PySpark.

A: Spark < 2.4
Need to use the udf but really slow in this case. :(
import itertools
from pyspark.sql.functions import max, count, col, collect_list, collect_set, udf
from pyspark.sql.types import ArrayType, IntegerType

@udf
def flatten(col):
    return list(itertools.chain.from_iterable(col))

df.groupBy('City', 'State', 'Hour') \
  .agg(collect_set(col('Score')).alias('Score'), collect_set(col('Percentage')).alias('Percentage'), count(col('Hour')).alias('total_volume')) \
  .orderBy('City', 'State', 'Hour') \
  .groupBy('City', 'State') \
  .agg(collect_list(col('Hour')).alias('total_hours'), collect_list(col('Score')).alias('total_scores'), collect_list(col('Percentage')).alias('total_perct'), collect_list(col('total_volume')).alias('total_volume')) \
  .select('City', 'State', 'total_hours', flatten(col('total_scores')), flatten(col('total_perct')), 'total_volume') \
  .show(10, False)

Spark 2.4+
Ok, this is worked with collect_set and collect_list.
from pyspark.sql.functions import max, count, col, collect_list, flatten

df.groupBy('City', 'State', 'Hour') \
  .agg(collect_set(col('Score')).alias('Score'), collect_set(col('Percentage')).alias('Percentage'), count(col('Hour')).alias('total_volume')) \
  .orderBy('City', 'State', 'Hour') \
  .groupBy('City', 'State') \
  .agg(collect_list(col('Hour')).alias('total_hours'), flatten(collect_list(col('Score'))).alias('total_scores'), flatten(collect_list(col('Percentage'))).alias('total_perct.'), collect_list(col('total_volume')).alias('total_volume')) \
  .show(10, False)

+----+-----+-----------+------------+------------+------------+
|City|State|total_hours|total_scores|total_perct.|total_volume|
+----+-----+-----------+------------+------------+------------+
|NYC |NYC  |[1]        |[0]         |[0]         |[1]         |
|DEN |CO   |[1, 2, 3]  |[0, 2, 0]   |[0, 99, 0]  |[2, 1, 1]   |
+----+-----+-----------+------------+------------+------------+

If you did not put the orderBy during this step, then the order of the result list will be mixed.

A: Another way using a window to count appearances of Hour , then filter 1 index (idx) based on the partition, and then groupby + collect_list
import pyspark.sql.functions as F
from pyspark.sql.window import Window

w = Window.partitionBy("City","State","Hour")
l = ['Hour','Score', 'Percentage', 'Volume']

(df.withColumn("idx",F.monotonically_increasing_id()).select("*",
            F.count("Hour").over(w).alias("Volume"),F.max("idx").over(w).alias("Indx"))
            .filter(F.col("idx")==F.col("Indx")).orderBy("idx").groupBy("City","State")
            .agg(*[F.collect_list(i).alias(f"total_{i}") for i in l])).show()

Output:
+----+-----+----------+-----------+----------------+------------+
|City|State|total_Hour|total_Score|total_Percentage|total_Volume|
+----+-----+----------+-----------+----------------+------------+
| NYC|  NYC|       [1]|        [0]|             [0]|         [1]|
| DEN|   CO| [1, 2, 3]|  [0, 2, 0]|      [0, 99, 0]|   [2, 1, 1]|
+----+-----+----------+-----------+----------------+------------+


text:
Q: My TextView array prints only the first element in the TextView array and not all elements My TextView array prints only the first element in the TextView array and not all elements, new to android. Please help me out.
Guys there was a typo, I had forgotten to show the increment of i in the code below. I have actually used increment of i, but yet only the first textview appears. Please check it out now and help me.
    Iterator<String> i1 = processesOccupyingHugeMemory.iterator();

    TextView[] text = new TextView[processesOccupyingHugeMemory.size()];
    int i=0;
    while(i1.hasNext())
    {
        text[i] = new TextView(this);
        text[i].setText(i1.next());
        text[i].setAllCaps(true);
        text[i].setId(i);
        text[i].setLayoutParams(params);
        myLinearLayout.addView(text[i]);
        i++;
    }
}

}
XML Code
<LinearLayout
    android:id="@+id/LinearLayout1"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

A: You have to increment i , you are always use 0 for the variable i

A: You forgot incrementing i in while loop.
    Iterator<String> i1 = processesOccupyingHugeMemory.iterator();

    TextView[] text = new TextView[processesOccupyingHugeMemory.size()];
    int i=0;
    while(i1.hasNext())
    {
        text[i] = new TextView(this);
        text[i].setText(i1.next());
        text[i].setAllCaps(true);
        text[i].setId(i);
        text[i].setLayoutParams(params);
        myLinearLayout.addView(text[i]);
        i++;
    }

Other than that:
Make sure you have used width WRAP_CONTENT in params, you use for textview.
And if you want each textview in new line, then you will need to set orientation vertical for linear layout in xml.
<LinearLayout
    android:id="@+id/LinearLayout1"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

A: You are setting the same id to the textview each time. Increment the id value in the loop.