text:
Q: write a simple benchmarking tool in java I want to write a simple benchmarking tool in java, that will spin up x threads and hit a url y times in total.
The actual task part of it will make a web request to a url, and post a XML file.
So what I want to do is, spin off 50 threads and keep hitting the url until I have made 10K requests.
Can someone explain how to do this, I believe using the Executor Service is the way to go.
Some things to consider:

*

*Once a thread is finished, I'm guessing it will immediately run another task correct?

*I need the thread to return as I have to keep track of success/failures, where should this be stored (it has to be thread-safe).

A: Yes, ExecutorService is a perfect choice for this task:
ExecutorService exec = Executors.newFixedThreadPool(50);

Start measuring time and simply submit 10K tasks to it:
for(int i = 0; i < 10000; ++i) {
  exec(new SubmitToUrlTask());
}

Consider using the same instance of (stateless or thread-safe) SubmitToUrlTask rather than creating new one in each iteration.
At the end you must wait for the executor to finish:
exec.shutdown();
if(!exec.awaitTermination(1, TimeUnit.MINUTE)) {
  throw new IllegalStateException("Waiting for too long, captain!");
}

Stop measuring the time now. awaitTermination() blocks until all tasks have finished, but not longer than given time (1 mminute in the example).

Once a thread is finished, I'm guessing it will immediately run another task correct?

Yes, ExecutorService is a bunch of threads and a queue of tasks. If a thread does not have anything to do, it takes first task from the queue.

I need the thread to return as I have to keep track of success/failures, where should this be stored (it has to be thread-safe).

You can use Callable<Boolean> and Future<Boolean> to track results. Also if you are using only a single instance of SubmitToUrlTask, it can have two variables of AtomicInteger type, tracking both successes and failures. This is much simpler if you don't need to track individual results.
That being said, have you considered using JMeter that has all these functionalities + much more out of the box? There is also ab console utility.

A: Here is the annotated source code which outlines a strategy you can use:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class LoadGen {
    /**
     * Hits the given url for nRequests times on nUsers threads.
     *
     * @return LoadGen.Result object with status of the test
     */
    public static Result generateLoad(final String url,
        int nUsers, int nRequests) throws InterruptedException {
        // A thread pool with one thread per simulated user
        ExecutorService threadPool = Executors.newFixedThreadPool(nUsers);

        // A latch awaited on by the user threads before the test is started
        final CountDownLatch startSignal = new CountDownLatch(1);

        // A latch awaited on by the main thread for all user threads
        // to complete the test
        final CountDownLatch doneSignal = new CountDownLatch(nUsers);

        // The Result object for this test run
        final Result result = new Result(nRequests);

        // Submit one Runnable per simulated user
        for (int i = 0; i < nUsers; i++) {
            threadPool.submit(new Runnable() {
                public void run() {
                    try {
                        // the Runnable awaits for the test to start
                        startSignal.await();

                        runSimulatedUser(url, result);

                        // indicate that this thread has completed
                        doneSignal.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        // Start all simulated user threads
        startSignal.countDown();

        // Wait for all simulated user threads to complete the test
        doneSignal.await();

        // Dispose all threads
        threadPool.shutdownNow();
        return result;
    }

    private static void runSimulatedUser(String url, Result result) {
        // run repeatedly ..
        while (true) {
            try {
                // hitting the URL, marking success and failure
                // until nRequests requests are made in total
                makeRequest(url);
                if (! result.success()) {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (! result.failure()) {
                    break;
                }
            }
        }
    }

    private static void makeRequest(String url) {
        // TODO: post the XML document to the URL etc
        System.out.println("Making request");
    }

    public static class Result {
        private final AtomicInteger nSuccess = new AtomicInteger();
        private final AtomicInteger nFailure = new AtomicInteger();
        private final AtomicInteger nTotal;

        public Result(int nTotal) {
            this.nTotal = new AtomicInteger(nTotal);
        }

        boolean success() {
            nSuccess.incrementAndGet();
            return nTotal.decrementAndGet() > 1;
        }

        boolean failure() {
            nFailure.incrementAndGet();
            return nTotal.decrementAndGet() > 1;
        }

        int getSuccessCount() {
            return nSuccess.get();
        }

        int getFailureCount() {
            return nFailure.get();
        }
    }

    public static void main(String[] args) throws Exception {
        // generate 10 requests on 2 threads
        LoadGen.generateLoad("http://myurl.com", 2, 10);
    }
}


text:
Q: Cant set relative path to python module in linux ubuntu Hy... lots of questions about relative paths, but none in ubuntu. I think ubuntu is my problem, so please help.. I tried every path combination and have no more ideas what to try to make it work.
Program is inporting one module into main window.
This is both..
import sys

sys.path.append("\home\zoran\Documents\Moduli")

import brojeviModul

def vrati(a, b, c):
    global br
    br = 10
    a += br
    b += br
    c += br
    return min(a , b, c)

def main():

    prviBroj = int(input("Unesite prvi broj: "))
    drugiBroj = int(input("Unesite drugi broj: "))
    treciBroj = int(input("Unesite treci broj: "))

    genPrva = brojeviModul.generirajBroj(prviBroj)
    genDruga = brojeviModul.generirajBroj(drugiBroj)
    genTreca = brojeviModul.generirajBroj(treciBroj)

    vratiPrvi = vratiZbroj(genPrva)
    vratiDrugi = vratiZbroj(genDruga)
    vratiTreci = vratiZbroj(genTreca)

    minimalnaVrijednost = vrati(vratiPrvi, vratiDrugi, vratiTreci)

    print("Najmanja vracena vrijednostje{}.".format(minimalnaVrijednost))

if __name__ == "__main__":
main()

And second...
def main():
    global broj

    broj = 100

    veciOdSto = int(input("Unesite troznamenkasti broj veći od 100:"))

    def generirajBroj(veciOdSto):
        if veciOdSto < 101 or veciOdSto > 999:
            print("Broj ne valja")
            return 150
        else:
            import random
            genBroj = random.randint(broj, veciOdSto)
            print("Generiran je slučajni broj: {}".format(genBroj))
            return genBroj

    def vratiZbroj(veciOdSto):
        if veciOdSto > 100 and veciOdSto < 999:
            prvaZnamenka = veciOdSto % 10
            drugaZnamenka = (veciOdSto // 10) % 10
            trecaZnamenka = veciOdSto //100
            return prvaZnamenka + drugaZnamenka + trecaZnamenka

if __name__ == "__main__":
    main()

And error:
 Traceback (most recent call last):
 File "/home/zoran/Desktop/glavni.py", line 34, in <module>
   main()
  File "/home/zoran/Desktop/glavni.py", line 21, in main
  genPrva = brojeviModul.generirajBroj(prviBroj)
AttributeError: module 'brojeviModul' has no attribute 'generirajBroj'

I even added this main class to my module because I find it in one sample..

A: The functions in the second module are defined in your main function, not in the module. Reindent your module, like so:
def main():
    global broj
    broj = 100
    veciOdSto = int(input("Unesite troznamenkasti broj veći od 100:"))

def generirajBroj(veciOdSto):
    if veciOdSto < 101 or veciOdSto > 999:
        print("Broj ne valja")
        return 150
    else:
        import random
        genBroj = random.randint(broj, veciOdSto)
        print("Generiran je slučajni broj: {}".format(genBroj))
        return genBroj

def vratiZbroj(veciOdSto):
    if veciOdSto > 100 and veciOdSto < 999:
        prvaZnamenka = veciOdSto % 10
        drugaZnamenka = (veciOdSto // 10) % 10
        trecaZnamenka = veciOdSto //100
        return prvaZnamenka + drugaZnamenka + trecaZnamenka

if __name__ == "__main__":
    main()

Also, paths are using forward slashes in unix.

A: Add your scripts to one of the directory within PYTHONPATH ENV variable or add the corresponding directory to $PYTHONPATH .
Ref - https://leemendelowitz.github.io/blog/how-does-python-find-packages.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serving static files via Nginx proxying HTTPS to gunicorn django in docker-compose I'm deploying my Django/Nginx/Gunicorn webapp to EC2 instance using docker-compose. EC2 instance has static IP where mywebapp.com / www.mywebapp.com points to, and I've completed the certbot verification (site works on port 80 over HTTP) but now trying to get working over SSL.
Right now, HTTP (including loading static files) is working for me, and HTTPS dynamic content (from Django) is working, but static files are not. I think my nginx configuration is wonky.
I tried copying the location /static/ block to the SSL server context in the nginx conf file, but that caused SSL to stop working altogether, not just static files over SSL.
Here's the final docker-compose.yml:
services:
  certbot:
    entrypoint: /bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h &
      wait $${!}; done;'
    image: certbot/certbot
    volumes:
      - /home/ec2-user/certbot/conf:/etc/letsencrypt:rw
      - /home/ec2-user/certbot/www:/var/www/certbot:rw
  nginx:
    command: /bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s reload; done
      & nginx -g "daemon off;"'
    depends_on:
      - web
    image: xxxxxxxx.dkr.ecr.us-east-1.amazonaws.com/xxxxxxxx:latest
    ports:
      - 80:80/tcp
      - 443:443/tcp
    volumes:
      - /home/ec2-user/certbot/conf:/etc/letsencrypt:rw
      - static_volume:/usr/src/app/public:rw
      - /home/ec2-user/certbot/www:/var/www/certbot:rw
  web:
    entrypoint: gunicorn mywebapp.wsgi:application --bind 0.0.0.0:7000"
    image: xxxxxxxx.dkr.ecr.us-east-1.amazonaws.com/xxxxxxxx:latest
    volumes:
      - static_volume:/usr/src/app/public:rw
version: '3.0'
volumes:
  static_volume: {}

nginx.prod.conf:
upstream mywebapp {
    # web is the name of the service in the docker-compose.yml
    # 7000 is the port that gunicorn listens on
    server web:7000;
}

server {
    listen 80;
    server_name mywebapp;
    location / {
        proxy_pass       http://mywebapp;
        proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
        proxy_set_header Host               $host;
        proxy_redirect   off;
    }
    location /static/ {
        alias /usr/src/app/public/;
    }
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
}

server {
    # https://github.com/wmnnd/nginx-certbot/blob/master/data/nginx/app.conf
    listen 443    ssl;
    server_name   mywebapp;
    server_tokens off;

    location / {
        proxy_pass          http://mywebapp;
        proxy_set_header    Host                $http_host;
        proxy_set_header    X-Real-IP           $remote_addr;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
    }

    # generated with help of certbot
    ssl_certificate     /etc/letsencrypt/live/mywebapp.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mywebapp.com/privkey.pem;
    include             /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam         /etc/letsencrypt/ssl-dhparams.pem;
}

and finally the nginx service Dockerfile:
FROM nginx:1.15.12-alpine

RUN rm /etc/nginx/conf.d/default.conf
COPY ./nginx.prod.conf /etc/nginx/conf.d

I simply build, push to ECR on local machine then docker-compose pull and run with docker-compose up -d on the EC2 instance.
The error I see in docker-compose logs is:
nginx_1    | 2019/05/09 02:30:34 [error] 8#8: *1 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: mywebapp, request: "GET / HTTP/1.1", upstream: "http://192.168.111.3:7000/", host: "ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com"

And I'm not sure what's going wrong. I'm trying to get both dynamic content (gunicorn) and static content (from: /usr/src/app/public) served correctly under HTTPS using the certs I've generated and verified.
Anyone know what I might be doing wrong?

A: Check your configuration file with nginx -T - are you seeing the correct configuration? Is your build process pulling in the correct conf?
It's helpful to just debug this on the remote machine - docker-compose exec nginx sh to get inside and tweak the conf from there and nginx -s reload. This will speed up your iteration cycles debugging an SSL issue.


text:
Q: How to auto fill cell C with a formula that only returns the date from cell a? Currently my google spreadsheet has cell B & A which contains my timestamp and temperature value which I send from my Arduino. I am unable to display it out on my google chart because it only takes in number range filter or date range filter, so I have to convert the timestamp to only a time as the date is not important.
I created a formula in cell C which is =int(A2) which returns me the date, and in cell D =C2-A2 which returns me the actual time that I wanted to use in my google chart. But when my arduino sends a new timestamp and temp value, the cells C and D do not auto update and convert for me.
Is there anything I can do to make cell 'C' and 'D' auto calculate and do the formula when my Arduino sends new data?

A: You can use array formulae for this.
In A2 you can put
=ArrayFormula(C2:C-A2:A)

If you want non filled cells not to display 0 you can
=ArrayFormula(IF(LEN(C2:C), C2:C-A2:A, ""))


text:
Q: Same IP Addresses while capturing Packets under Linux (C Program) I am receiving network packets by writing a code in c. So far I am receiving packets correctly but the only problem I'm facing is that I'm having same IP addresses for Ethernet, TCP and UDP. i'm not having any trouble while receiving via tcpdump.
Ethernet source of my system is: b0:10:41:fc:d7:2f
And IP address of my interface is: 192.168.10.145
These are received packets:

162 >>> Received packet with 66 bytes:     Ethernet src:
  b0:10:41:fc:d7:2f dst: b0:10:41:fc:d7:2f type: 0x800  IP version: 4
  ihl: 5 ttl: 64 protocol: 6 src: 192.168.10.145 dst 192.168.10.145     TCP
  src: 46888 dst: 80 seq: 3048209837 win: 4508 ACK          000000: b728 0050
  b5af fdad 0e1d 21a1 8010 119c     .(.P......!.....        0x0010: e258 0000
  0101 080a 5a05 1f81 0595 4669
163 >>> Received packet with 66 bytes:  Ethernet src:
  b0:10:41:fc:d7:2f dst: b0:10:41:fc:d7:2f type: 0x800  IP version: 4
  ihl: 5 ttl: 64 protocol: 6 src: 192.168.10.145 dst 192.168.10.145     TCP
  src: 38836 dst: 443 seq: 1969857171 win: 341 ACK          000000: 97b4 01bb
  7569 a293 0473 15bc 8010 0155     ....ui...s.....U        0x0010: 11f1 0000
  0101 080a 4011 29b5 45f5 c4da
164 >>> Received packet with 1024 bytes:    Ethernet src:
  0:1a:a0:3f:d6:fc dst: 0:1a:a0:3f:d6:fc type: 0x800    IP version: 4 ihl:
  5 ttl: 64 protocol: 6 src: 110.93.233.24 dst 110.93.233.24    TCP src:
  80 dst: 46888 seq: 236790177 win: 595 ACK         000000: 0050 b728 0e1d
  21a1 b5af fdad 8010 0253  .P.(..!........S        0x0010: 6e5f 0000 0101
  080a 0595 46a1 5a05 199a  n_........F.Z...        0x0020: f107 eb73 1b82
  1492 c88f e84c 101a 9416  ...s.......L....        0x0030: 9a27 900f 2020
  1985 836f 79d5 8a26 15fa  .'..  ...oy..&..

And this is my code:
layer2: {
struct ethhdr *eth = (struct ethhdr*) data;
printf("\tEthernet src: %s dst: %s type: %#04x\n",
    ether_ntoa((const struct ether_addr*) eth->h_source),
    ether_ntoa((const struct ether_addr*) eth->h_dest),
    ntohs(eth->h_proto)
);
protocol = ntohs(eth->h_proto);
next_hdr = (char *) (eth + 1);}

layer3: switch (protocol) {
    case ETH_P_IP: {
        /* Parse IP protocol */
        struct iphdr *ip = (struct iphdr*) next_hdr;
        char buf[32];
        printf("\tIP version: %u ihl: %u ttl: %u protocol: %u src: %s dst %s\n",
            ip->version,
            ip->ihl,
            ip->ttl,
            ip->protocol,
            inet_ntop(AF_INET, &ip->saddr, buf, sizeof(buf)),
            inet_ntop(AF_INET, &ip->daddr, buf, sizeof(buf))
        );

What am I doing wrong ?

A: You're using the same buf to hold both IP addresses:
inet_ntop(AF_INET, &ip->saddr, buf, sizeof(buf)),
inet_ntop(AF_INET, &ip->daddr, buf, sizeof(buf))

Because you're using the same buffer, and both calls to inet_ntop() are done before the call to printf(), the last call to inet_ntop() will overwrite the results from the first call.

A: If following the first Advise, wouldn't work. Maybe you need a Buffer for Ethernet too ?
E.g.

struct ethhdr *eth = (struct ethhdr *)Buffer;

and get the Data with

eth->h_dest[0] , eth->h_dest[1] , eth->h_dest[2] , eth->h_dest[3] , eth->h_dest[4] , >eth->h_dest[5]

?


text:
Q: JSON support for companion object I have a class that looks somewhat like that
import java.time.OffsetDateTime

import spray.json._
import DefaultJsonProtocol._

sealed trait Person {

  def firstName: String

  def country: String

  def lastName: String

  def salary: Option[BigDecimal]
}

case class InternalPerson(
                     firstName: String,
                     country: String,
                     lastName: Option[BigDecimal],
                     salary: Option[BigDecimal]
                    ) extends Person

object Person {
  def fromName(name: Name, country: String, salary: Option[BigDecimal]): Person = {
    InternalPerson(
              firstName = name.firstName,
              lastName = name.lastName,
              country = country,
              salary = salary
              )
  }
}

object PersonJsonProtocol extends DefaultJsonProtocol {
  implicit val personFormat = jsonFormat4(Person.apply)
}

I am just trying to add a json support to my class. whenever I import the protocol and spray.json._ from another classes I get:
Note: implicit value personFormat is not applicable here because it comes after the application point and it lacks an explicit result type
and
value apply is not a member of object of Person
any idea on how to have Json support for companion objects that extends a trait in scala?

A: If you defined your implicit in terms of the case class, InternalPerson, json formatting should be enabled:  implicit val personFormat = jsonFormat4(InternalPerson)
And you won't have to define an apply() method, which you will have to do in either the Person trait or any implementation thereof otherwise.

A: You can use play framework to deal with Json.
https://www.playframework.com/documentation/2.6.x/ScalaJson
I think it's very easy and intuitive.
For primitive types it's enough to use Json.format[ClassName]. If you have something more complex you can write your own writes and reads. I know that this question is about spray, but another solution can be good.
So for example for InternalPerson it'll be:
import play.api.libs.json.Json

case class InternalPerson {
  firstName: String,
  country: String,
  lastName: Option[BigDecimal],
  salary: Option[BigDecimal]
)

object InternalPerson {
  implicit val format = Json.format[InternalPerson]
}

In case that you want to do it with Trait it will be the same. Sometimes you need to write explicitly reads and writes.


text:
Q: No static method canDrawOverlays I've noticed someone who is using my app reported a crash which logged by the Google Developer Console:
java.lang.NoSuchMethodError: No static method canDrawOverlays(Landroid/content/Context;)Z in class Landroid/provider/Settings; or its super classes (declaration of 'android.provider.Settings' appears in /system/framework/framework.jar)
    at com.pack.MainActivity.checkDrawOverlayPermission(MainActivity.java:311)
    at com.pack.MainActivity.onCreate(MainActivity.java:127)
    at android.app.Activity.performCreate(Activity.java:6033)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5268)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)

The canDrawOverlays is an API 23+ method and I Use it like that:
 /** code to post/handler request for permission */
    public final static int REQUEST_CODE = 100; /*(see edit II)*/

    @SuppressLint("NewApi")
    public void checkDrawOverlayPermission() {
        /** check if we already  have permission to draw over other apps */
        if (!Settings.canDrawOverlays(this)) {
            /** if not construct intent to request permission */
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName()));
            /** request permission via start activity for result */
            startActivityForResult(intent, REQUEST_CODE);
        }
    }

And I have this in my MainActivity:
checkDrawOverlayPermission();

The device which crashed using Android 5.1
HOw I can make sure my app will work on ANdroid 5.1? (API 22 and below) who don't have this method which available from API 23 and up?

A: Check the current API of the device which runs your code. If it >= 23, you can use the code
if(Build.VERSION.SDK_INT >= 23) {
     // if (!Settings.canDrawOverlays(this)) {
     //
} else {
     // another similar method that supports device have API < 23
}

A: Use this
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

       if (!Settings.canDrawOverlays(this)) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + getPackageName()));
        /** request permission via start activity for result */
        startActivityForResult(intent, REQUEST_CODE);
    }

    } else {
     }

A: For all methods that appeared in newer SDK versions you should use the following pattern:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  // code for Marshmallow (SDK 23) and newer versions
} else {
  // fallback for older versions
}


text:
Q: Minimal condition checking for.function undefined in Javascript Sorry if this question has been asked in some different way. Basically I have to write this:
 (window.name ="xyz" && ahdframeset == ahdtop && typeof
  window.parent.ahdframe.frames == "object" && typeof window.parent.ahdframe.frames
 [window.name] == "undefined" ))

I have to mainly check if window.parent.ahdframe.frames[window.name].somefunction is defined or not ? Instead of verifying for object and undefined, can I use something like
 (window.name ="xyz" && ahdframeset == ahdtop && typeof
  window.parent.ahdframe.frames[window.name].somefunction == "undefined" ))

and not worry about javascript errors when window.parent.ahdframe is null or undefined

A: You can't just "not worry about JavaScript errors".  You have to test the properties to see whether they're empty.
(window.name ="xyz" && ahdframeset == ahdtop &&
  window.parent && window.parent.ahdframe && window.parent.ahdframe.frames && window.parent.ahdframe.frames[window.name] &&
  typeof window.parent.ahdframe.frames[window.name].somefunction == "undefined" ))


text:
Q: Compiling Cairo-dock errors on GTK dependency I've Redhat 7.2 running Cinnamon, and hate the docks provided, how come I can't resize the area a widgit is allocated?  All apps are jammed into half the dock.
Drives me to compile cairo-dock from source as it isn't an ibm redhat blessed package.
cmake .. -DCMAKE_INSTALL_PREFIX=/usr
...
-- checking for module 'wayland-client>=1.0.0'
--   package 'wayland-client>=1.0.0' not found
-- checking for module 'gtk+-3.0>=3.4.0'
--   package 'gtk+-3.0>=3.4.0' not found

so I find gtk version is 3.14.13-16.el7 using yum list installed "gtk*"
I downloaded gtk 3.4.4 and compiled it and follow the INSTALL provided, sudo make install, which completes with no errors
rerunning cmake gives me the same error, so I'm wondering if I had to remove 3.14?  I'm not really sure how best to proceed and thought it best to get some advice.  I'm not really in the mood to break things.  Thanks for your time and consideration.

A: Calvin, I'm also IBMer and installed RHEL7.2 from IBM's image.
I could successfully download the sources and install Cairo Docker and respective plugins.
I followed the instructions in this page here:
Glx-Dock - Generic:Compilation
First, install all dependencies below from official IBM repository.
I used the same package names for the Fedora dependencies and some may NOT exist for RHEL. Therefore, some plugins won't be available by fetching dependencies from official repository only - but the Cairo Docker will work.
sudo yum install cmake make pkgconfig gcc gcc-c++ gettext glib2-devel\
cairo-devel librsvg2-devel dbus-glib-devel libxml2-devel libXrender-devel\
mesa-libGL-devel mesa-libGLU-devel pango-devel libXxf86vm-devel\
libXtst-devel libXrandr-devel libX11-devel libcurl-devel gtk3-devel\
vte3-devel lm_sensors-devel libxklavier-devel libexif-devel\
libetpan-devel gnome-menus-devel alsa-lib-devel libical-devel\
upower-devel libzeitgeist-devel

Untar the packages and build with the commands described there except that you need to force the lib64 in both main and plugin builds with:
cmake .. -DCMAKE_INSTALL_PREFIX=/usr -DFORCE_LIB64=yes


text:
Q: biztalk xslt - mapping I 'm a newbie on bts - just started yesterday, having a "tutor" giving me a a few concepts - after the first mapping  using bts tools (shipped on visual studio).
now the guy who is tutoring ask me to do that manually... i write my own xslt file.
since i never work with xslt befor i'm a little bit lost.
i had an "incomming" xml with a namespace wich i want to modify to an output xml, with a diferent namespace.
after that i had to pass directly values from one xml xml to another and to other values i had to sum or multiply .
incoming xml namespace = http://NWMessaging.CustomerOrder
outcoming xml namespace = http://FKMessaging.SupplierPO/
i have no ideia out to get values from 1st xml to 2nd one.
any tips to start?
<?xml version="1.0" encoding="utf-8"?>

A: If you create a map in Visual Studio's BizTalk Mapper, it can generate the XSLT for you, which is perhaps the best way to begin to understand how XSLT works. This allows you to see what the namespaces will be set to, what linking nodes from your input to your output schema look like, etc.
In Visual Studio:

*

*go to the Solution Explorer

*right-click on your map file ([something].btm)

*select Validate Map

*after VS compiles and runs the validation, the Output pane will show you the location of the "output XSLT" file

Unless you are going to do really complex mappings, you likely won't need to know XSLT all that well. If you do need to do that, then you can always pick up a book.


text:
Q: How to avoid temporary object creation (and deletion) when constructing with initializer list? Suppose I have two template classes A and B:
// Non-modifiable template class.
template<class T>
class A{
private:
    T* ptr;
    int size;
public:
    A( int const inputSize ):
        ptr{ new T[ inputSize ] }, size{ inputSize }
    {}
};

// Modifiable template class.
template<class T>
class B{
private:
    A<T> a_obj;
    int idx;
public:
    B( int const inputSize ):
        a_obj{ A<T>{ inputSize } }, idx{ 0 } //temporary object creation?
    {}
};

B has a member variable with type A which needs to be constructed during the construction of B. Is there a way to avoid temporary construction of object with type A when constructing B (if it happens at all)? Also please suppose we cannot modify A template class.
What I'm trying to get at is a similar functionality we see with emplace_back() compared to push_back() in vectors: objects are constructed at the place and not twice.

A: You can (and should) pass the A constructor arguments directly without code implying a temporary, i.e. instead of...
a_obj{ A<T>{ inputSize } }, idx{ 0 } //temporary object creation?

...use...
a_obj{ inputSize }, idx{ 0 }

(Whether the former actually creates a temporary is up to the optimiser).


text:
Q: What level of permissions do you need to access the Workflow Settings of a library? I am trying to access the Workflow Settings of a document library, but I get Access Denied. I am wondering what level of permissions should I have in order to go to these settings?

A: I just tested this on SharePoint 2010 and for OOTB permission levels, it looks like you would need the Design permission level at a minimum to access the Workflow Settings in a list/library. You can also have the Manage Hierarchy permission level, but this would give you a lot more access than to just the Workflow Settings.


text:
Q: Compute Engine Managed VM takes too long to reboot Friends. I have a Google App engine website that uses one module on Google Compute Engine. It uses the Python standard runtimes with the following configuration:
runtime: python27
threadsafe: true
vm: true

manual_scaling:
  instances: 1

Machine type: f1-micro (1 vCPU, 0.6 GB memory)

health_check:
  enable_health_check: True
  check_interval_sec: 5
  timeout_sec: 2
  unhealthy_threshold: 2
  healthy_threshold: 2
  restart_threshold: 4

The problem is that periodically this instance becomes "unhealthy" (it respondes with 503 http code) and stays like that for around 10 to 15 minutes. This happens even when there's no traffic/access to the app. Shouldn't this instance reboot after 4 failed health checks? Does it take 15 minutes to reboot?
Thanks in advance.


text:
Q: using powershell inside batch file to add floating numbers from text file i have a text file logging timestamps from ffprobe on video durations of some video files,  which that text file looks like this:
14.068700
5.043011
84.071967
5.043011
104.058600
5.043011
134.055234
5.056000 ....

I am trying to add these up,  since batch files do not allow for floating numbers i chose to use powershell.   here is my following code:
set total=0
for /f "tokens=*" %%x in (timestamps.txt) do (
    set item=%%x
    echo !item!
    for /f  "delims=." %%i in ('powershell %total% + %item%') DO SET total=%%i
    echo %total%
)

but again it seems cause it is a floating number i am unable to do something like
 SET /a total=%total% + %total%

so that i can not add that as a variable in this line:
 powershell %total% + %item%

I have tried every combo i can think of with no luck, lots of searches and nothing comes back.
any idea how to do this or is there a better way to add up all these in pure batch ?

A: a pure Powershell solution would have been much simpler, but seeing as you require batch-file with powershell:
@echo off
setlocal enabledelayedexpansion & set nums=
for /f "usebackq delims=" %%x in ("timestamps.txt") do set nums=!nums!%%x+
for /f "delims=" %%i in ('powershell %nums:~0,-1%') do set "total=%%i"
echo Total: %total%

We just append all the numbers with the operator + to a variable, then pass that variable to powershell and get the result.
Note! delayedexpansion is needed because we are setting
or by utilizing powershell to do all the work and simply assign the result to the variable:
@echo off
for /f "delims=" %%i in ('"powershell -command (Get-Content -Path "timestamps.txt" ^| Measure-Object -Sum^).Sum"') do set "total=%%i"
echo Total: %total%

A: so this is what i came up with,  not as elegant as it possibly can be BUT it is working.  Wish it was a bit quicker  but PowerShell slows things down a bit but definitely worth it!
its crazy to think when doing dos they never thought of using floating  numbers, lol
anyways here is code:
set seconds=0
set item=0
for /f "tokens=*" %%t in (%filename%_copy_two%fileextension%) do (
        set item=%%t
        for /f %%i in ('powershell !item!+!seconds!') do (set seconds=%%i)
    )

for /f %%i in ('powershell -NoP "[Math]::Round(!seconds!/ 60,2)"')  do (set minutes=%%i)

set HH=00
for /f "tokens=1 delims=." %%r in ('echo %minutes%') do set min=%%r
for /f "tokens=2 delims=." %%p in ('echo %minutes%') do set sec=%%p

IF %sec% GTR 60 (
    set /a newSec=!sec!-60
    if !newSec! lss 10 set newSec=0!newSec!
    set /a newMin=1 + !min!
    if !newMin! lss 10 set newMin=0!newMin!

) else (
    set /a newMin=!min!
    set /a newSec=!sec!
)

IF %newMin% LSS 60 (
    if !newMin! lss 10 set newMin=0!newMin!
    set MM=!newMin!
    if !newSec! lss 10 set newSec=0!newSec!
    set SS=!newSec!
    GOTO playlistTotal
)

IF %newMin% GEQ 60 IF %newMin% LSS 120 (
    set /a MM=!newMin!-60
    if !MM! lss 10 set MM=0!MM!
    set /a HH=01
    set SS=!newSec!
    GOTO playlistTotal
)

IF %newMin% GEQ 120 IF %newMin% LSS 180 (
    set /a MM=!newMin!-120
    if !MM! lss 10 set MM=0!MM!
    set /a HH=02
    set SS=!newSec!
    GOTO playlistTotal
)

IF %newMin% GEQ 120 IF %newMin% LSS 240 (
    set /a MM=!newMin!-180
    if !MM! lss 10 set MM=0!MM!
    set /a HH=03
    set SS=!newSec!
    GOTO playlistTotal
)

IF !newMin! EQU 240 (
    set /a MM=!newMin!-240
    if !MM! lss 10 set MM=0!MM!
    set /a HH=04
    set SS=!newSec!
    GOTO playlistTotal
)

IF %newMin% Gtr 240 (
    ECHO  We do not suggest a single playlist over 4 hours.
    echo  Please Go back edit your list to be shorter.
    ECHO  And just append to it
    del %filename%_copy%fileextension%
    del %filename%_copy_two%fileextension%
    GOTO editPlaylist
)

:playlistTotal
del %filename%_copy%fileextension%
del %filename%_copy_two%fileextension%
echo.
Echo Playlist a total duration of = !HH!:!MM!:!SS!
echo.

IF !newMin! EQU 240 (
    set /a MM=!newMin!-240
    if !MM! lss 10 set MM=0!MM!
    set /a HH=04
    set SS=!newSec!
    GOTO playlistTotal
)

IF %newMin% Gtr 240 (
    ECHO  We do not suggest a single playlist over 4 hours.
    echo  Please Go back edit your list to be shorter.
    ECHO  And just append to it
    del %filename%_copy%fileextension%
    del %filename%_copy_two%fileextension%
    GOTO editPlaylist
)

:playlistTotal
del %filename%_copy%fileextension%
del %filename%_copy_two%fileextension%
echo.
Echo Playlist has a total duration of= !HH!:!MM!:!SS!
echo.

I hope this helps someone out! kind of stinks i cant ask a question for 6 months for this question considering there is NOT solution that I can find that met me OP
And once again I posted my solution after a question which I try to do every time, have a great day!
EDIT:  thanks to @Gerhard
I have changed to this, but leaving  the code here in case someone needs for a similar issue in a different way.
for /f "delims=" %%i in ('"powershell -command (Get-Content -Path "%filename%_copy_two%fileextension%" ^| Measure-Object -Sum^).Sum"') do set "seconds=%%i"
for /f %%i in ('powershell -NoP "[Math]::Round(!seconds!/ 60,2)"')  do (set minutes=%%i)

Then keeping the same as is till someone posts a better solution.

A: You can achieve this in a very simple and pure Batch file that run much faster than any PS:
@echo off
setlocal

set /A factor=1000000, total=0
for /F "tokens=1,2 delims=." %%a in (timestamps.txt) do set /A total+=%%a*factor+1%%b-factor

echo %total:~0,-6%.%total:~-6%

Of course, this solution is so simple because it assumes that all input numbers have 6 decimals! If this is not the case, then the code should be modified accordingly...


text:
Q: Google App Engine Flex Container Deployment Issues I am trying to deploy my Go 1.14 microservices application on to Google's Flexible environment. I read that there are issues with finding GOROOT, and how it is unable to obtain the correct dependencies.
I wanted to use the flexible environment because I needed to do port forwarding. Since my domain name was used to run the actual application, I wanted port 8081 to run my microservices.
I followed the instruction from this link:

https://blog.cubieserver.de/2019/go-modules-with-app-engine-flexible/

I tried option 3.
This is my gitlab-ci.yaml configurations file.
# .gitlab-ci.yaml
stages:
  - build
  - deploy

build_server:
  stage: build
  image: golang:1.14
  script:
    - go mod vendor
    - go install farmcycle.us/user/farmcycle
  artifacts:
    paths:
      - vendor/

deploy_app_engine:
  stage: deploy
  image: google/cloud-sdk:270.0.0
  script:
    - echo $SERVICE_ACCOUNT > /tmp/$CI_PIPELINE_ID.json
    - gcloud auth activate-service-account --key-file /tmp/$CI_PIPELINE_ID.json
    - gcloud --quiet --project $PROJECT_ID app deploy app.yaml

  after_script:
  - rm /tmp/$CI_PIPELINE_ID.json

This my app.yaml configuration file
runtime: go
env: flex

network:
  forwarded_ports:
    - 8081/tcp

When I deployed this using the Git CI pipeline. Build stage passes, but the Deploy stage failed.
Running with gitlab-runner 13.4.1 (e95f89a0)
  on docker-auto-scale 72989761
Preparing the "docker+machine" executor
Preparing environment
00:03
Getting source from Git repository
00:04
Downloading artifacts
00:02
Executing "step_script" stage of the job script
00:03
$ echo $SERVICE_ACCOUNT > /tmp/$CI_PIPELINE_ID.json
$ gcloud auth activate-service-account --key-file /tmp/$CI_PIPELINE_ID.json
Activated service account credentials for: [farmcycle-hk1996@appspot.gserviceaccount.com]
$ gcloud --quiet --project $PROJECT_ID app deploy app.yaml
ERROR: (gcloud.app.deploy) Staging command [/usr/lib/google-cloud-sdk/platform/google_appengine/go-app-stager /builds/JLiu1272/farmcycle-backend/app.yaml /builds/JLiu1272/farmcycle-backend /tmp/tmprH6xQd/tmpSIeACq] failed with return code [1].
------------------------------------ STDOUT ------------------------------------
------------------------------------ STDERR ------------------------------------
2020/10/10 20:48:27 staging for go1.11
2020/10/10 20:48:27 Staging Flex app: failed analyzing /builds/JLiu1272/farmcycle-backend: cannot find package "farmcycle.us/user/farmcycle/api" in any of:
    ($GOROOT not set)
    /root/go/src/farmcycle.us/user/farmcycle/api (from $GOPATH)
GOPATH: /root/go
--------------------------------------------------------------------------------
Running after_script
00:01
Running after script...
$ rm /tmp/$CI_PIPELINE_ID.json
Cleaning up file based variables
00:01
ERROR: Job failed: exit code 1

This was the error. Honestly I am not really sure what this error is and how to fix it.

A: Surprisingly, even using the latest Go runtime, runtime: go1.15, go modules appear to not be used. See golang-docker.
However, Flex builds your app into a container regardless of runtime and so, in this case, it may be better to use a custom runtime and build your own Dockerfile?
runtime: custom
env: flex

Then you get to use e.g. Go 1.15 and go modules (without vendoring) and whatever else you'd like. For a simple main.go that uses modules e.g.:
FROM golang:1.15 as build

ARG PROJECT="flex"
WORKDIR /${PROJECT}

COPY go.mod .
RUN go mod download

COPY main.go .

RUN GOOS=linux \
    go build -a -installsuffix cgo \
    -o /bin/server \
    .

FROM gcr.io/distroless/base-debian10

COPY --from=build /bin/server /

USER 999

ENV PORT=8080
EXPOSE ${PORT}

ENTRYPOINT ["/server"]

This ought to be possible with Google's recently announced support for buildpacks but I've not tried it.


text:
Q: Prevent pandas read_excel() to divide all percent values by one hundred? I was loading an xlsx file with pandas (1.0.5) and noticed that values with a percent sign (e.g. 0.3%) are automatically divided by 100.
I know how to load that column as a string but don't understand why it would divide the value by 100. Ideally, I'd like to have only the float value without the percent sign. For now I stripped the % and cast the columns, but there has to be a better way. This does not happen when loading the data as CSV.
df = pd.read_excel("testfile.xlsx")

input.xlsx :
|alpha|beta|
|:-|:-|
|0.3%|0.34%|

resulting data frame :
|alpha|beta|
|:-|:-|
|0.003|0.0034|


text:
Q: jQuery, when performing AJAX loads, how to prevent the site from scroll down & staying put I'm building a web app that loads content with $.ajax and then injects the content in a contentCol...
problem is every time this happens it scroll the browser down. Is there a global way to prevent this and just keep the scrollbar where the user was initially before calling the AJAX?
Thx

A: ok here's what worked... Not loving this bec it prevent the user from REFRESHing ajax content. I'd love it if you can one up me with something better and more elegant...
$('a').live('click', function() {
    // Page Jump Prevention - Does the clicked on Hash differ from the currently loaded hash, if not return false
    if (window.location.hash.split('#')[1] == this.href.split('#')[1]) {
        //alert('Dude we already loaded this!')
        return false;
    }
});


text:
Q: Is a space allowed between #! and the first character of the path? In the language i work with, "#" does not start a comment.
So i have to find a way to pass the first shebang line without yielding an error.
A trick could do the job provided that some space is/are allowed after the heading #!, i mean writting
#! /usr/path/to/the/bin/to/call/to/run/me

instead of
#!/usr/path/to/the/bin/to/call/to/run/me

I have no linux installation available to do the test myself.
Would this shebang work?

A: The shebang (#!) is a 16-bit kernel-interpreted magic "number" (actually 0x23 0x21).  Thereafter, the kernel program loader (following the exec-family call) attempts to execute the remainder of the line to handle the remainder of the containing file's content.  Many, if not most modern kernels disregard preceding spaces to the command that follows the shebang.  As such, #! /bin/bash, #! /usr/bin/perl, and the like, should be acceptable with most modern kernels.  That said, a shebang with no following space is far more commonly seen.
Note, and FYI, the executable and linkable format (ELF) magic number is 32-bits: 0x7F 0x45 0x4C 0x46 or [DEL] [E] [L] [F].


text:
Q: for what values of $x$ does $\sum_{n=0}^\infty \sin(x/2^n)$ converge? I can't seem to use the root or ratio test here because of the ugly function inside of $\sin(x)$. Have tried rewriting the function using the sin taylor series but again just end up with a long mess!

A: Hint: $|\sin(t)| \le |t|$ for real $t$.

A: For all real $x$, There is some $N_0$ such that $|2^{-N_0} x| < 1.
Then
$$
\left| \sum_{N_0}^\infty \sin (2^{-n}x)  \right| \leq \left| \sum_{N_0}^\infty 2^{-N_0} x 2^{-(n-N_0)}  \right| \leq 2
$$
So the infinite part of the series converges.  The remaining terms, with $n<N_0$, are a finite series, so of course that converges as well.
So $\sum_{N_0}^\infty \sin (2^{-n}x)  $ converges absolutely for all real $x$.


text:
Q: Eigenvalues of three given linear operators
Determine the eigenvalues of each linear transformation. Give brief explanations.
(Hint: you do not need to find a matrix representing the linear transformation.)
(a) $\mathcal P : \Bbb R^3 \rightarrow \Bbb R^3$ given by projection onto the plane $3x-y-2z=0$
(b) $\mathcal Q : M(2,2) \rightarrow M(2,2)$ given by $Q(A)=A^T$ (the transpose of A.)
(c) $\mathcal R : \mathcal P_2 \rightarrow \mathcal P_2$ given by $\mathcal R(p)=(x-2)p'(x)$
(where $\mathcal P_2 =$ the vector space of polynomials in $x$ of degree $\le 2.$)

This is a question I found in a practice exam which I was attempting. I was absolutely at odds with what to do, especially given the hint. Once I finished the exam, I came back to the question and found the matrix for the first question, which is
$$
\frac{1}{14}\begin{bmatrix}
5 & 3 & 6 \\
3 & 13 & -2 \\
6 & -2 & 10 \\
\end{bmatrix}
$$
and the eigenvalues for that are $1,1,0$ with corresponding eigenvectors $(\frac{2}{3},0,1),(\frac{1}{3},1,0)$ and $(\frac{-3}{2},\frac{1}{2},1)$. I did this with the hope that I would be able to work backwards and see how they actually wanted me to find the answer so I could do it for the next parts. Given the hint and the very low mark value of this question on the paper, it can't be very complicated, but I'm stuck.
Please give me some hints as to how to proceed and tackle this question.

A: i think the question is asking for the exercise of "intuitive" perceptions. e.g. a projection clearly has eigen-values $0,1$ (for vectors perpendicular to or (resp) lying in the invariant subspace). symmetric and anti-symmetric matrices show that the transpose has eigenvalues $\pm 1$


text:
Q: Perl : Trying to deference an array after sorting it I am currently writing a perl script where I have a reference to an array (students) of references. After adding the  hash references to the array. Now I add the references to the array of students and then ask the user how to sort them. This is where it gets confusing. I do not know how to deference the sorted array. Using dumper I can get the sorted array but in a unorganized output. How can I deference the array of hash references after sorting?
#!bin/usr/perl
use strict;
use warnings;
use Data::Dumper;
use 5.010;
#reference to a var $r = \$var; Deferencing $$r
#reference to an array $r = \@var ; Deferencing @$r
#referenc to  a hash $r = \%var ; deferencing %$r

my $filename = $ARGV[0];
my $students = [];

open ( INPUT_FILE , '<', "$filename" ) or die "Could not open to read \n ";

sub readLines{

    while(my $currentLine = <INPUT_FILE>){
        chomp($currentLine);
        my @myLine = split(/\s+/,$currentLine);
        my %temphash = (
        name => "$myLine[0]",
        age  => "$myLine[1]",
        GPA  => "$myLine[2]",
        MA   => "$myLine[3]"
        );
        pushToStudents(\%temphash);
    }

}

sub pushToStudents{
    my $data = shift;
    push $students ,$data;
}

sub printData{

    my $COMMAND = shift;

    if($COMMAND eq "sort up"){
        my @sortup = sort{ $a->{name} cmp $b->{name} } @$students;
        print Dumper @sortup;

    }elsif($COMMAND eq "sort down"){
        my @sortdown = sort{ $b->{name} cmp $a->{name} } @$students;
        print Dumper @sortdown;
        //find a way to deference so to make a more organize user friendly read.

    }else{
        print "\n quit";
    }

}

readLines();
#Output in random, the ordering of each users data is random
printf"please choose display order : ";
my $response = <STDIN>;
chomp $response;
printData($response);

A: The problem here is that you're expected Dumper to provide an organised output. It doesn't. It dumps a data structure to make debugging easier. The key problem will be that hashes are explicitly unordered data structures - they're key-value mappings, they don't produce any output order.
With reference to perldata:

Note that just because a hash is initialized in that order doesn't mean that it comes out in that order.

And specifically the keys function:

Hash entries are returned in an apparently random order. The actual random order is specific to a given hash; the exact same series of operations on two hashes may result in a different order for each hash.

There is a whole section in perlsec which explains this in more detail, but suffice to say - hashes are random order, which means whilst you're sorting your students by name, the key value pairs for each student isn't sorted.
I would suggest instead of:
my @sortdown = sort{ $b->{name} cmp $a->{name} } @$students;
print Dumper @sortdown;

You'd be better off with using a slice:
my @field_order = qw ( name age GPA MA );

foreach my $student ( sort { $b -> {name} cmp $a -> {name} } @$students ) {
   print @{$student}{@field_order}, "\n";
}

Arrays (@field_order) are explicitly ordered, so you will always print your student fields in the same sequence. (Haven't fully tested for your example I'm afraid, because I don't have your source data, but this approach works with a sample data snippet).
If you do need to print the keys as well, then you may need a foreach loop instead:
foreach my $field ( @field_order ) {
    print "$field => ", $student->{$field},"\n";
}

Or perhaps the more terse:
print "$_ => ", $student -> {$_},"\n" for @field_order;

I'm not sure I like that as much though, but that's perhaps a matter of taste.

A: The essence of your mistake is to assume that hashes will have a specific ordering. As @Sobrique explains, that assumption is wrong.
I assume you are trying to learn Perl, and therefore, some guidance on the basics will be useful:

#!bin/usr/perl

Your shebang line is wrong: On Windows, or if you run your script with perl script.pl, it will not matter, but you want to make sure the interpreter that is specified in that line uses an absolute path.
Also, you may not always want to use the perl interpreter that came with the system, in which case #!/usr/bin/env perl maybe helpful for one-off scripts.

use strict;
use warnings;
use Data::Dumper;
use 5.010;

I tend to prefer version constraints before pragmata (except in the case of utf8). Data::Dumper is a debugging aid, not something you use for human readable reports.

my $filename = $ARGV[0];

You should check if you were indeed given an argument on the command line as in:
@ARGV or die "Need filename\n";
my $filename = $ARGV[0];

open ( INPUT_FILE , '<', "$filename" ) or die "Could not open to read \n ";

File handles such as INPUT_FILE are called bareword filehandles. These have package scope. Instead, use lexical filehandles whose scope you can restrict to the smallest appropriate block.
There is no need to interpolate $filename in the third argument to open.
Always include the name of the file and the error message when dying from an error in open. Surrounding the filename with ' ' helps you identify any otherwise hard to detect characters that might be causing the problem (e.g. a newline or a space).
open my $input_fh, '<', $filename
    or die "Could not open '$filename' for reading: $!";

sub readLines{

This is reading into an array you defined in global scope. What if you want to use the same subroutine to read records from two different files into two separate arrays? readLines should receive a filename as an argument, and return an arrayref as its output (see below).

   while(my $currentLine = <INPUT_FILE>){
        chomp($currentLine);

In most cases, you want all trailing whitespace removed, not just the line terminator.

       my @myLine = split(/\s+/,$currentLine);

split on /\s+/ is different than split ' '. In most cases, the latter is infinitely more useful. Read about the differences in perldoc -f split.

       my %temphash = (
        name => "$myLine[0]",
        age  => "$myLine[1]",
        GPA  => "$myLine[2]",
        MA   => "$myLine[3]"
        );

Again with the useless interpolation. There is no need to interpolate those values into fresh strings (except maybe in the case where they might be objects which overloaded the stringification, but, in this case, you know they are just plain strings.

       pushToStudents(\%temphash);

No need for the extra pushToStudents subroutine in this case, unless this is a stub for a method that will later be able to load the data to a database or something. Even in that case, it be better to provide a callback to the function.

sub pushToStudents{
           my $data = shift;
           push $students ,$data;
       }

You are pushing data to a global variable. A program where there can only ever be a single array of student records is not useful.

sub printData{
    my $COMMAND = shift;
    if($COMMAND eq "sort up"){

Don't do this. Every subroutine should have one clear purpose.
Here is a revised version of your program.
#!/usr/bin/env perl

use 5.010;
use strict;
use warnings;

use Carp qw( croak );

run(\@ARGV);

sub run {
    my $argv = $_[0];
    @$argv
        or die "Need name of student records file\n";

    open my $input_fh, '<', $argv->[0]
        or croak "Cannot open '$argv->[0]' for reading: $!";

    print_records(
        read_student_records($input_fh),
        prompt_sort_order(),
    );

    return;
}

sub read_student_records {
    my $fh = shift;

    my @records;

    while (my $line = <$fh>) {
        last unless $line =~ /\S/;
        my @fields = split ' ', $line;
        push @records, {
            name => $fields[0],
            age => $fields[1],
            gpa => $fields[2],
            ma => $fields[3],
        };
    }

    return \@records;
}

sub print_records {
    my $records = shift;
    my $sorter = shift;

    if ($sorter) {
        $records = [ sort $sorter @$records ];
    }

    say "@{ $_ }{ qw( age name gpa ma )}" for @$records;

    return;
}

sub prompt_sort_order {
    my @sorters = (
        [ "Input order",  undef ],
        [ "by name in ascending order",  sub { $a->{name} cmp $b->{name} } ],
        [ "by name in descending order", sub { $b->{name} cmp $a->{name} } ],
        [ "by GPA in ascending order",   sub { $a->{gpa} <=> $b->{gpa} } ],
        [ "by GPA in descending order",  sub { $b->{gpa} <=> $a->{gpa} } ],
    );

    while (1) {
        print "Please choose the order in which you want to print the records\n";
        print "[ $_ ] $sorters[$_ - 1][0]\n" for 1 .. @sorters;
        printf "\n\t(%s)\n", join('/', 1 .. @sorters);

        my ($response) = (<STDIN> =~ /\A \s*? ([1-9][0-9]*?) \s+ \z/x);
        if (
            $response and
            ($response >= 1) and
            ($response <= @sorters)
        ) {
            return $sorters[ $response - 1][1];
        }
    }

    # should not be reached
    return;
}


text:
Q: how can I read the specific block of a file Suppose I have a file /foo/bar. stat /foo/bar can show the inode information of it -- something like this:
  Size: 9511068     Blocks: 18584      IO Block: 4096   regular file
Device: ca01h/51713d    Inode: 793183      Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2015-01-29 13:58:23.000000000 +0000
Modify: 2015-01-24 11:48:47.000000000 +0000
Change: 2015-01-29 14:01:09.177162834 +0000

But it doesn't show the addresses of each block of contents. How can I read the specific, say, the third block of the file /foo/bar? Is there any such command?

A: You can use debugfs command. Using it open the filesystem you want to inspect and there is a command blocks which shows you all block adresses used by a file. I am not sure if it works with filesystems other than ext family.


text:
Q: The argument type 'Future' can't be assigned to the parameter type 'Future?' The Error:
lib/pages/view_page.dart:90:21: Error: The argument type 'Future' can't be assigned to the parameter type 'Future?'
because 'dynamic' is nullable and 'Object' isn't.

*

*'Future' is from 'dart:async'.

*'Object' is from 'dart:core'.
future: generateEmployeeList(),

The codes which have a specific error
@override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text('Syncfusion flutter datagrid'),
            ),
            body: FutureBuilder<Object> (
                future: generateEmployeeList(),
                builder: (context, data) {
                  return data.hasData
                      ? SfDataGrid(
                          source: employeeDataSource,
                          columns: _columns,
                          columnWidthMode: ColumnWidthMode.fill)
                      : Center(
                          child: CircularProgressIndicator(
                          strokeWidth: 2,
                          value: 0.8,
                        ));
                }));
      }

Future codes:
        Future<dynamic> generateEmployeeList() async {
            // Give your PHP URL. It may be online URL o local host URL.
            // Follow the steps provided in the below KB to configure the mysql using
            // XAMPP and get the local host php link,
            ///
            var url = "my_url";
            final response = await http.get(Uri.parse(url));
            var list = json.decode(response.body);

            // Convert the JSON to List collection.
            List<Employee> _employees =
                await list.map<Employee>((json) => Employee.fromJson(json)).toList();
            employeeDataSource = EmployeeDataSource(_employees);
            return _employees;
          }

Question: How can I assign The argument type 'Future' to the parameter type 'Future?'

A: The error is because you have FutureBuilder<Object>, but generateEmployeeList() has a return type of Future<dynamic>. Type dynamic can be null, but Object can't be null.
Since you are returning a List<Employee> value from the future, solve the problem like this:
body: FutureBuilder<List<Employee>>

And then:
Future<List<Employee>> generateEmployeeList() async {
  ...
  return Future.value(_employees);
}


text:
Q: Count along with date condition for each id i have data in 2 Sql tables/Pandas DF
1st containing the user id and discount date like below

the other table contains all purchase events

How can i get the user id wise status giving counts before the discount and after the discount.

A: You can join the tables and use conditional aggregation:
SELECT p.userid,
       SUM(p.purchase_date < d.discount_date) Before_discount,
       SUM(p.purchase_date >= d.discount_date) After_discount,
       COUNT(*) total_purchases
FROM purchases p INNER JOIN discounts d
ON d.userid = p.userid
GROUP BY p.userid

Change the table names purchases and discounts to the actual ones.


text:
Q: Cleaning Dataframe Using Columns Conditions - Python/Spyder I have a dataframe as following:
Year-Week  Ticket   Policy
2022-25    12502    COMPLIED
2022-26    12502    NOT COMPLIED
2022-20    12502    COMPLIED
2022-15    12502    COMPLIED
2022-26    12471    COMPLIED
2022-24    12409    COMPLIED
2022-26    12409    NOT COMPLIED
2022-25    12406    COMPLIED

There are cases that are duplicated and that is okay since they are from different year-week, however, how could I standarized that the same ticket have the same policy. E.g: If a ticket in a week has "NOT COMPLIED", the policy should be the same for that ticket no matter the week, so, should be something like this:
Output Sample
Year-Week  Ticket   Policy
2022-25    12502    NOT COMPLIED
2022-26    12502    NOT COMPLIED
2022-20    12502    NOT COMPLIED
2022-15    12502    NOT COMPLIED
2022-26    12471    COMPLIED
2022-24    12409    NOT COMPLIED
2022-26    12409    NOT COMPLIED
2022-25    12406    COMPLIED

I was thinking this should be done by using an if function in python.

A: You can do it in this way:
df = pd.DataFrame({"Year-Week": ['2022-25', '2022-26'], "Ticket": [12502, 12502], "Policy": ["COMPLIED", "NOT COMPLIED"]})
policies = df[['Ticket', 'Policy']].groupby('Ticket').max()
new_values = df[['Ticket']].merge(policies, on='Ticket')
df.update(new_values)

Please, note that you can use code above only for this case, where "NO COMPLIED" is longer than "COMPLIED". In other cases you should use another aggregation functions.


text:
Q: How can I get user (self) rated movies/series data from IMDB (mostly python)? I want to retrieve reviews that I have given to movies/series on IMDB app/website under my account.
Does IMDB expose any such API?
I tried accessing the URL mentioned in the screenshot. But looks like I need the token?
How to get IMDB token?
I went through https://github.com/alberanid/imdbpy but looks like there are no such API's to get user reviewed data.

Can anyone please guide me in the right direction?

A: I guess that's what you are looking for:
http://www.omdbapi.com
IMDB api.

A: I tried a different way altogether and it worked,
import requests
import browsercookie
import bs4
url = 'https://www.imdb.com/user/ur<user_id>/ratings?ref_=nv_usr_rt_4'
cj = browsercookie.chrome()
res = requests.get(url, cookies=cj)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, "html.parser")


text:
Q: Search in mongo db by date I have a mongo db collection, where is row createdDate, which contains datetime value in format Y-m-d H:i:s. Is there any way to search through collection via method find() where I know only the date (Y-m-d)? I've tried few solutions, but nothing worked for me... Here is one of them. Thanks for any help!
$currentDate = '2017-05-16';
$dateQuery =  ['createdDate' => $currentDate];

foreach ($this->collection->find($dateQuery) as $key => $log) {
    .....
}

A: Finally solved by myself:
    $dateRegex = new \MongoRegex(('/' . $currentDate . '/i'));

    foreach ($this->collection->find(['createdDate' => $dateRegex]) as $key => $log) {
        ....
    }


text:
Q: how to initialize spring application context when eclipse jetty server startup We have a web project based on JAX-WS, I have some code which involves spring, and I need to initialize the spring context within server startup. However it doesn't make sense.
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class JettyServer2 {
    public static void main(String[] args) throws Exception {
        Server server = new Server(9000);
        ServletContextHandler context = new ServletContextHandler(server, "/*");
        context.addServlet(servlet, "/*");
        context.setErrorHandler(new ErrorHandler());
        try {
            server.start();
            //System.setProperty("spring.profiles.active", "test");
            //try to initialize spring context here
            server.join();
        } finally {
            server.destroy();
        }
    }
}

I tried to initialize system property which I commented out in above code, however, both the system property and the spring context initialization don't work. I'm guessing they are running in different jvm and current thread is dead after server.destroy().
Could anyone help to figure out why spring context initialization doesn't work, and let me know how to make it on the right way?
The initialization code is just like:
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);

Thanks in advance.


text:
Q: Why doesn't x' = a.x + b.u, y = c . x + d.u hold in this state-space model? I have noted that sometimes state variables may change (thanks Thomas's help  :)), due to the Mathematica's internal automatic transformation from a descriptor state-space model to a standard state-space model.
I think that the relationship x' = a.x + b.u, y = c . x + d.u should hold in any state-space.
However, this relationship doesn't hold in the following state-space model.
Instead, I found that
x' = a.x - b.u, y = - c . x + d.u
hold in my state-space model. Why does this happen?
By the way, I believe that I used the right state variable in my code.

code:
Remove["Global`*"] // Quiet;

m = {{Subscript[\[ScriptM], 1], 0, 0}, {0, Subscript[\[ScriptM], 2],
    0}, {0, 0, Subscript[\[ScriptM], 3]}};
k = Array[Subscript[\[ScriptK], #1, #2] &, {3, 3}];
c = Array[Subscript[\[ScriptC], #1, #2] &, {3, 3}];
bs = {{1, -1, 0}, {0, 1, -1}, {0, 0, 1}};
\[CapitalLambda] = {{1, 1, 1}}\[Transpose];

uf = {uf1[t], uf2[t], uf3[t]};
ue = {ue1[t], ue2[t], ue3[t]};
pN = {pN1[t], pN2[t], pN3[t]};
mN = {mN1[t], mN2[t], mN3[t]};
u = Flatten@{uf, ue, pN, mN};
lhs = Flatten[
   m.{x1''[t], x2''[t], x3''[t]} + c.{x1'[t], x2'[t], x3'[t]} +
    k.{x1[t], x2[t], x3[t]}];
rhs = Flatten[+m.ue + bs.uf + m.\[CapitalLambda] pN];
eq = lhs - rhs == 0 // Thread;

y = {x1''[t], x2''[t], x3''[t]} + ue + mN;
z = {x3'[t], x3[t], x2'[t], x2[t], x1'[t], x1[t]};

ss = StateSpaceModel[eq, z, u, y, t,
   SystemsModelLabels -> {ToString /@ u, ToString /@ y,
     ToString /@ z}];
{AA, BB, CC, DD} = Normal[ss];
ddxEQ = Flatten[Solve[eq, {x3''[t], x2''[t], x1''[t]}]][[All, 2]];
ddxSS = (AA.z - BB.u)[[1 ;; -1 ;; 2]];

ddxEQ - ddxSS // Simplify
Reverse[ddxEQ] + ue + mN - Flatten[-CC.z + DD.u] // Simplify

A: This is the same issue I had pointed out in an earlier post.
In general, the variables you give in the second argument to StateSpaceModel are not the states. In this case they are $\left\{-\text{x3}'(t),-\text{x3}(t),-\text{x2}'(t),-\text{x2}(t),-\text{x1}'(t),-\text{x1}(t)\right\}$. You can determine that from the computations below.
states = Array[v, 6];
ssPrelim = StateSpaceModel[eq, {x3'[t], x3[t], x2'[t], x2[t], x1'[t], x1[t]}, u,
  Join[vars = {x1[t], x2[t], x3[t], x1'[t], x2'[t], x3'[t]}, y], t];
z = states /. Solve[Thread[vars == Normal[ssPrelim][[3, 1 ;;Length@vars]].states], states][[1]]
ss = StateSpaceModel[SystemsModelDelete[ssPrelim, None, Range[6]],
  SystemsModelLabels -> {ToString /@ u, ToString /@ y, ToString /@ z}];

And then the verification works.
{AA, BB, CC, DD} = Normal[ss];
ddxEQ = Flatten[Solve[eq, {x3''[t], x2''[t], x1''[t]}]][[All, 2]];
ddxSS = -(AA.z + BB.u)[[1 ;; -1 ;; 2]];
ddxEQ - ddxSS // Simplify
Reverse[ddxEQ] + ue + mN - Flatten[CC.z + DD.u] // Simplify

{0, 0, 0}
{0, 0, 0}

Update
In v12.1, the states will be the specified variables. Earlier, when possible, this worked for standard state-space systems. Now it also does so for descriptor systems.
ss = StateSpaceModel[eq, z, u, y, t,
     SystemsModelLabels -> {ToString /@ u, ToString /@ y, ToString /@ z}];
{AA, BB, CC, DD} = Normal[ss];
ddxEQ = Flatten[Solve[eq, {x3''[t], x2''[t], x1''[t]}]][[All, 2]];
ddxSS = (AA.z + BB.u)[[1 ;; -1 ;; 2]];
ddxEQ - ddxSS // Simplify
Reverse[ddxEQ] + ue + mN - Flatten[CC.z + DD.u] // Simplify

{0, 0, 0}
{0, 0, 0}

The above calculation now works because the resulting states in fact the specified variables z.
states = Array[v, 6];
ssPrelim = StateSpaceModel[eq, z, u,
           Join[vars = {x1[t], x2[t], x3[t], x1'[t], x2'[t], x3'[t]}, y], t];
states /. Solve[Thread[vars == Normal[ssPrelim][[3, 1 ;;Length@vars]].states], states][[1]]
z


text:
Q: How to convert an Uploaded JPEG Image to unit8 type in Google Colab/Python? I am trying to convert an uploaded image(JPEG, gif) into uint8/16 type on Google Colab using skimage.util.
# How to Import an image
from google.colab import files
from IPython.display import Image

# Convert to 8-bit uint
from skimage.util import img_as_uint

uploaded = files.upload()

img_as_uint(uploaded)

I am getting error in last line as:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-c19636843da4> in <module>()
----> 1 img_as_uint(uploaded)

1 frames
/usr/local/lib/python3.6/dist-packages/skimage/util/dtype.py in convert(image, dtype, force_copy, uniform)
    248     if not (dtype_in in _supported_types and dtype_out in _supported_types):
    249         raise ValueError("Can not convert from {} to {}."
--> 250                          .format(dtypeobj_in, dtypeobj_out))
    251
    252     if kind_in in 'ui':

ValueError: Can not convert from object to uint16.

A: I found a simple solution to the above problem.
We can use an matplotlib.pyplot.imread('filename.jpg') to convert the input image into an image object/pixel intensity values.
The code is as follows:
# How to Import an image
from google.colab import files
import matplotlib.pyplot as plt

# Select file from Local Drive
uploaded = files.upload()

# Convert uploaded image into uint type
img = plt.imread('Lenna.jpg')

# Confirm pixel dtype, shape and range(should be 0-255)
print('Data Type:',img.dtype)
print('Data Shape:',img.shape)
print('Min: %.3f, Max: %.3f' % (img.min(), img.max()))

Output :
Data Type: uint8
Data Shape: (373, 497, 3)
Min: 0.000, Max: 255.000


text:
Q: alloy model for hydrocarbons i need to model hydrocarbon structure using alloy
basically i need to design alkane, alkene and alkyne groups
i have created following signatures(alkene example)
sig Hydrogen{}
sig Carbon{}
sig alkenegrp{
    c:one Carbon,
    h:set Hydrogen,
    doublebond:lone alkenegrp
}
sig alkene{
    unit : set alkenegrp
}
fact{
    all a:alkenegrp|a not in a.doublebond.*doublebond
    all a:alkenegrp|#a.h=mul[#(a.c),2]
}
pred show_alkene{
    #alkene>1
}
run show_alkene

this works from alkene but when ever i try to design the same for alkane or alkyne by changing the fact like all a:alkynegrp|#a.h=minus[mul[#(a.c),2],2] it doesnt work.
Can anyone suggest how do i implement it?
My problem statement is
In Organic chemistry saturated hydrocarbons are organic compound composed entirely of single
bonds and are saturated with hydrogen. The general formula for saturated hydrocarbons is
CnH2n+2(assuming non-cyclic structures). Also called as alkanes. Unsaturated hydrocarbons
have one or more double or triple bonds between carbon atoms. Those with double bond are
called alkenes. Those with one double bond have the formula CnH2n (assuming non-cyclic
structures). Those containing triple bonds are called alkynes, with general formula CnH2n-2.
Model hydrocarbons and give predicates to generate instances of alkane, alkene and alkyne.
We have tried as:
sig Hydrogen{}
sig Carbon{}

sig alkane{
c:one Carbon,
h:set Hydrogen,
n:lone alkane
}

fact{
//(#h)=add [mul[(#c),2],2]
//all a:alkane|a not in a.*n
all a:alkane|#a.h=mul[#(a.c),2]
}
pred show_alkane(){}

run show_alkan

e
General formula for alkane is CnH2n+2,for multiplication we can use mul inbuilt function but we can not write for addtion as we have to do CnH2n+2.What should we write so that it can work for alkane

A: I understand alkanes, alkenes, and alkynes a little better now, but I still don't understand why you think your Alloy model doesn't work.
To express the CnH2n-2 constraint, you can certainly write what you suggested
all a:alkynegrp |
   #a.h = minus[mul[#(a.c), 2], 2]

The problem is only that in your alkane sig declaration you said c: one Carbon, which is going to fix the number of carbon atoms to exactly 1, so minus[mul[#(a.c), 2], 2] is always going to evaluate to exactly 0.  I assume you want to alloy for any number of carbons (since Cn) so you should change it from c: one Carbon to c: set Carbon.  If you then run the show_alkane predicate, you should get some instances where the number of carbons is greater than 1 and thus, the number of hydrogens is greater than 0.
Also, for the alkane formula
all a:alkynegrp |
   #a.h = plus[mul[#(a.c), 2], 2]

the default scope of 3 will not suffice, because you will need at least 4 atoms of hydrogen when a.c is non-empty, but you can fix that by explicitly giving a scope
run show_alkane for 8

If this wasn't the problem you were talking about, please be more specific about why you think "it doesn't work", i.e., what is it that you expect Alloy to do and what is it that Alloy actually does.


text:
Q: Load an image to a GSL matrix Does anyone know about some function that loads a grayscale image into a GSL matrix?
Something like:
gsl_matrix *M;
load_image("./image.jpg", M); // any image extension would also be fine

A: Something like this works on my PC: allows you to load a grayscale JPG image using libjpeg.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <jpeglib.h>
#include <gsl/gsl_matrix.h>

gsl_matrix *load_jpg_image(const char *pFileName)
{
    FILE *pFile;
    long jpegSize;
    unsigned char *pJpegBytes, *pPixels;
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;
    int status, w, h, numComponents, stride, x, y;
    gsl_matrix *pMatrix;

    pFile = fopen(pFileName, "rb");
    if (!pFile)
    {
        fprintf(stderr, "Can't open file\n");
        return NULL;
    }

    // Get the size of the file
    fseek(pFile, 0, SEEK_END);
    jpegSize = ftell(pFile);
    rewind(pFile);

    if (jpegSize == 0)
    {
        fclose(pFile);
        fprintf(stderr, "Empty file\n");
        return NULL;
    }

    // Read it into memory and close file
    pJpegBytes = (unsigned char *)malloc(jpegSize);
    fread(pJpegBytes, 1, jpegSize, pFile);
    fclose(pFile);

    // Jpeg decompression starts here
    memset(&cinfo, 0, sizeof(struct jpeg_decompress_struct));
    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_decompress(&cinfo);

    jpeg_mem_src(&cinfo, pJpegBytes, jpegSize);
    status = jpeg_read_header(&cinfo, TRUE);

    if (status != 1)
    {
        free(pJpegBytes);
        fprintf(stderr, "Invalid JPEG header\n");
        return NULL;
    }

    jpeg_start_decompress(&cinfo);

    w = cinfo.output_width;
    h = cinfo.output_height;
    numComponents = cinfo.output_components;

    if (numComponents != 1)
    {
        free(pJpegBytes);
        fprintf(stderr, "Can only handle 1 color component\n");
        return NULL;
    }

    pPixels = (unsigned char *)malloc(w*h);
    stride = w*numComponents;

    // perhaps this can de done much faster by processing
    // multiple lines at once
    while (cinfo.output_scanline < cinfo.output_height)
    {
        unsigned char *buffer_array[1];
        buffer_array[0] = pPixels + cinfo.output_scanline * stride;

        jpeg_read_scanlines(&cinfo, buffer_array, 1);
    }

    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);

    free(pJpegBytes);

    // Now, create and fill in the matrix
    pMatrix = gsl_matrix_alloc(h, w);
    for (y = 0 ; y < h ; y++)
        for (x = 0 ; x < w ; x++)
            gsl_matrix_set(pMatrix, y, x, pPixels[x+y*stride]);

    return pMatrix;
}

int main(void)
{
    gsl_matrix *pMatrix;
    int rows, cols;
    int i, j;

    pMatrix = load_jpg_image("test.jpg");
    if (pMatrix == NULL)
    {
        fprintf(stderr, "Can't load matrix\n");
        return -1;
    }

    //
    // Use the matrix
    //

    gsl_matrix_free(pMatrix);
    return 0;
}


text:
Q: How to jtextField focus event in NetBeas I made a landing interface in Java using NetBeans. I want to set when the textfield input format does not meet the requirements, then  Red tips occur, how to achieve this? I know it is related to focus event, but I do not know the  details

A: I suggest that use ActionEvent and ActionListener for textfield.
then use textfield.getText() to get String data.
you can now examine the String's content by separate it.
If you wanna check the format is a number or not, just use NumberFormatException.
https://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html
after that,
you want a red warning tip, use label with color red, and .setVisible(boolean) to control it shows or not.


text:
Q: How can I extract the data showed in Version Changes before reconcile/post process? I want to make a script in python to extract the data about version changes before make the reconcile/post process. Is that possible? I trying to avoid use C# or VB script.

A: Here's a python script to try. It's designed to be set up and run as an ArcGIS Toolbox script. Parameter type info is commented in the code. This will take an input dataset and target dataset (which correspond to the dataset form the input and target Versions that you are reconciling). You will need to make a database connection to each Version and use those connections when adding the datasets as parameters. The script will compare the current geometry and attribution for each Version and produce a csv output file which lists the OBJECTID, type of change, and for attribute changes the field and values. It will find adds, deletes, geometry updates and attribute updates. I've only tested this on a small dataset with "contrived" edits for testing, but hopefully it will work for you as well.
import arcpy, os

inputDataset = arcpy.GetParameterAsText(0)    # Parameter Type = Feature Class
targetDataset = arcpy.GetParameterAsText(1)   # Parameter Type = Feature Class
outputFolder = arcpy.GetParameterAsText(2)    # Parameter Type = Folder
outputName = arcpy.GetParameterAsText(3)      # Parameter Type = String

inputDict = {}
changes = []

# GET FIELDS
arcpy.AddMessage("Getting Fields\n")
fields = ["OID@", "Shape@JSON"]
fieldList = arcpy.ListFields(targetDataset)
for field in fieldList:
    if field.name not in ("OBJECTID", "SHAPE", "Shape_Length", "Shape_Area", "RuleID", "Override"):
        fields.append(field.name)

# SEARCH INPUT DATASET, ADD DATA TO DICTIONARY
arcpy.AddMessage("Searching Input Dataset\n")
with arcpy.da.SearchCursor(inputDataset, fields) as inputRows:
    for inputRow in inputRows:
        oid = inputRow[0]
        geom = inputRow[1]
        attrs = {"Geometry":geom}
        for i in range(len(fields)):
            if i > 1:
                field = str(fields[i])
                attrs[field] = inputRow[i]
        inputDict[oid] = attrs

# SEARCH TARGET DATASET AND COMPARE TO DICTIONARY DATA
arcpy.AddMessage("Searching Target Dataset\n")
with arcpy.da.SearchCursor(targetDataset, fields) as targetRows:
    for targetRow in targetRows:

        # If no match in dictionary, it's a delete
        oid = targetRow[0]
        if oid not in inputDict.keys():
            changes.append([oid, "Delete", "N/A", "N/A", "N/A"])
        else:

            # If geometries don't match, it's a geometry update
            geom = targetRow[1]
            if geom != inputDict[oid]["Geometry"]:
                changes.append([oid, "Geometry Update", "N/A", "N/A", "N/A"])

            # If attribute values don't match, it's an attribute update
            for j in range(len(fields)):
                if j > 1:
                    field = str(fields[j])
                    value = targetRow[j]
                    if value != inputDict[oid][field]:
                        changes.append([oid, "Attribute Update", field, value, inputDict[oid][field]])

            # If there was a match, remove item from dictionary
            del inputDict[oid]

# Anything left in the dictionary is an added feature
for oid in inputDict.keys():
    changes.append([oid, "Add", "N/A", "N/A", "N/A"])

# Write Output Change File
arcpy.AddMessage("Writing Output File\n")
outputFile = open(outputFolder + os.sep + outputName + ".csv", "w")
outputFile.write("OID,CHANGETYPE,FIELD,INPUTVALUE,TARGETVALUE\n")
for change in changes:
    line = ""
    for item in change:
        line += str(item)
        line += ","
    line = line[:-1]
    line += "\n"
    outputFile.write(line)

arcpy.AddMessage("\n\nAll Done!\n\n")


text:
Q: Validate dropdownlist only if another textbox has a value - ASP.NET In my web application, i have a textbox and a dropdownlist.
My requirement is, i want to implement validation where it makes mandatory for the user to choose the dropdownlist if he fills the textbox, other wise the validation should not happen.
The code i have,

            Returned On

                <asp:TextBox ID="Txtto" runat="server" AutoCompleteType="Disabled"></asp:TextBox>

                <asp:DropDownList ID="ddlcond" runat="server" Height="26px" Width="156px" Visible="false">
                    <asp:ListItem Text="Working Condition" value="none"></asp:ListItem>
                    <asp:ListItem Text="Good-Usuable" Value="1"></asp:ListItem>
                    <asp:ListItem Text="Bad-Need Maintenance" Value="2"></asp:ListItem>
                </asp:DropDownList>

<asp:Button ID="BtnUpdate" runat="server" Text="Update" Visible="false" OnClick="BtnUpdate_Click" Width="75px" />

A: There are many ways to do this. On the btnUpdate_Click check to see if there is any text and route accordingly.
 if(Txtto.Text.Trim().Length > 0)
 {
     if(ddlcond.SelectedValue == "none")
      {
         //call alert (excuse the syntax I'm typing from memory)
         ScriptManager.RegisterStartupScript(Page, Page.GetType, "err", "alert('Error You must select a drop down list value')", True);
      }
     else
     {
         // your code to run here, page is valid
     }


text:
Q: What is the difference between deterministic and stochastic model? Simple Linear Model:
$x=\alpha t + \epsilon_t$ where $\epsilon_t$  ~iid $N(0,\sigma^2)$
with $E(x) = \alpha t$ and $Var(x)=\sigma^2$
AR(1):
$X_t =\alpha X_{t-1} + \epsilon_t$ where $\epsilon_t$  ~iid $N(0,\sigma^2)$
with $E(x) = \alpha t$ and $Var(x)=t\sigma^2$
So a simple linear model is regarded as a deterministic model while a AR(1) model is regarded as stocahstic model.
According to a Youtube Video by Ben Lambert - Deterministic vs Stochastic, the reason of AR(1) to be called as stochastic model is because the variance of it increases with time. So is the feature of non-constant variance to be the criteria to determine the stochastic or deterministic?
I also don't think simple linear model is totally deterministic as we have a $\epsilon_t$ term associated with the model. Hence, we always have a randomness in $x$. So to what degree can we say a model is deterministic or stochastic?

A: Some informal definitions

*

*A deterministic time series $\{y_t\}$ can be written as a function only of time. There is NO randomness. Some examples:

*

*$y(t) = 2t$

*$y(t) = e^t$

*A stochastic process $\{Y_t\}$ is a series of random variables. Recall that a random variable is a function from a sample space $\Omega$ to an outcome. A stochastic process $Y(t,\omega)$ is a function of both time $t$ and an outcome $\omega$ from sample space $\Omega$. Examples:

*

*$y_t = \epsilon_t$ where $\epsilon_t \sim \mathcal{N}(0, 1)$ (i.e. follows standard normal distribution)

*$y_t = .7 y_{t-1} + \epsilon_t$

You can also think of a stochastic process as a deterministic path for every outcome $\omega$ in the sample space $\Omega$. Randomly draw an $\omega \in \Omega$ and you get a path $Y_t(\omega)$.
Some comments...

... reason of AR(1) to be called as stochastic model is because the variance of it increases with time.

That's not the reason! The reason an AR(1) defines a stochastic process is because the process is random. Different values are possible at a time $t$, hence the process is stochastic.

I also don't think simple linear model is totally deterministic as we have a $\epsilon_t$ term associated with the model.

The $x_t$ you have written up there is not deterministic. If you had a time series process $x_t = \alpha t + \epsilon_t$ where $\{\epsilon_t\}$ is a white noise process, then the time series $\{x_t\}$ would not be deterministic. It is stochastic because there is randomness!
The time series $y_t = \alpha t$ would be deterministic. You can decompose $\{x_t\}$ into two components: a deterministic component $\alpha t$ and a stochastic component $\epsilon_t$.
This leads to Wold's Theorem that any covariance stationary process can be uniquely decomposed into a deterministic component and a stochastic component.

A: The video is talking about deterministic vs. stochastic trends, not models. The highlight is very important. Both your models are stochastic, however, in the model 1 the trend is deterministic.
The model 2 doesn't have a trend. Your question text is incorrect.
The model 2 in your question is AR(1) without a constant, while in the video the model is a random walk (Brownian motion):
$$x_t=\alpha+x_{t-1}+e_t$$
This model indeed has a stochastic trend. It's stochastic because it's $\alpha t$ only in average. Each realization of a Brownian motion will deviate from $\alpha t$ because of the random term $e_t$, which is easy to see by differencing:
$$\Delta x_t=x_t-x_{t-1}=\alpha+e_t$$
$$x_t=x_0+\sum_{t=1}^t\Delta x_t=x_0+\alpha t +\sum_{t=1}^t e_t$$

A: As Aksakal mentioned in his answer, the video Ken T linked describes properties of trends, not of models directly, presumably as part of teaching about the related topic of trend- and difference-stationarity in econometrics.  Since in your question, you asked about models, here it is in the context of models:
A model or process is stochastic if it has randomness.  For example, if given the same inputs (independent variables, weights/parameters, hyperparameters, etc.), the model might produce  different outputs.  In deterministic models, the output is fully specified by the inputs to the model (independent variables, weights/parameters, hyperparameters, etc.), such that given the same inputs to the model, the outputs are identical.  The origin of the term "stochastic" comes from stochastic processes.  As a general rule of thumb, if a model has a random variable, it is stochastic.   Stochastic models can even be simple independent random variables.
Let's unpack some more terminology that will help you understand the literature around statistical models (deterministic, stochastic, or otherwise...):
Stochastic models do not need to be time-dependent or even Markov processes (dependent on past states, for example $AR(1)$ is first-order Markov since it depends on the state at $t-1$).  The linear model you posed above is stochastic (has a random variable) but not Markov (does not depend on past states).  In the linear model posed in the question, the error term is a random variable that we assume is uncorrelated (some people go further to state that error is i.i.d.), symmetrically distributed about the mean (some people go further to state that error is normally distributed), and mean zero ($\mu_{\epsilon_t}=0$), etc.  We make these assumptions in order to make the linear model useful to estimate the dependent variable(s) by minimizing some norm of that error term.  These assumptions allow us to derive useful properties of estimators and prove that certain estimators are the best under those assumptions; for example, that the OLS estimator is BLUE.
A simpler example of a stochastic model is flipping a fair coin (heads or tails), which can be modeled stochastically as an i.i.d. uniformly distributed binary random variable, or a Bernoulli process.   You can also consider the coin flip as a physical system and come up with a deterministic model (in an idealized setting) if you take into account the shape of the coin, angle and force of impact, distance to the surface, etc.  If the latter (physical) model  of the coin flip has no random variables in it (e.g. it doesn't consider measurement error of any of the inputs to the model), then it is deterministic.
In teaching statistics, there is a common point of confusion between stochasticity and heteroscedasticity.  For example, Ken T has confused stochasticity for heteroscedasticity (or variability in variance).  A random (stochastic) variable, such as the output variable $X_t$ of an $AR(1)$ process or $\epsilon_t$ in a linear model $y_t = ax_t+\epsilon_t$, is heteroscedastic iff its variance changes over some input, such as time ($t$) in this case, such that different groups within the population have different variances.  In the video that Ken T linked (by Ben Lambert), if you pause it at 4:00 (4 minutes), you can see that $Var[X_t]$ in the model on the right side changes with $t$ (heteroscedastic) while $Var[X_t]$ in the linear model is constant (homoscedastic).
Furthermore, there is sometimes confusion between stationary stochastic processes and non-stationary stochastic processes.  Stationarity implies that statistics such as mean or variance do not change over time in the model.  Both are still considered stochastic models/processes as long as there is randomness involved.  As fellow Maroon, Matthew Gunn, mentions in his answer, Wold's decomposition states that any stationary stochastic process can be written as the sum of a deterministic and a stochastic process.


text:
Q: Convert string to slice of string TLDR
How to convert "[\"a\",\"b\"]" (type string) to slice of string ["a", "b"]?
Usecase
I am using text/template to create a yaml file which is used in go package.
// test_params.yaml
ips: {{.ips}}

// values.yaml
ips: '["10.0.0.1","10.0.0.2"]'           # string

// get_ip.go

// Read values
v, _ := ioutil.ReadFile("values.yaml")
config = make(map[string]interface{})
_ = yaml.Unmarshal(v, &config)

// Create file and replace values
tmpl, _ := template.New("CentralConfig").Parse(tmplStr)
f, _ := os.Create("final_yaml.yaml")
_ = tmpl.Execute(f, config)

This will create a yaml
// final_yaml.yaml
ips: '["10.0.0.1","10.0.0.2"]'           # string

From where I have to use ips as []string.
The reason I am not using an array in the first place in values.yaml is that it will create final_yaml.yaml that is not proper yaml.
So if I had used
// values.yaml
ips: ["10.0.0.1","10.0.0.2"]           # array

then the final_yaml would look like:
// final_yaml.yaml
ips: '[10.0.0.1 10.0.0.2]'           # string

which doesn't seem usable at all.
Also, if someone has a better approach to do the same something to use variables in yaml (maybe like a library yaml/template similar to text/template), I would be pleased to hear.

A: From the YAML perspective, the sensible thing to do would be to give the value as sequence and then properly render it out again. go-yaml allows you to capture the YAML structure as yaml.Node however it is not able to convert it back to a string representation again. Given the data in yaml.Node, it is generally possible to implement it yourself for simple input:
package main

import (
    "gopkg.in/yaml.v3"
    "os"
    "text/template"
)

var testParams = `ips: {{.ips}}`

var params = `ips: ["10.0.0.1","10.0.0.2"]`

type Subtree struct {
    root *yaml.Node
}

// UnmarshalYAML is called by the YAML unmarshaler and captures
// the value as yaml.Node.
func (s *Subtree) UnmarshalYAML(n *yaml.Node) error {
    s.root = n
    return nil
}

func renderNode(n *yaml.Node) string {
    switch n.Kind {
    case yaml.ScalarNode:
        return "\"" + n.Value + "\""
    case yaml.SequenceNode:
        ret := "["
        first := true
        for _, item := range(n.Content) {
            if first {
                first = false
            } else {
                ret += ", "
            }
            ret += renderNode(item)
        }
        return ret + "]"
    default:
        panic("node kind not implemented")
    }
}

// String is called by the template renderer.
func (s *Subtree) String() string {
    return renderNode(s.root)
}

func main() {
    var config map[string]*Subtree
    _ = yaml.Unmarshal([]byte(params), &config)

    tmpl, _ := template.New("CentralConfig").Parse(testParams)
    _ = tmpl.Execute(os.Stdout, config)
}

This will render
ips: ["10.0.0.1", "10.0.0.2"]

Please be aware that renderNode as given is not safe as it will not properly escape special characters in scalars. Also it doesn't handle mappings or aliases. This snippet merely serves as starting point and you'll need to add additional functionality as necessary.


text:
Q: how to redirect on edittext when click on icon or image? Following is my xml file. I want that when I click imgDescAddCity it will redirect on next EditText which is txtDescAddCity. It is like a WhatsApp status when we click on edit or change status icon it can allow writing new status in EditText same as hear. I want that when I click on imgDescAddCity icon cursor will redirect on txtDescAddCity EditText.
<include
    android:id="@+id/include"
    layout="@layout/header_new_city"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/include"
    android:background="@color/backgroundLayout"
    android:orientation="vertical"
    android:weightSum="5">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="10dp"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/txtCityNameAddCity"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:hint="City name"
                    android:inputType="textPersonName" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="10dp"
                    android:layout_weight="1"
                    android:orientation="horizontal"
                    android:weightSum="2">

                    <TextView
                        android:id="@+id/textView141"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginRight="10dp"
                        android:layout_marginTop="10dp"
                        android:layout_weight="1.75"
                        android:text="Description"
                        android:textStyle="bold" />

                    <ImageView
                        android:id="@+id/imgDescAddCity"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="10dp"
                        android:layout_marginTop="10dp"
                        android:layout_weight="0.25"
                        app:srcCompat="@drawable/ic_border_color_black" />
                </LinearLayout>

                <EditText
                    android:id="@+id/txtDescAddCity"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="10dp"
                    android:layout_weight="1"
                    android:background="@null"
                    android:hint="description here" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginBottom="10dp"
                    android:layout_marginTop="10dp"
                    android:layout_weight="1"
                    android:background="@color/backgroundColor"
                    android:orientation="horizontal"
                    android:weightSum="2">

                    <Spinner
                        android:id="@+id/spinner2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1.75"
                        android:background="@null"
                        android:layout_gravity="center"
                        android:entries="@array/addcity" />

                    <ImageView
                        android:id="@+id/imageView82"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:layout_weight="0.25"
                        app:srcCompat="@drawable/search_magnifying" />

                </LinearLayout>

                <EditText
                    android:id="@+id/txtSeasonToVisitAddCity"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:hint="Best season to visit"
                    android:inputType="textPersonName" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="horizontal"
                    android:weightSum="2">

                    <TextView
                        android:id="@+id/txt"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginRight="10dp"
                        android:layout_marginTop="10dp"
                        android:layout_weight="1.75"
                        android:text="City photo" />

                    <ImageView
                        android:id="@+id/imgAttachAddCity"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="10dp"
                        android:layout_marginTop="10dp"
                        android:layout_weight="0.25"
                        app:srcCompat="@drawable/attach" />

                </LinearLayout>

            </LinearLayout>

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerViewAddCityImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:elevation="0dp"
                android:orientation="horizontal" />

            <TextView
                android:id="@+id/addCity"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:background="@color/lightBlue"
                android:paddingBottom="10dp"
                android:paddingTop="10dp"
                android:text="city"
                android:textAlignment="center"
                android:textColor="@color/backgroundColor" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

A: as per my above comment
use requestFocus method on edittext
edittext.requestFocus();

try this tutorial.