text:
Q: Large training and testing data in libsvm I'm using Libsvm in a 5x2 cross validation to classify a very huge amount of data, that is, I have 47k samples for training and 47k samples for testing in 10 different configurations.
I usually use the Libsvm's script easy.py to classify the data, but it's taking so long, I've been waiting for results for more than 3 hours and nothing, and I still have to repeat this procedure more 9 times!
does anybody know how to use the libsvm faster with a very huge amount of data? does the C++ Libsvm functions work faster than the python functions?

A: LibSVM's training algorithm doesn't scale up to this kind of datasets; it takes O(n³) time in the worst case and around O(n²) on typical ones. The first thing to try is scaling your datasets properly; if it still doesn't work, switch to

*

*a linear SVM (or logistic regression) using, e.g., Liblinear, Vowpal Wabbit or Wapiti

*a more scalable kernel SVM implementation such as LaSVM

A: As larsmans mentioned, libsvm may not scale all that well depending on the dimensionality of the data and the number of data points.
The C implementation may run a bit faster, but it won't be a significant difference.  You have a few options available to you.

*

*You could randomly sample your data to work on a small subset of it.

*You could project your data into a lower dimension with something like PCA

*Depending on your data type, you can look into different kernels.  Would a histogram intersection kernel work out for your data?  Are you using an RBF kernel when you really just need a linear decision function?

Hope this helps!  One of the toughest problems in machine learning is coping with the pure magnitude of data required at times.

A: easy.py is a script for training and evaluating a classifier. it does a metatraining for the SVM parameters with grid.py. in grid.py is a parameter "nr_local_worker" which is defining the mumber of threads. you might wish to increase it (check processor load).


text:
Q: How to identify changes from and to using Regex in R leveraging stringr? I want to extract the sentenses that capture the change in profits. Here is my toy data:
library(tibble)
library(stringr)

df <- tibble(company = c("A", "B"),
             text = c("The profits of ABC increased from 2% earlier to about 5% in 2021. How are you? The profit of XYZ however only increased by 50 bps to 220bps. I am good. MNL's profits increased to 6% from 3%. Thank you! The profits of Alpha increased 20bps from 5% to 5.2%. How are you doing? The profits of Beta went up 30bps from 500 bps to 530 bps. Fantastic!!",
                      "The profits of AHA increased from 3% earlier to about 5% in 2022. How are you buddy? The profit of KHFG however only increased by 40 bps to 210bps. I am good sir. LRD's profits increased to 7% from 5%. Thank you mate! The profits of Gamma increased 15bps from 5% to 5.15%. How are you doing dude? The profits of Lambda went up 20bps from 500 bps to 520 bps. Got it!!"))

desired_output <- tibble(company = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"),
                             text = c("The profits of ABC increased from 2% earlier to about 5% in 2021.",
                                      "The profit of XYZ however only increased by 50 bps to 220bps.",
                                      "MNL's profits increased to 6% from 3%.",
                                      "The profits of Alpha increased 20bps from 5% to 5.2%.",
                                      "The profits of Beta went up 30bps from 500 bps to 530 bps.",
                                      "The profits of AHA increased from 3% earlier to about 5% in 2022.",
                                      "The profit of KHFG however only increased by 40 bps to 210bps.",
                                      "LRD's profits increased to 7% from 5%.",
                                      "The profits of Gamma increased 15bps from 5% to 5.15%.",
                                      "The profits of Lambda went up 20bps from 500 bps to 520 bps."))

I could think of a regex to capture cases like

*

*from "some digits with %/bps/BPS suffix" to "some digits with %/bps/BPS suffix"

*to "some digits with %/bps/BPS suffix" from "some digits with %/bps/BPS suffix"

*increased "some digits with %/bps/BPS suffix" to "some digits with %/bps/BPS suffix"

*increased "some digits with %/bps/BPS suffix" from "some digits with %/bps/BPS suffix"

*up "some digits with %/bps/BPS suffix" from "some digits with %/bps/BPS suffix"

*up "some digits with %/bps/BPS suffix" to "some digits with %/bps/BPS suffix"

for test, the number formats can be any combinatio of with or without decimal places

*

*2% to 5%

*2bps to 5 bps

*2BPS to 5 BPS

*2bps - 5 bps

*2 BPS - 5BPS

I don't know where to start and hence don't have an attempted regex here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How did Geralt of Rivia escape the Wild Hunt We know that he was a Wild Hunt rider, as he traded his soul for Yens', but how did he escape from the clutches of the Hunt. Does it relate to the 3rd game where the Hunt King says that Geralt brings more death and despair if left alone?

A: In Witcher 3, you will learn that

 Ciri freed Geralt from the wild hunt.  The intention of the Wild Hunt all along was to capture Ciri, they first tried to use Yennifer, and then they had Geralt for a while.  Once she freed him, she left him near Kaer Morhen to begin the events of Witcher 1.


text:
Q: Hello I can't seem to figure out why my program isn't working The program is to calculate the total price for meat but I keep getting the output of $.68 instead of $10.89, any help would be greatly appreciated. While i'm sure it's most likely a error with the last println statement any help would be useful.
 /**********************************************************************
Program: Deli.java
Description: Computes the price of a deli item given the weight (in ounces)
        and the price per pound.
***********************************************************************/

import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Deli
{
/* -------------------------------------------------------------------------------------
The function main reads in the price per pound of a deli item
and the number of ounces of a deli item then computes the total price
and prints a "label" for the item that includes the unit price (per pound),
the weight and total price.
----------------------------------------------------------------------------------------*/

public static void main (String[] args)
{
final double OUNCES_PER_POUND = 16.0;
double pricePerPound;   // price per pound
double weightOunces;    // weight in ounces
double weight;      // weight in pounds
double totalPrice;      // total price for the item
Scanner scan = new Scanner(System.in);

/* ------------------------------------------------------------------------
Declare money as a NumberFormat object and use the
getCurrencyInstance method to assign it a value.
Declare fmt as a DecimalFormat object and instantiate
it to format numbers with at least one digit to the left of the
decimal and the fractional part rounded to two digits.
Prompt the user and read in each input.
-------------------------------------------------------------------------*/
NumberFormat format1 = NumberFormat.getCurrencyInstance();
DecimalFormat format2 = new DecimalFormat("0.##");
System. out. println ("Welcome to the CS Deli! ! \n ");
System.out.print ("Enter the price per pound of your item: ");
pricePerPound = scan.nextDouble();
System.out.print ("Enter the weight (ounces): ");
weightOunces = scan.nextDouble();

// Convert ounces to pounds and compute the total price
weight = weightOunces / OUNCES_PER_POUND;
totalPrice = pricePerPound * weight;

// Print the unit price, weight, and total price using the formatting objects.
// Format the weight in pounds and use the money format for the prices.
System.out.println("\nUnit Price: " + format1.format(pricePerPound) + " per pound");
System.out.println("\nWeight: " + format2.format(weightOunces) + " pounds");
System.out.println("\nTotal Price: " + format1.format(totalPrice));
}
}

A: "The inputs are $4.25 for the unit price, and 2.56 pounds."
I think you're a little confused here as to how your application is expecting its input. The prompts ask for The price per pound:
Enter the price per pound of your item: 4.25

and then asks to enter  The weight in ounces:
Enter the weight (ounces): 2.56

Again, it asks to enter in ounces not pounds. The code then takes this ounces input (2.56) and converts it to pounds which ends up being about 0.16 pounds. Well, I suppose 0.16 pounds of the item which is priced at $4.25 per pound will cost you $0.68 dollars (or just 68 cents).
If you really wanted to purchase 2.56 pounds of the item then you should have supplied 40.96 (2.56 * 16) in the ounces prompt.
As @JohnBayko has already so graciously pointed out, you are displaying the wrong value in your output from this code line:
System.out.println("\nWeight: " + format2.format(weightOunces) + " pounds");

It should be your conversion value displayed not what was entered:
System.out.println("\nWeight: " + format2.format(weight) + " pounds");


text:
Q: Is CUDA optimising this Code Badly or am I wrong? Here is a block of Code I have been working on and have been recieving a result I didn't expect. I've cut down my full code block to just highlight the problem. I expect that at the end of this block spID should be a block of tid values with the exception of those pixels where lbBool is true where spID should be _CCL_SHARED_MEM_MAX_VALUE (255). However If I use NSight to debug the data at the __syncthreads() I find all the spID values equivalent to where lbBool was true are 0.
My blocks are composed of 16 by 16 threads so uint8 is sufficient for storing all the values (0-255). I realise that there will be a single valid pixel with the ID 255 and a load of dead pixels with a Value of 255. That is fine.
I'm using unsigned long for tOut.
In this case my Image is 100x100 but it fails on each image size I've tried.
I'm running on a GTX 580 and regularly use kernels with 256 threads.
Calling the Kernel:
#define _CCL_SHARED_MEM_TYPE uint8
#define _CCL_SHARED_MEM_MAX_VALUE 255

template<class tOut> tOut *nsGPUBaseClasses::IbxCCL4Link(bool *lbEdges,uint32 liImageWidth,uint32 liImageHeight,tOut *lpOut)
{
dim3 liThreads(16,16);
dim3 liBlocks((liImageWidth+liThreads.x-1)/liThreads.x,(liImageHeight+liThreads.y-1)/liThreads.y);

if(lpOut == nullptr) _CHECK_CUDA_ERROR(cudaMalloc(&lpOut,sizeof(tOut)*liImageWidth*liImageHeight));

IbxCCL4LinkCUDA<<<liBlocks,liThreads,(sizeof(_CCL_SHARED_MEM_TYPE)*liThreads.x*liThreads.y+sizeof(bool)*2)>>>(lbEdges,liImageWidth,liImageHeight,lpOut);

_CHECK_CUDA_ERROR_EMPTY();

return lpOut;
}

And the Kernel Itself:
template<class tOut> void __global__ IbxCCL4LinkCUDA(bool *lbBool,unsigned long liImageWidth,unsigned long liImageHeight,tOut *lpOut)
{
    // Shared Memory
    __shared__ float lbSpecific[];
    _CCL_SHARED_MEM_TYPE *spID=reinterpret_cast<_CCL_SHARED_MEM_TYPE*>(&lbSpecific);

    //IDs for thread
    unsigned long tid = threadIdx.x+threadIdx.y*blockDim.x;
    unsigned long liXPos = threadIdx.x+blockIdx.x*blockDim.x;
    unsigned long liYPos = (threadIdx.y+blockIdx.y*blockDim.y);

    //Check if it is in image bounds
    if(liXPos>=liImageWidth || liYPos>=liImageHeight) return;
    unsigned long liPPos = liXPos+liYPos*liImageWidth;

    //If Boolean is true
    if(lbBool[liPPos])
    {
        spID[tid] = _CCL_SHARED_MEM_MAX_VALUE;
        lpOut[liPPos] =liImageWidth*liImageHeight;
        return;
    }
    lpOut = &lpOut[liPPos];
    lpOut[0] = (blockIdx.x+blockIdx.y*gridDim.x)*(_CCL_SHARED_MEM_MAX_VALUE+1);

    spID[tid] = tid;
    __syncthreads();

    //More Processing Goes Here

    lpOut[0] += static_cast<tOut>(spID[tid]);
}

Should this be outputting 255 or 0 in equivalent locations to lbBool being true?
If it is zero is this Cuda optimising out the write to shared memory?
Is there a way I can make the boolean check set the Value to 255?

A: Your shared memory allocation is broken.  __shared__ float lbSpecific; allocates ONE floating point value.  You then set spID to that address, and use locations far beyond the single floating point allocation.
Just allocate the shared memory you want, with the correct size and type, and skip the typecast.
__shared__ _CCL_SHARED_MEM_TYPE spID[TOTAL_BLOCK_SIZE];


text:
Q: How do I fix a permissions problem with MS Distributed File System? I have a computer that is new, Windows 7, that is supposed to have access to particular network resources on a Distributed File System.  However, despite all permissions being set correctly, I have consistent trouble accessing them.
For instance, I'm supposed to be able to reach \company.org\main\subdir.  All the permissions have been granted, only when I try to access it by name, it tells me I don't have permission to access \main.
This is where the fun starts.  If I ping company.org, get the IP, replace company.org by the IP, I can then access \IP\main\subdir without any problems at all.  However we have a ton of scripts and build tools that access the network resource by name.
My sysadmin has found that using MS's dfsutil.exe, we can fix it temporary using this sequence of commands:
C:\dfsutil.exe /pktinfo
C:\dfsutil.exe /PktFlush
C:\dfsutil.exe /SpcFlush
C:\dfsutil.exe /PurgeMupCache
C:\dfsutil.exe /pktinfo
After that, everything is great... until I reboot, or until some unspecified time later where suddenly I don't have access to \main\ anymore.
Hoping to find a more permanent solution than waiting for it to break and running a batch file.

A: dfs is site aware, do you happen to know if your in a multisite dfs infrastructure?


text:
Q: how to add iiwa joint torque sensor in drake I want to use iiwa's joint torque feedback data in my controller's input.
But I didn't find API to get joint torque data.
Which API should I use?
get_reaction_forces_output_port. or get_generalized_contact_forces_output_port?

A: The iiwa API makes three torque values available: commanded, measured, and external.  In the manipulation_station simulation, we take commanded to be the value of the input port, measured to be the same (assuming ideal torque tracking), and external to be the value from the get_generalized_contact_forces_output_port -- since contact forces are the only source of external torques.
You can see that code here and here.


text:
Q: Where do all the numbers come from in the standard 2.2 gamma correction for RGB? Here is the standard fwd Gamma 2.22 (1 / 0.45) correction formula:
for R,G,B < 0.018
R´ = 4.5 * R
G´ = 4.5 * G
B´ = 4.5 * B
for R,G,B ≥ 0.018
R´ = 1.099 * R^0.45 - 0.099
G´ = 1.099 * G^0.45 - 0.099
B´ = 1.099 * B^0.45 - 0.099

Where do the figures 0.18, 4.5, 1.099, and 0.099 come from? I specifically need to know how they are derived.
I need to know because I am writing a gamma correction function, and the simple approach of using a power and scaling, rather than the above, yields different results.

A: So here is how far I figured it.
The gamma correction function had to be designed with the following requirements (see this paper):

*

*the voltage for 0 intensity must be 0

*the voltage for 1 intensity must be 1

*it must behave like a power function (exponent 1/2.22=0.45) close to intensity 1

*it must be linear close to the origin (to reduce the effect of sensor noise at low intensity)

*it must be continuous and continuously differentiable in [0,1]

so this problem can be solved by finding the numbers {a,b,c,x0} defining a function g:x->g(x) such as:

*

*g(x) = a*x^.45+b in [x0,1]

*g(x) = cx im [0,x0[

*g(1) = 1

*g(0) = 0

*lim{x->x0-}(g) = lim{x->x0+}(g)

*lim{x->x0-}(dg/dx) = lim{x->x0+}(dg/dx)

which yields the following equations:

*

*a+b=1

*c*x0=a*x0^.45+b

*c=0.45*a*x0^-0.55

equivalent to:

*

*a=1/(1-.55*x0^.45)

*b=-.55*x0^.45/(1-.55*x0^.45)

*c=.45*x0^-.55/(1-.55*x0^.45)

if you set x0 to 0.018, you get :

*

*a=1.099

*b=-.099

*c=4.5

The remaining questions is: how did they choose x0? I could not find any justification for the 0.018 value... Or they could have started with any of the other 3 parameters (for instance, set the toe slope to 4.5, they derive a,b and x0).
Not sure this will solve your problem, anyway I hope this helps (I had fun with the math).


text:
Q: How to build hsdis.dll for Windows 32-bit? I am trying to build hsdis.dll in my laptop 32-bit Windows. I read http://dropzone.nfshost.com/hsdis.htm instructions and got to know that  I will have to follow those steps. I saw that I have to use the mingw64-i686-gcc-core. I followed the steps, but have always  found this error.
make[2]: i686-w64-mingw32: Command not found
Makefile:246: recipe for target 'libiberty.a' failed
make[2]: *** [libiberty.a] Error 127
make[2]: Leaving directory '/home/User/hsdis/build/Linux-i586/libiberty'
Makefile:8045: recipe for target 'all-libiberty' failed
make[1]: *** [all-libiberty] Error 2
make[1]: Leaving directory '/home/User/hsdis/build/Linux-i586'
Makefile:192: recipe for target 'build/Linux-i586/bfd/libbfd.a' failed
make: *** [build/Linux-i586/bfd/libbfd.a] Error 2

I would also like to know how to use the directive PrintAssembly, because i wanted to see the assembly code, of a Java class.
I have already saw other posts here, but none of them helped.
Thanks in advance

A: Here are the steps which help me to build it (x64 version, x86 should be almost the same):

*

*download and unpack the latest hsdis sources as described in the building manual from the http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/tags;

*download the latest bintuils-2.26.tar.gz package from the http://mirror.tochlab.net/pub/gnu/binutils/;

*copy it to your Cygwin home directory and unpack it from the Cygwin terminal (this is very important, otherwise you may get permission problems):
tar -xzvf ./binutils-2.26.tar.gz

*install the following Cygwin packages: mingw64-x86_64-gcc-core for x64 or mingw64-i686-gcc-core for x86, diffutils and make;

*go to hsdis directory;

*for x64 library build with the command: make OS=Linux MINGW=x86_64-w64-mingw32 'AR=x86_64-w64-mingw32-ar' BINUTILS=~/binutils-2.26 CONFIGURE_ARGS="--host=x86_64-w64-mingw32", for x86 library build with the command: make OS=Linux MINGW=i686-w64-mingw32 'AR=i686-w64-mingw32-ar' BINUTILS=~/binutils-2.26 CONFIGURE_ARGS="--host=i686-w64-mingw32"

*if you have errors with undefined references to zlib (i.e. build/Linux-amd64/bfd/libbfd.a(compress.o):compress.c:(.text+0x7e): undefined reference to inflate), modify Makefile in hsdis: find the line $(CC) $(OUTFLAGS) $(CPPFLAGS) $(CFLAGS) $(SOURCE) $(DLDFLAGS) $(LIBRARIES) for the $(TARGET) target and append to the end -lz -L$(TARGET_DIR)/zlib, then run the build command again;

*after that you should find the library hsdis-amd64.dll in hsdis\build\Linux-amd64\ for x64, or hsdis-i386.dll in hsdis\build\Linux-i586\ for x86.


text:
Q: When to use a Array() over Generic.Lists in .NET when is it appropriate to use an array over a Generic List(of T) in .NET
I have struggled to see any benefit an array provides over the Generic List but get the feeling I may be missing something. Performance is one thing that struck me as one potential bottleneck ?
Thanks

A: When you are using a fixed number of a given type of object there's no point in taking the small performance hit associated with the List class as you won't use any of its features.

A: I will now shamelessly copypaste my edited answer for a very similar question asked here today:

I would like to point it out that
  while arrays have covariance, generic
  lists do not. For example, an array of
  type MyChildClass[] can be easily
  casted to MyParentClass[], while
  List<MyChildClass> cannot be casted
  to List<MyParentClass>, at least not
  directly.
If you need covariance, either use
  arrays, use LINQ's Cast() method or
  some other means to cast each item
  individually.

A: Another reason to use regular arrays, is when you are working with platform invoke (execute unmanaged c/c++ code), but this is limited to a very small set of applications
Also, as a remark: if the size of the array is known but you still want to use a generic list, don't forget to pass the size to the capacity parameter of the constructor.
for example:
List<int> lst = new List<int> (100);

Otherwise, the list will start with a very small capacity, and will several times need to allocate new chunks of memory, instead of allocating the required space at once.

A: Many of the higher level data structures (including List) use arrays internally, it's the only way to store a raw sequence in memory - so array have to exist in the programing language, otherwise you wouldn't have higher level data structures.
My opinion is that unless you have to (for example because you are using a component that requires it) you should never use arrays - especially don't write code that returns arrays are accept arrays as parameters, so you don't force others to use arrays too.
The only exception (in my opinion) is the rare case you need a collection of a known fixed size as a local variable than it's just seems wasteful to use something else.

A: If you want to cache a fixed number of data, use arrays.  Otherwise, use Generic lists...they are just easier to use, provide more flexibility, and are typed (no need for boxing/unboxing)...simple as that.  Also, an array is a fixed length while lists can be variable and change whenever you like.  The reasons can go on and on why to use a generic list vs. an array.  Arrays are just a pain in the ass. And honestly the performance hit using a list vs. an array can probably be debated to the nth degree


text:
Q: Risk of compromised Amazon SES SMTP Credentials? I host www.foo.com for a client. The website sends emails via postfix which has my Amazon SES SMTP Credentials configured and my SES has foo.com as
a verified domain and this all works fine.
Now the client wants to send emails from her gmail account as sally@foo.com (using gmail's "add another email address that you own" feature) so she has asked for the SMTP credentials.  Other than hitting the sending limits of my SES account, what are the other risks if I share the smtp credentials of my SES account with her? Anyone know a better way to satisfy her request?
Possible dupe of If my SES SMTP credentials are compromised can my SES API usage (using access key+secret) be affected but I'm really looking for a list of other risks and ways to avoid them.

A: Set up a separate AWS account for your client, preferably billed directly to them. Problem solved.

A: Another solution is to create another SMTP user and restrict it to only one From email address.
After creating the SMTP user, head over to IAM console and overwrite the policy with this:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
               "ses:SendRawEmail"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "ses:FromAddress": "noreply@example.com",
                }
            }
        }
    ]
}


text:
Q: dramatic slow down using multiprocess and numpy in python I write a python code for Q-learning algorithm and I have to run it multiple times since this algorithm has random output. Thus I use multiprocessing module. The structure of the code is as follows
import numpy as np
import scipy as sp
import multiprocessing as mp
# ...import other modules...

# ...define some parameters here...

# using multiprocessing
result = []
num_threads = 3
pool = mp.Pool(num_threads)
for cnt in range(num_threads):
    args = (RL_params+phys_params) # arguments
    result.append(pool.apply_async(Q_learning, args))

pool.close()
pool.join()

There is no I/O operation in my code and my work station has 6 cores (12 threads) and enough memory for this job. When I run the code with num_threads=1, it takes me only 13 seconds and this mission only occupies 1 thread with CPU usage 100% (using top command).
click to see picture of CPU status
However, if I run it with num_threads=3 (or more), it shall takes more than 40 seconds and this mission will occupy 3 threads with each thread use 100% CPU core.
click to see picture of CPU status
I can't understand this slowing down because there is no parallelization in all self-defined functions and no I/O operation. It is also interesting to notice that when num_threads=1, CPU usage is always less than 100%, but when num_threads is larger than 1, CPU usage may sometimes be 101% or 102%.
On the other hand, I wrote another simple test file which does not import numpy and scipy, then this problem never show. I have noticed this question why isn't numpy.mean multithreaded? and it seem my problem is due to the automatic parallelization of some methods in numpy (such dot). But as I shown in the pictures, I can't see any parallelization when I run a single job.

A: When you use a multiprocessing pool, all the arguments and results get sent through pickle. This can be very processor-intensive and time-consuming. That could be the source of your problem, especially if your arguments and/or results are large. In those cases, Python may spend more time pickling and unpickling the data than it does running computations.
However, numpy releases the global interpreter lock during computations, so if your work is numpy-intensive, you may be able to speed it up by using threading instead of multiprocessing. That would avoid the pickling step. See here for more details: https://stackoverflow.com/a/38775513/3830997


text:
Q: Calling a method that returns a URL in groovy script def publishVersion() {
    def Payload = versionPayload()
    def response = httpRequest(
        customHeaders: [
            [ name: "Authorization", value: "Bearer " + env.BEARER_TOKEN ],
            [ name: "Content-Type", value: "application/vnd.api+json" ]
        ],
        httpMode: 'POST',
        requestBody: "${Payload}",
        url: "https://app.terraform.io/api/v2/organizations/my-organization/registry-modules/private/my-organization/vnet/provider/versions"
    )
    def data = new JsonSlurper().parseText(response.content)
    println ("Run Id: " + data.data.links.upload)
    return data.data.links.upload
}
def UPLOAD
UPLOAD = sh(
        '''curl \
        --header "Content-Type: application/octet-stream" \
        --request PUT \
        --data-binary @module.tar.gz \
        data.data.links.upload
        '''
)

I am trying to create a module version in Terraform cloud. The publishVersion() method will invoke the API call and part of the API response is a URL where the module will be uploaded. And  that URL is what publishVersion() is returning as data.data.links.upload. The URL returned by the publishVersion() method, I am trying to upload the module.tar.gz  to the URL by using the UPLOAD method in the last part. "it says could not resolve host."

A: Probably you have to do something like the below.
def URL = publishVersion()
UPLOAD = sh(
        """curl \
        --header "Content-Type: application/octet-stream" \
        --request PUT \
        --data-binary @module.tar.gz \
        ${URL}
        """
)


text:
Q: Background Image won't show in div This is my HTML Code

.jumbotron
    {
     background-image: url("file://C:\xampp\htdocs\CSProject\images\Psi.png");
     height: 250px;
     width: 250px;
    }
<!DOCTYPE html>
    <html>
     <head>
      <link rel="stylesheet" href="stylesheet.css">
     </head>

     <body>
      <div class="jumbotron">
      </div>
     </body>
    </html>

I haven't been able to find any solutions as to why this background image won't show.
Thanks for any help or info.

A: The URL for background-image needs to path from your CSS file, not from your root directory.
So if your CSS file is contained in the folder CSProject, try changing:
.jumbotron {
  background-image: url("images/Psi.png");
}

A: It has something to do with your image path...like Erez recommended i would use a relative path.
If your HTML code and 'images' folder are within the 'CSProject' folder,  then reference that image like
background-image:url('/images/Psi.png');

Which brings me to my next point, why is your file-path using backslashes? it should be
 /htdocs/CSProject/images/Psi.png


text:
Q: Ethernet not detected in Ubuntu 16.04 LTS I am a new to Linux. I cannot get a LAN connection in Ubuntu 16.04 LTS. It used to work in Windows 7.
Here is the result from if config -a
enp0s25   Link encap:Ethernet  HWaddr f0:de:f1:2c:0c:ce
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:20 Memory:f8500000-f8520000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:93790 errors:0 dropped:0 overruns:0 frame:0
          TX packets:93790 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:8114335 (8.1 MB)  TX bytes:8114335 (8.1 MB)

wlp3s0    Link encap:Ethernet  HWaddr 00:24:d7:69:9f:28
          inet addr:192.168.0.9  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: 2606:a000:4dc4:e300:9058:8ec2:f59e:27d8/64 Scope:Global
          inet6 addr: fe80::6476:3f7c:2c08:839a/64 Scope:Link
          inet6 addr: 2606:a000:4dc4:e300:72bc:fcf9:87c9:a0b1/64 Scope:Global
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:225018 errors:0 dropped:1 overruns:0 frame:0
          TX packets:118451 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:86856712 (86.8 MB)  TX bytes:17154818 (17.1 MB)

Here is the output from lspci
00:00.0 Host bridge: Intel Corporation Core Processor DRAM Controller (rev 02)
00:01.0 PCI bridge: Intel Corporation Core Processor PCI Express x16 Root Port (rev 02)
00:02.0 VGA compatible controller: Intel Corporation Core Processor Integrated Graphics Controller (rev 02)
00:16.0 Communication controller: Intel Corporation 5 Series/3400 Series Chipset HECI Controller (rev 06)
00:19.0 Ethernet controller: Intel Corporation 82577LM Gigabit Network Connection (rev 06)
00:1a.0 USB controller: Intel Corporation 5 Series/3400 Series Chipset USB2 Enhanced Host Controller (rev 06)
00:1b.0 Audio device: Intel Corporation 5 Series/3400 Series Chipset High Definition Audio (rev 06)
00:1c.0 PCI bridge: Intel Corporation 5 Series/3400 Series Chipset PCI Express Root Port 1 (rev 06)
00:1c.1 PCI bridge: Intel Corporation 5 Series/3400 Series Chipset PCI Express Root Port 2 (rev 06)
00:1c.3 PCI bridge: Intel Corporation 5 Series/3400 Series Chipset PCI Express Root Port 4 (rev 06)
00:1c.4 PCI bridge: Intel Corporation 5 Series/3400 Series Chipset PCI Express Root Port 5 (rev 06)
00:1d.0 USB controller: Intel Corporation 5 Series/3400 Series Chipset USB2 Enhanced Host Controller (rev 06)
00:1e.0 PCI bridge: Intel Corporation 82801 Mobile PCI Bridge (rev a6)
00:1f.0 ISA bridge: Intel Corporation QM57 Chipset LPC Interface Controller (rev 06)
00:1f.2 SATA controller: Intel Corporation 5 Series/3400 Series Chipset 6 port SATA AHCI Controller (rev 06)
00:1f.3 SMBus: Intel Corporation 5 Series/3400 Series Chipset SMBus Controller (rev 06)
00:1f.6 Signal processing controller: Intel Corporation 5 Series/3400 Series Chipset Thermal Subsystem (rev 06)
01:00.0 VGA compatible controller: NVIDIA Corporation GT218M [NVS 3100M] (rev a2)
03:00.0 Network controller: Intel Corporation Centrino Ultimate-N 6300 (rev 35)
0d:00.0 SD Host controller: Ricoh Co Ltd MMC/SD Host Controller (rev 01)
0d:00.1 System peripheral: Ricoh Co Ltd R5U2xx (R5U230 / R5U231 / R5U241) [Memory Stick Host Controller] (rev 01)
0d:00.3 FireWire (IEEE 1394): Ricoh Co Ltd R5C832 PCIe IEEE 1394 Controller (rev 01)
ff:00.0 Host bridge: Intel Corporation Core Processor QuickPath Architecture Generic Non-core Registers (rev 02)
ff:00.1 Host bridge: Intel Corporation Core Processor QuickPath Architecture System Address Decoder (rev 02)
ff:02.0 Host bridge: Intel Corporation Core Processor QPI Link 0 (rev 02)
ff:02.1 Host bridge: Intel Corporation 1st Generation Core i3/5/7 Processor QPI Physical 0 (rev 02)
ff:02.2 Host bridge: Intel Corporation 1st Generation Core i3/5/7 Processor Reserved (rev 02)
ff:02.3 Host bridge: Intel Corporation 1st Generation Core i3/5/7 Processor Reserved (rev 02)

And here is the output from sudo lshw -C network
  *-network
       description: Ethernet interface
       product: 82577LM Gigabit Network Connection
       vendor: Intel Corporation
       physical id: 19
       bus info: pci@0000:00:19.0
       logical name: enp0s25
       version: 06
       serial: f0:de:f1:2c:0c:ce
       capacity: 1Gbit/s
       width: 32 bits
       clock: 33MHz
       capabilities: pm msi bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=e1000e driverversion=3.2.6-k firmware=0.12-1 latency=0 link=no multicast=yes port=twisted pair
       resources: irq:25 memory:f8500000-f851ffff memory:f8525000-f8525fff ioport:1820(size=32)
  *-network
       description: Wireless interface
       product: Centrino Ultimate-N 6300
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: wlp3s0
       version: 35
       serial: 00:24:d7:69:9f:28
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=iwlwifi driverversion=4.10.0-32-generic firmware=9.221.4.1 build 25532 ip=192.168.0.9 latency=0 link=yes multicast=yes wireless=IEEE 802.11
       resources: irq:30 memory:f8100000-f8101fff

I don't really know how to interpret those results in terms of troubleshooting, but I would appreciate any help that you could provide.
Update
I am sorry for the poor explanation. Ubuntu is not detecting the the fact that it is connected (i.e., it says "Wire Unplugged"). The ethernet port lights are off.
Here is the output from  dmesg | grep -e e100 -e enp
 dmesg | grep -e e100 -e enp
[    1.253294] e1000e: Intel(R) PRO/1000 Network Driver - 3.2.6-k
[    1.253294] e1000e: Copyright(c) 1999 - 2015 Intel Corporation.
[    1.253459] e1000e 0000:00:19.0: Interrupt Throttling Rate (ints/sec) set to dynamic conservative mode
[    1.411004] e1000e 0000:00:19.0 eth0: (PCI Express:2.5GT/s:Width x1) f0:de:f1:2c:0c:ce
[    1.411007] e1000e 0000:00:19.0 eth0: Intel(R) PRO/1000 Network Connection
[    1.411083] e1000e 0000:00:19.0 eth0: MAC: 9, PHY: 10, PBA No: A002FF-0FF
[    1.411697] e1000e 0000:00:19.0 enp0s25: renamed from eth0
[   20.756979] IPv6: ADDRCONF(NETDEV_UP): enp0s25: link is not ready
[   20.954637] IPv6: ADDRCONF(NETDEV_UP): enp0s25: link is not ready

A: It is detected. It's enp0s25. You just don't have an IP address. Look in Settings -> Network -> Wired and turn on dhcp


text:
Q: Why is left side constant omitted when solving differential equation using separation method? What happened to the left side constant when Solving differential equation using separation method?
$$\frac{dy}{dx}=y$$
$$\frac{dy}{y}=dx$$
$$\int\frac{dy}{y}=\int dx$$
$$ln\left(\left|y\right|\right)=x+C_2$$
$$y=e^{x+C_2}=Ce^x$$
However,
$$\int \:1dx=x+C_2$$
and
$$\int \frac{1}{y}dy=\ln \left|y\right|+C_1$$
So I would write:
\begin{align*}
 ln\left(\left|y\right|\right)+C_1&=x+C_2\\
 ln\left(\left|y\right|\right)&=x+C_2-C_1\\
 \left|y\right|&=e^{x+C_2-C_1}
\end{align*}
So what happened to $C_1$ ?
Also, why $e^{x+C_2}=e^{C_2}e^x$ is equal to $Ce^x$ ?
Finally, why the solution is  $y=Ce^x$ not $y=-Ce^x$ if $C$ is arbitrary ?

A: Constants are arbitrary. You can call $C_2=C_2-C_1$, or $C=e^{C_2}$, without loss of generality. They are defined with a boundary condition, until then the solution works for every number you plug in for $C_1$, $C_2$ or $C$.


text:
Q: MySql avg() function not returning correct value I am learning about the average function and tried it as follows:
Account Table using open_emp_id field:
+-------------+
| open_emp_id |
+-------------+
|           1 |
|           1 |
|           1 |
|           1 |
|           1 |
|           1 |
|           1 |
|           1 |
|          10 |
|          10 |
|          10 |
|          10 |
|          10 |
|          10 |
|          10 |
|          13 |
|          13 |
|          13 |
|          16 |
|          16 |
|          16 |
|          16 |
|          16 |
|          16 |
+-------------+

My SQL query:
SELECT avg(open_emp_id)
FROM account;

My Result:
+------------------+
| avg(open_emp_id) |
+------------------+
|           8.8750 |
+------------------+

How is the result not 10?
(1+ 10 + 13 + 16) / 4 = 10

A: The avg(expression) function returns the average of all input values.
You have 8 1's = 8
You have 7 10s = 70
You have 3 13's = 39
You have 6 16's = 96
All the above added together is 213.
You have a total of 24 input elements hence, 213 / 24 = 8.875


text:
Q: linux: truecrypt/veracrypt/luks/etc without /dev/loop* I'm using a linux system without any /dev/loop* devices and without the loop module compiled into the kernel, and I don't have the option of upgrading the system or kernel. I want to use luks, truecrypt, veracrypt, or something similar to create a file that gets mounted as an encrypted partition. Is there any way to do this without the kernel loop module?
My system doesn't even have a loop module to load via modprobe.
Any thoughts or suggestions?
Thank you very much.

A: The loop device is the logical point to add disk encryption.
If you don't have a loop module, find the sources for the kernel version you are using, try to find or guess the configuration, and compile a loop module yourself.


text:
Q: CMake: Instruct compiler to ignore warnings from libs folder I'm trying to specify to the compiler to ignore all messages + warnings originating from the libs folder, where I keep my external libraries used in my project.
The LLVM library is the main cause of the problem, since the warnings produced fill up the entire screen making it very difficult for me to efficiently identify compile-time errors, etc.
I'm using CMake and have my LLVM 9.0.0 library under the libs folder. I would like to instruct the compiler (using CMake) to ignore all warnings and messages originating from the libs folder.
This is my CMakeLists.txt file:
# General project settings.
cmake_minimum_required(VERSION 3.12.4)
project(ionir)

# Setup compiler flags.
set(CMAKE_CXX_STANDARD 17)

# General project information.
set(PROJECT_URL "https://github.com/ionlang/ir-c")

# Setup source and build directories.
set(SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(BIN_DIR ${CMAKE_CURRENT_BINARY_DIR})

option(USE_MD "Use MD instead of MTd" OFF)

if (USE_MD)
    set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MD")
    #set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
endif(USE_MD)

set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd")

# Setup versioning.
set(VERSION_MAJOR "1")
set(VERSION_MINOR "0")
set(VERSION_PATCH "0")
set(VERSION "$(VERSION_MAJOR).$(VERSION_MINOR).$(VERSION_PATCH)")

# Configure and use LLVM. Also ensures LLVM 9.0.0 is installed.
find_package(LLVM 9.0.0 EXACT REQUIRED CONFIG)

message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}")
message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}")

# Include LLVM source directories (for syntax support, etc.). The SYSTEM symbol supposedly marks the directory to supress warnings.
include_directories(SYSTEM ${LLVM_INCLUDE_DIRS}) #---> COMMENTED TO SOLVE CIRCULAR DEPS. PROBLEM.
add_definitions(${LLVM_DEFINITIONS})

# Disable warnings from includes.
#add_library(llvm INTERFACE)
#target_sources(llvm INTERFACE)
#target_include_directories(llvm PRIVATE include/ SYSTEM INTERFACE include/)

# Set source file(s).
file(GLOB_RECURSE SOURCES
    "src/*.h"
    "src/*.cpp"
)

# Specify that this project is a library.
add_library(${PROJECT_NAME} ${SOURCES})

# Provide include directories to be used in the build command. Position in file matters.
#target_include_directories(${PROJECT_NAME} PRIVATE "src")
include_directories("src")

# Find the libraries that correspond to the LLVM components
# that we wish to use
# llvm_map_components_to_libnames(llvm_libs support core irreader)

# Link against LLVM libraries.
target_link_libraries(${PROJECT_NAME} ${llvm_libs})

# Setup unit testing using Google Test (GTest) if applicable. This binds the CMakeLists.txt on the test project.
option(BUILD_TESTS "Build tests" ON)

if (BUILD_TESTS)
    add_subdirectory(libs/googletest)
    add_subdirectory(test)
endif()

And below is some of the warnings/messages I'm receiving that are filling up the console.

How can I accomplish this?


text:
Q: Внедрение списка зависимостей с помощью контейнера Castle.Windsor В качестве IoC-контейнера используется Castle.Windsor.
Корневой элемент приложения - планировщик Scheduler, который выполняет в определенной последовательности различные задания. Задания реализуют интерфейс IWorker, поэтому я решил внедрить(inject) List<IWorker> в Scheduler(список заданий). Впоследствии, планируется много различных типов заданий, сейчас их два: Cleaner и Writer. Cleaner нужен в одном экземпляре, используем Синглтон.
Необходимо правильно внедрить N экземпляров Writer, где N - количество XML файлов в поддиректории приложения. Каждый из XML-файлов надо десериализовать и передать в качестве входного параметра каждому Writerу. Т.е. надо внедрить в Schedulerимплементацию для каждого XML. Как это правильно реализовать? Вообще какой паттерн используется в таком случае? Фабрика?
Конфигурация контейнера Castle.Windsor:
var container = new WindsorContainer();
// Для внедрения List
container.Kernel.Resolver.AddSubResolver(new ListResolver(container.Kernel, true));
// Регистрация Scheduler
container.Register(CastleRegistration.Component.For<IScheduler>().ImplementedBy<Scheduler>);
// Регистрация Workers...
container.Register(CastleRegistration.Component.For<IWorker>().ImplementedBy<Writer>());
container.Register(CastleRegistration.Component.For<IWorker>().ImplementedBy<Writer>());
// ...количество зависит от количества файлов + каждому надо передать десериализованный XML в качестве параметра
container.Register(CastleRegistration.Component.For<IWorker>().ImplementedBy<Cleaner>());
// Забираем Scheduler
var sched = container.Resolve<IScheduler>();

Scheduler:
public class Scheduler : IScheduler
{
    public IList<IWorker> Workers { get; set; }

    public Scheduler(IList<IWorker> workers)
    {
        Workers = workers;
    }
}

Writer:
public class Writer : IWorker
{
    public string Source { get; set; }

    public Writer()
    {
    }

    public Writer(string source)
    {
        Source = source;
    }
}

Cleaner:
public class Cleaner : IWorker
{
    public Cleaner()
    {
    }
}

UPDATE:
Дополнительный вопрос:
Содержимое Xml-файлов переехали в одну из таблиц БД. В Scheduler (корневой компонент) нужно внедрить по Writerу с параметром на каждую запись в таблице. Из полезного совета в ответе(Andrew Prigorshnev), следует, что обращаться к БД будет правильным после настройки контейнера и получения из него корневого компонента.
С точки зрения архитектуры, правильным ли будет внедрить в Scheduler компоненты: WriterFactoryи Repository(слой доступа к БД), после чего получить экземпляр Scheduler, затем в нем с помощью Repository получить список параметров, а потом сделать на каждый параметр по Writerу с помощью WriterFactory?

A: Насколько я понимаю в наиболее общем виде вопрос состоит в следующем: как правильно внедрить список зависимостей с помощью контейнера Castle Windsor?
Ответ следующий. Сам подход с внедрением списка через конструктор вполне корректный и Castle Windsor умеет работать с такими сценариями. Чтобы внедрить список зависимостей надо сделать следующее:

*

*Зарегистрировать в контейнере резолвер списков. Вы это уже сделали в строчке container.Kernel.Resolver.AddSubResolver(new ListResolver(container.Kernel, true));

*Зарегистрировать в контейнере несколько компонентов, которые должны быть внедрены в виде списка. При этом если вы внедряете список типа IList<IWorker> контейнер добавит в список все компоненты типа IWorker, которые вы зарегистрируете. Это вы сделали частично. В вашем примере не учтено, что когда вы регистрируете несколько одинаковых компонентов они должны быть именованными (делается с помощью метода .Named()), и по всей видимости вы не знаете как внедрить строку в конструктор компонента - это делается с помощью метода .DependsOn()
Таким образом правильная реализация вашей задачи должна выглядеть вот так:
        var container = new WindsorContainer();

        // Для внедрения List
        container.Kernel.Resolver.AddSubResolver(new ListResolver(container.Kernel, true));

        // Регистрация Scheduler
        container.Register(Component.For<IScheduler>().ImplementedBy<Scheduler>());

        // Writers
        container.Register(Component
            .For<IWorker>()
            .ImplementedBy<Writer>()
            .DependsOn(Dependency.OnValue("source", "files/first.xml"))
            .Named("firstWriter"));

        container.Register(Component
            .For<IWorker>()
            .ImplementedBy<Writer>()
            .DependsOn(Dependency.OnValue("source", "files/second.xml"))
            .Named("secondWriter"));

        container.Register(Component
            .For<IWorker>()
            .DependsOn(Dependency.OnValue("source", "files/third.xml"))
            .ImplementedBy<Writer>()
            .Named("thirdWriter"));

        // Cleaner
        container.Register(Component.For<IWorker>().ImplementedBy<Cleaner>());

        // Забираем Scheduler
        var scheduler = container.Resolve<IScheduler>();

И еще несколько замечаний, касающихся конкретно вашей реализации:

*

*Вы хотите передавать в воркеры xml, но это плохая идея. Тогда вам придется прочитать его из файла прямо в корне компоновки, в том месте где вы настраиваете контейнер. Но чтение из файла это отдельная задача, никак не связанная с разрешением зависимостей, поэтому делать ее в корне компоновки не стоит. Пусть этим занимается один из ваших компонентов. В связи с этим, в примере кода выше вы можете увидеть что во Writer'ы передается путь к файлу, а не его содержимое.

*Если файлы, которые вы обрабатывате меняются редко и их имена и количество известны на этапе написания кода, пример приведенный выше может вас полностью устроить. Но если это не так, надо сделать еще немного дополнительной работы, и как вы правильно предположили, надо использовать фабрики. Возможное решение здесь следующее. Надо добавить новую абстракцию - поставщик воркеров, который будет представлять собой фабрику, создающую воркеры:
 public interface IWorkersProvider
 {
    IEnumerable<IWorker> GetWorkers();
 }

Поставщик Cleaner'ов будет просто возвращать один Cleaner.  А поставщик Writer'ов может получать как аргумент конструктора путь к папке, в которой надо искать файлы, и затем в методе GetWorkersсоздавать по одному воркеру на каждый найденный файл:
public class WritersProvider : IWorkersProvider
{
    public WritersProvider(string folderPath)
    {
    }

    public IEnumerable<IWorker> GetWorkers()
    {
        // здесь создаем по одному воркеру на каждый найденный файл
    }
}

При такой архитектуре ваш Sheduler должен получать вместо списка воркеров, список поставщиков воркеров:
public class Scheduler : IScheduler
{
    public Scheduler(IList<IWorkersProvider> providers)
    {
        // здесь надо опросить все поставщики, чтобы сформировать
        // список воркеров
    }
}

Регистрация такой конфигурации в Castle Windsor делается с помощью тех же методов, что и регистрация в первом примере, поэтому не буду здесь ее описывать.
UPDATE: Ответ на дополнительный вопрос
Лучше сделать так:

*

*В Scheduler внедрить список поставщиков воркеров (IEnumerable<IWorkersProvider>), как описано выше

*Внедрить Repository в конструктор WritersProvider и уже во WritersProviderопрашивать базу данных

Идея здесь вот в чем. Каждый класс должен выполнять одну единственную задачу. Задача Scheduler-а взять готовый список воркеров и запустить их. Задача поставщиков воркеров - создать воркеры на основе какого-то правила (из xml-файлов, таблиц бд и т.д.). Разделив обязанности таким образом, вы получите код, который легко модифицировать. Если вы захотите поменять что-то в логике запуска воркеров, вы прийдете и поменяете только один класс - Scheduler, при этом вы будете уверены, что вы никак не сломали логику создания воркеров, потому что эту работу выполняют совсем другие классы.
Потенциально у вас может быть множество поставщиков воркеров, работающих по разным правилам. Один поставщик может всегда возвращать один и тот же жестко закодированный воркер, второй создавать по воркеру на каждый xml-файл в какой-нибудь директории, третий создавать воркеры на основе таблицы в базе данных, четвертый получать список воркеров, которые надо создать, у удаленного сервиса и т.д. Более того, в процессе развития проекта у поставщика воркеров может меняться  правило, по которому он создает воркеры (у вас это уже произошло -  вместо xml-файлов у вас теперь таблица в бд.)
Если поставщику воркеров для выполнения его работы нужен доступ к бд, внедряйте Repository прямо в поставщик. Если потом это правило изменится, прийдете и поменяете только конкретный поставщик, не трогая другие поставщики и не трогая Scheduler.
Вариант с фабрикой похуже, но тоже годится. Но если будете внедрять фабрику воркеров то Repository внедряйте уже в нее, а не в Scheduler.
Фабрика хуже, потому что, когда количество воркеров вырастет, вы все равно будете вынуждены разнести создание воркеров разных типов по отдельным классам, иначе фабрика будет слишком большой и запутанной. В итоге вы все равно создадите несколько фабрик (что полность аналогично моему варианту со списком поставщиков воркеров, отличие только в названии, фабрика и поставщик в данном случае одно и то же).


text:
Q: Change Kendo Grid DataSource specific field with jQuery I'm new to Kendo UI and would appreciate your advice.
I have a Partial view that renders Kendo Grid:

    @Html.Partial("AccountsGrid", context.CustomerAccounts)

The view: AccountsGrid.cshtml
@model IEnumerable<DAL.Model.CustomerAccount>

    @(Html.Kendo().Grid(Model)
      .Name("AccountsGrid")
      .Columns(columns =>
      {
          columns.Bound(u => u.CUSTOMER_NO)
          ...
      })
     .Pageable().HtmlAttributes(new {id="AccGrid" })
    )

My first problem is when I try to access the grid:
var grid = $("#AccGrid").data("kendoGrid");

It is undefined. Can it be because of hidden Partial?
And second- I would like to change existing dataSource for context.CustomerAccounts.Where(c=>c.CUSTOMER_NO == someValue) dynamically but cannot find a solution.

A: And you can use json + jQuery for the change your data source
var grid = $("#AccountsGrid").data("kendoGrid");
grid.setDataSource(dataSource);


text:
Q: How to reset the cornerstone viewport when new image is loaded I am trying to make a Dicom viewer app in react using Cornerstone.js library. I have two components in my react app. One is ImagePreview and the other is CornerStoneElement. CornerStoneElement is where I initialize the cornerstone library and it loads the current image in its state. When a new image is pushed to CornerStoneElement's state it is loading the new image in a weird way as all the aspect ratios are gone and the viewport is zoomed in. Upon switching the image multiple times through ImagePreview, the viewport keeps getting bigger and bigger. What I need is to reset the viewport whenever a new image is loaded in the CornerStoneElement component. Here is the code for both components.
ImagePreview.js
import React,{useState,useEffect,useRef} from 'react'

const ImagePreview = ({ image,parentStateSetter,imageListIndex }) => {

let setParentState = (e) => {
parentStateSetter(e.target.getAttribute('image-list-index'));

 }

return (

   );
}

export default ImagePreview

CornerStoneElement.js
import React,{useState, setState, useRef, useEffect} from "react";
import * as cornerstone from "cornerstone-core";
import * as cornerstoneMath from "cornerstone-math";
import * as cornerstoneTools from "cornerstone-tools";

import Hammer from "hammerjs";
import * as cornerstoneWebImageLoader from "cornerstone-web-image-loader";

cornerstoneTools.external.cornerstone = cornerstone;
cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
cornerstoneWebImageLoader.external.cornerstone = cornerstone;
cornerstoneTools.external.Hammer = Hammer;

cornerstoneTools.init();

const CornerStoneElement = (props) => {

    console.log('props is called', props);
    const stack = (Object.keys(props.stack).length > 0 )? props.stack : '';
    const [viewport, setViewport] = useState(cornerstone.getDefaultViewport(null, undefined));
    const imageId  = (Object.keys(props.stack).length > 0 )? props.stack.imageIds[0] : '';;
    const viewPortRef = useRef(null);

    const onWindowResize = () => {
        console.log("onWindowResize :", viewPortRef.current);
        cornerstone.resize(viewPortRef.current);
    }

    const onImageRendered = () => {
        const viewport = cornerstone.getViewport(viewPortRef.current);
        console.log('onImageRendered :',viewport);
        setViewport(viewport);

    }

    const onNewImage = () => {
        const enabledElement = cornerstone.getEnabledElement(viewPortRef.current);

    }

    const addZoomTool = (e) => {
      e.preventDefault();
      const ZoomMouseWheelTool = cornerstoneTools.ZoomMouseWheelTool;

      cornerstoneTools.addTool(ZoomMouseWheelTool)
      cornerstoneTools.setToolActive('ZoomMouseWheel', { mouseButtonMask: 1 })
    }

    const addLengthTool = (e) => {
      e.preventDefault();
      const LengthTool = cornerstoneTools.LengthTool;

      cornerstoneTools.addTool(LengthTool)
      cornerstoneTools.setToolActive('Length', { mouseButtonMask: 1 });
    }

    const addElipticalTool = (e) => {
      e.preventDefault();
      const EllipticalRoiTool = cornerstoneTools.EllipticalRoiTool;

      cornerstoneTools.addTool(EllipticalRoiTool)
      cornerstoneTools.setToolActive('EllipticalRoi', { mouseButtonMask: 1 })
    }

    useEffect(() => {

        console.log('use effect is called ');

        const element = viewPortRef.current;
        // Enable the DOM Element for use with Cornerstone

        cornerstone.enable(element);

        // Load the first image in the stack
        if(imageId){

          cornerstone.loadImage(imageId).then(image => {
            // Display the first image

            cornerstone.displayImage(element, image);
            // Add the stack tool state to the enabled element
            /* cornerstoneTools.addStackStateManager(element, ["stack"]);
            cornerstoneTools.addToolState(element, "stack", stack);    */

            element.addEventListener( "cornerstoneimagerendered", onImageRendered );
            element.addEventListener("cornerstonenewimage", onNewImage);
            window.addEventListener("resize",onWindowResize);
          });
          console.log('inside comp will mount :', element);
        }

    }, [imageId])

    return (

            <button className = "text-sm bg-blue-500 hover:bg-blue-700 text-white  p-2 rounded m-2" onClick = {addZoomTool}> Zoom Tool</button>
            <button className = "text-sm bg-blue-500 hover:bg-blue-700 text-white  p-2  rounded m-2" onClick = {addLengthTool}> Length Tool </button>
            <button className = "text-sm bg-blue-500 hover:bg-blue-700 text-white  p-2 rounded m-2" onClick = {addElipticalTool}> Eliptical Tool </button>

            <canvas className="cornerstone-canvas" />

Zoom: {viewport.scale}

              WW/WC: {viewport.voi.windowWidth} /{" "}
              {viewport.voi.windowCenter}

      );
}

export default CornerStoneElement;

A: So the problem was not in cornerstone. All I had to do is assign height to the parent of cornerstone element inside of which it was getting rendered and it solved the issue.


text:
Q: Ambiguous mapping. Cannot map method Spring Boot I have a problem with appropriate mapping to endpoints. I want to get result like this:

*

*When I go to /api/leagues/1 show league with id=1,

*When I go to /api/leagues/spain show league with country="spain",

*When I go to /api/leagues/la liga show league with leagueName="la liga"

my code is like this:
@RestController
@RequestMapping("/api/leagues")
public class LeagueController {

    @Autowired
    private LeagueService leagueService;

    @GetMapping("")
    public List<League> getLeagues() {
        return leagueService.getAllLeagues();
    }

    @GetMapping("/{id}")
    public League getLeagueById(@PathVariable Long id) {
        return leagueService.getLeagueById(id);
    }

    @GetMapping("/")
    public League getLeagueByCountry(@RequestParam(value="country") String country) {
        return leagueService.getLeagueByCountry(country);
    }

    @GetMapping("/")
    public League getLeagueByLeagueName(@RequestParam(value="leagueName") String leagueName) {
        return leagueService.getLeagueByLeagueName(leagueName);
    }

}

However, when running I get the following error message:
Ambiguous mapping. Cannot map 'leagueController' method`

When I change my code like this:
@RestController
@RequestMapping("/api/leagues")
public class LeagueController {

    @Autowired
    private LeagueService leagueService;

    @GetMapping("")
    public List<League> getLeagues() {
        return leagueService.getAllLeagues();
    }

    @GetMapping("/{id}")
    public League getLeagueById(@PathVariable Long id) {
        return leagueService.getLeagueById(id);
    }

    @GetMapping("/")
    public League getLeagueByCountry(@RequestParam(value="country") String country) {
        return leagueService.getLeagueByCountry(country);
    }

}

It works, but then I should use the following endpoint:
/api/leagues?country=spain

But I prefer having this endpoint in stead:
/api/leagues/spain

Can someone explain me how I can solve problem or help me find a solution for the mapping I want? I will be grateful for that.

A: The error is rather clear according to your experimentation.
You cannot have more than one @GetMapping("...") with the same path whatever the signature of the method.
While this code compiles, it is not enough at runtime for Spring :
@GetMapping("/")
public League getLeagueByCountry(@RequestParam(value="country") String country) {
    return leagueService.getLeagueByCountry(country);
}

@GetMapping("/")
public League getLeagueByLeagueName(@RequestParam(value="leagueName") String leagueName) {
    return leagueService.getLeagueByLeagueName(leagueName);
}

not like i want to:
/api/leagues/spain

To get such a mapping where I suppose spain is a country among others : the country information should be specified as a @PathVariable parameter :
@GetMapping("/{country}")
public League getLeagueByCountry(@PathVariable String country) {
    return leagueService.getLeagueByCountry(country);
}


text:
Q: Inverse limit of irreducible spaces Let $(X_{i})_{i \in \mathbb{N}}$ be an inverse system of topological spaces. Assume that each of the $X_{i}$ is irreducible. Then is it true that $\projlim X_{i}$ is also irreducible?
I read in a paper that the inverse limit of irreducible schemes are irreducible, so this is the motivation for the question.


text:
Q: Setting timezone while using jQuery CountDown Currently we have this code, which works, except it needs to use a specified timezone, rather than the user's timezone:
 $('#countdown').countdown('<?php echo $date_end?>').on('update.countdown', function(event) {
            var format = '%-S second%!S';

            if (event.offset.years > 0 || event.offset.weeks > 0 || event.offset.days > 0 || event.offset.hours > 0 || event.offset.minutes > 0) {

                if(event.offset.minutes > 0) {
                    format = '%-M minute%!M ' + format;
                }
                if(event.offset.hours > 0) {
                    format = '%-H hour%!H ' + format;
                }
                if(event.offset.days > 0) {
                    format = '%-d day%!d ' + format;
                }
                if(event.offset.weeks > 0) {
                    format = '%-w week%!w ' + format;
                }
            }
           $(this).html(event.strftime(format));
        }).on('finish.countdown', function(event) {
           $(this).html('Finished');
        });

I have seen several examples of adding timezones, but none are using the jquery countdown plugin in the same way we are.
Any ideas on how to add +10 as the current timezone? so it uses that rather than the user's timezone?
Thanks.

A: I am guessing you are using https://github.com/hilios/jQuery.countdown, because it doesn't have timezone options to use it.
I used moment.js and moment-timezone-with-data.js(contains all the timezones) to handle timezone.

function to convert the date to proper timezone and returns in milliseconds
var timefun = function (countdown,zone){
 var date = moment.tz(countdown,"YYYY/MM/DD",zone);
 return date.valueOf();
}

make use of the above function to pass milliseconds as an argument to jQuery.countdown()
$(".countdown").countdown(timefun($(".countdown").data("countdown"),$(".countdown").data("zone")))

example:
http://jsfiddle.net/heLrsnqx/2/
if you are using http://keith-wood.name/countdown.html, refer following example
example:
http://jsfiddle.net/w1oyv8kv/

A: Looks like the actual date that is used in the code is coming from that PHP snippet. You can set the default timezone in PHP using:
date_default_timezone_set($timezone_identifier);

$timezone_identifier is a string that can be things like 'UTC' or 'America/Los_Angeles'.
For a full list of supported timezone identifiers, see the related PHP docs.

A: According to the documentation, you can access the finalDate object with event.finalDate. So if you can't set the timezone server side, do event.finalDate.setUTCHours(10) before calling event.strftime
More on setUTCHours here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours


text:
Q: Detect when an element is in the viewport using GSAP ScrollTrigger Plugin I am trying to detect when an element is in the viewport using GSAP3's Scroll Trigger Pluging. However, it doesn't seem to want to work. The terminal is reporting:
"Invalid property" "scrollTrigger" "set to" Object {
  trigger: ".c"
} "Missing plugin? gsap.registerPlugin()"

My JS code is as below:
gsap.registerPlugin(ScrollTrigger);
gsap.to(".box", {
    scrollTrigger: {
        trigger: ".c"
    },
    x: 400,
    rotation: 360
});

Then the HTML is:

  EMPTY

    HELLO

I also came across someone who had a similar issue https://greensock.com/forums/topic/24472-invalid-property-scrolltrigger/ However, even trying solutions from the GreenSock Docs it still doesn't work.


text:
Q: Showing that if $a$ is a transitive set then $\cup a$ is also a transitive set. I am working on a problem in Enderton's text on set-theory that appears to be deceptively easy. It is likely that I making a mistake somewhere so if someone can comment it would be much appreciated.
Question: Show that if $a$ is a transitive set then $\cup a$ is also a transitive set.
Answer so far: Assume that $a$ is a transitive set. By definition, $\cup a = \{x \in y \ |$ for some $y \in a$}. Since $a$ is transitive, whenever we have for every $x \in y \in a$, we have $x \in a$. But these are just the conditions of set $\cup a$. So $\cup a$ is transitive.

A: Suppose $x \in y \in \bigcup a$. By your argument above, $y \in \bigcup a$ implies that $y \in a$. Then $x \in \bigcup a$ by definition of $\bigcup a= \{x : (\exists y \in a)(x \in y)\}$.

A: Suppose that $w\in\cup a$,  then  there is $a_i\in a$, such that $w\in a_i$,  how $a$ is transitive then $w\in a$, and if $x\in w$ then by definition of union $x\in \cup a$.
How $x\in w\in\cup a$ implies $x\in \cup a$, then  $\cup a$ is transitive.


text:
Q: Use PDFDocument properly I can't find any decent sample to use the PDFDocument since API level 19.
The samples mostly show an activity with one text field, and this text field is added to a PDF.
What I want to do
I want to subtract data from my models, create a PDF with this data and show this PDF.
What
What I don't want
I don't want to put TextViews and ImageViews in the layout of the fragment, then put these in a PDFDocument and generate a PDF file.
That seems a bit odd.
The part I don't get
Should I create an XML file where I will fill all my views with the data from my models, then create a PDF from this inflated XML? Is het screensize independent?
Please point me in the right direction!


text:
Q: Cannot install jupyter Every time I load jupyter notebook I get the error:
(venv) C:\Users\Kris\PycharmProjects\HelloWorld>jupyter notebook
'jupyter' is not recognized as an internal or external command,
operable program or batch file.

I reinstalled Pycharm, Python and  Conda but the issue persists.
When running pip install jupyter,  I do get some installation but it errors out at
Collecting MarkupSafe>=0.23 (from jinja2>=2.4->nbconvert->jupyter)
  Downloading https://files.pythonhosted.org/packages/b9/2e/64db92e53b86efccfaea71321f597fa2e1b2bd3853d8ce658568f7a13094/MarkupSafe-1.1.1.tar.gz
Collecting pywin32>=1.0; sys_platform == "win32" (from jupyter-core->nbconvert->jupyter)
  Could not find a version that satisfies the requirement pywin32>=1.0; sys_platform == "win32" (from jupyter-core->nbconvert->jupyter) (from versions: )
No matching distribution found for pywin32>=1.0; sys_platform == "win32" (from jupyter-core->nbconvert->jupyter)

How can I get Jupyter to install?

A: You can try this: python -m pip install jupyter and then python -m jupyter notebook.


text:
Q: Define inflow/s with different depart speeds I want the vehicles in the inflow to drive constant speed but I want this constant speed to change between episodes (let's make this speed uniformly sampled between 10 m/s and 25 m/s).
E.g. in episode #5 all vehicles drive in 12.3 m/s and in episode #6 all vehicles drive in 19.7 m/s.
How can I do that?
Can I do it with only one inflow or do I need an infinite number of inflows, one per speed and change dynamically between them? (which I'm not sure how, anyway)

A: Yes! It's a little tricky but you can make it work. If you look at the reset method on line 988 of the following file (https://github.com/flow-project/flow/blob/master/flow/envs/bottleneck.py) you can see that what we do is create a new set of inflows and then restart the simulation so that the new set of inflows is active. You should be able to add a similar bit of code to your environment to make it work.


text:
Q: How toolbar and fragment background to use one gradient color android kotlin I have a problem with creating screen with one gradient color. I have activity which contains toolbar and container which hold fragments.
 activity.xml:

<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:background="@drawable/main_blue_gradient"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    <RelativeLayout
            android:id="@+id/toolbarTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toTopOf="parent">

        <ImageView
                android:id="@+id/backArrowBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:padding="16dp"
                android:src="@drawable/back_arrow_icon" />

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:padding="16dp"
                android:text="@string/create_resume"
                android:textColor="@color/main_white"
                android:textSize="20sp" />

    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

<RelativeLayout
        android:id="@+id/contentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar">

</RelativeLayout>

The problem comes when i replace container with fragment which has the same color ->
        android:background="@drawable/main_blue_gradient
the result is two different gradient colors:

A: You should make your toolbar transparent and make it overlap the contentContainer. Then in your fragment, you should add a top padding equal to the toolbar height.


text:
Q: UnicodeDecodeError: 'utf8' codec can't decode byte while iterating over json I am a beginner at python. I am trying to use json.loads() in my code to iterate over a json object returned from an API.
The following is the error I am getting:
Traceback (most recent call last):
  File "/Users/Saket/Downloads/Telegram Desktop/update_trbble (2).py", line 209, in <module>
    today_trbbles=json.loads(open_discovery_api)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd8 in position 36: unexpected end of data
logout

I have checked out a few posts and tried to use .encode('utf-8') and also convert to unicode by using the unicode() method. These also are not working.
sample data:
status: 0,
message: "success",
results: {
totalTime: "3 ms",
queryTime: "0 ms",
status: 0,
cursor: "AoJ/spqIs9ICPwU4YzcyNWFlZi1hNjM1LTRiNzEtYjM1Ni02MWQ2MWFlMGQwZWU=",
numFound: 523,
size: 30,
songss: [
{
albumArt: "https://i.scdn.co/image/233728c2073337d67309fd205c6cc028e831d857",
artist: "Arty, Nadia Ali & BT",
docSource: [
"CACHE"
],
commentCount: 0,
createdBy: "wiredmau5",
createdTime: "Fri Jan 22 15:07:45 UTC 2016",
createdUTS: 1453475265411,
createdUserId: "ae186330-5fa5-469c-b1cc-8f3d3b61e538",
downVoteCount: 0,
favouriteCount: 0,
flag1Count: 0,
falg2Count: 0,
flag3Count: 0,
flag4Count: 0,
flag5Count: 0,
flag6Count: 0,
genre: [
"Trance"
],
genrePriority: 0,
hour: 0,
language: "english",
languagePriority: 0,
likeCount: 0,
minute: 0,
modifiedTime: {
time: 1453475748201,
minutes: 15,
seconds: 48,
hours: 15,
month: 0,
year: 116,
timezoneOffset: 0,
day: 5,
date: 22
},

A: Your program is having an issue interpreting the encoding of the output of your API request. First, make sure you have both json and urllib.request imported. Then, you need to open the API URL, in this case, I set the output equal to byte_Obj. Then you will convert the information into ascii text using the .read() and .decode() function. Then, to make your indices integers you will use the .load() function from the json package you imported. Hope this helps!
    import json
    import urllib.request
    byte_Obj = urllib.request.urlopen("API URL Here") #urllib is used to open the URL of the API provided
    json_string = byte_Obj.read().decode("ascii", "ignore") #to decode output into ascii text
    info = json.loads(json_string) #final info with indices as integers


text:
Q: After copying a range of cells, and choosing a new cell, PasteSpecial fails I have tried to solve this seemingly easy problem, but can't find a solution.
I'm trying to copy a selected cell, plus 2 cells that follow, then create a new row and paste the contents in the first cell of the new row.
The first part works fine, After selection the prompt asks if this is the correct cell to copy, then the copy happens, and a new row is created with the first cell selected, but the code fails on the PasteSpecial.
You will see comments of what I tried, in the code, that have not worked.
I'd appreciate any help that is given. Thanks in advance.
Dave
Sub SelectCell_on_RowThenAdd2andAskYorN_AddRow_Paste()

Dim Msg, Style, Response, MyString
    Msg = "Is Job Number the job you wish to copy?"
    Style = vbYesNo
    Response = MsgBox(Msg, Style)

    If Response = vbYes Then   ' User chose Yes.
        MyString = "Yes"   ' Perform some action.

    ActiveCell.Select 'Takes active cell and offsets 1 to the right
    Selection.Resize(Selection.Rows.Count, _
        Selection.Columns.Count + 2).Select ' Resizes selection by 2 rows
        Selection.Copy

    Else   ' User chose No.
        MyString = "No"   ' Perform some action.

    MsgBox "Choose the correct Job Number," & (Chr(13)) & "then Click the Copy Button.", vbOKOnly

    End If

    Dim oNewRow As ListRow
    Set oNewRow = Selection.ListObject.ListRows.Add(AlwaysInsert:=True)
    oNewRow.Range.Cells(1, 1).Select
    'Cells(Selection.Row, 1).Select  --- Did not work
    'ActiveSheet.Paste  --- Did not work
    'Paste Special gives error PasteSpecial Method of Range Class Failed
    Selection.PasteSpecial Paste:=xlValues

End Sub


text:
Q: List files in .7z, .rar and .tar archives using PHP I want to list the files inside an archive, without their extraction.
The types of archives I am interested in:

*

*.7z (7-Zip)

*.rar (WinRAR)

*.tar (POSIX, e.g. GNU tar).

*.zip (ISO standard, e.g. WinZip)

For .zip files, I have been able to achieve this:
<?php
    $za = new ZipArchive();
    $za->open('theZip.zip');
    for ($i = 0; $i < $za->numFiles; $i++) {
        $stat = $za->statIndex($i);
        print_r(basename($stat['name']) . PHP_EOL);
    }
?>

However, I have not managed to do the same for .7z files. Haven't tested .rar and .tar, but will need them as well.

A: Arnuld's comment is a clue as to the most practical way to solve the problem. Even if you can find implementations of all the possible archive types you want to support acessible to PHP, only ZIP and gzip are natively supported by a PHP extension. The remainder will either be native PHP code or shell out to invoke a standalone binary. The former will be a bit of a performance/resource bottleneck while the latter will be dependant on your underlying platform.
(BTW, unless you trust the users completely with access to your server, or are a relatively good programmer, you're going to have to do more inspection of the content than just listing what is inside an uploaded archive).
Once you've collected a ragtag assortment of utilities, and audited the code to a reasonable level, you should then be decorating the implementation with a uniform API to ensure that your glue code doesn't turn into spaghetti.
If it were me, I'd start from scratch implementing an interface like that for PHP's zip around the standalone binaries; PHP is, after all, a scripting language. That you will be applying this to user uploaded files is no reason not to use an existing, native code implementation, indeed, the security consideration is a strong argument for such an approach.
Remember to watch outfor zip bombs.

A: I think this class might help you
Code sample from the link
// Open an archive.
$archive = new SevenZipArchive('docs.7z');

// Show number of contained files:
print $archive->count() . " file(s) in archive\n";

// Show info about the first contained file:
$entry = $archive->get(0);
print 'First file name: ' . $entry['Name'] . "\n";

// Iterate over all the contained files in archive, and dump all their info:
foreach ($archive as $entry) {
    print_r($entry);
}

Update
As promised in my comments and OP asked for one way to check uploaded files against bomb, here is a link that describe it. It is a ClamAV® is an open source antivirus engine for detecting trojans, viruses, malware & other malicious threats source antivirus.
From ClamavNet site I found this information

Whenever a file exceeds ArchiveMaxCompressionRatio (see clamd.conf man
  page), it's considered a logic bomb and marked as Oversized.zip . Try
  increasing your ArchiveMaxCompressionRatio setting.

That said my experience with uploading files comes from typically trusted users. Zip bombs or any other threats, if I was you, I will research it first and find out how a zip bombs/any other threats works, this will help you preventing it through extra coding or solution.
Further more depending on your business size, budget and how critical your web-app is, it is a good idea to make a kind of strategy, policy and roles on your site, which describes the usage of your web-app. A part of that is files uploading policy, like which type of files allowed to be uploaded, what is the maximum size, who can upload and accepting your disclaimer where you mentioning these stuffs etc. that policy should be reflected as guideline to audience using your web-app services.
Here is few links about zip bombs:

*

*How does one make a Zip bomb?

*How can I protect myself from a zip bomb?

*https://en.wikipedia.org/wiki/Zip_bomb

A: Try this
<?php

$x = exec("7z l ./test.zip | awk '/^[0-9]{4}-/{print}'", $l);
foreach($l as $r)
{
    $e = explode(" ", $r);
    $c = count($e)-1;
    echo $e[$c]."\n";
}
?>

A: This is something that has come up before (for various reasons like this and this and the one with broken links in the answer).
Generally the prevailing opinion at the moment is to create a wrapper (either DIY or use a library) which relies on having a 7-zip binary (executable) to be accessible on the server and wrap calls to the binary using exec(), rather than a pure PHP solution.
Since the 7zip format supports a variety of compression algorithms, I'm assuming that you probably want a pure PHP implementation of reading/decompressing the LZMA format. While there are LZMA SDKs available for C, C++, C# and Java and someone has made a PHP Extension for LZMA2 (and a fork for LZMA) as yet even though there has even been interest on the 7-zip forums for quite a while, no one seems to have ported this over as a comprehensive PECL extension or pure PHP yet.
Depending on your needs & motivation, this leaves you with:

*

*add the 7-zip binary to your server, and use a wrapper library, be it your own or someone else's

*install and use an unofficial PECL extension

*bravely port the LZMA SDK to PHP yourself (and hopefully contribute it back to open source!)

For other formats you can look to the PHP documentation for examples and details on usage:

*

*.rar has its own official PECL extension

*.tar can be extracted by the Phar PECL extention (also see SO for examples)

*.zip has an official PECL extension

*.gz has an official PECL exension

*and a couple of other formats
Since all of these involve PECL extensions, if you're limited by your webhost in some way and need pure PHP solutions for this, it might be easier to just shift to a more amenable webhost.
To attempt to protect against zip bombs, you can look at the compression ratios as suggested by this answer (packed size divided by unpacked size and treat anything over a certain threshold as invalid), although the zip bomb talked about the answer to one of the linked questions would indicate that this can be ineffective against multi-layered zip bombs. For those you would need to look at whether or not the files you're listing are archives as well, ensuring you're not doing any kind of recursive extraction and then treat archives that contain archives as invalid.
For completeness, some usage examples for official PECL extensions:
RAR:
<?php
// open the archive file
$archive = RarArchive::open('archive.rar');
// make sure it's valid
if ($archive === false) return;
// retrieve a list of entries in the archive
$entries = $archive->getEntries();
// make sure the entry list is valid
if ($entries === false) return;
// example output of entry count
echo "Found ".count($entries)." entries.\n";
// loop over entries
foreach ($entries as $e) {
    echo $e->getName()."\n";
}
// close the archive file
$archive->close();
?>

TAR:
<?php
// open the archive file
try {
    $archive = new PharData('archive.tar');
}
// make sure it's valid
catch (UnexpectedValueException $e) {
    return;
}
// make sure the entry list is valid
if ($archive->count() === 0) return;
// example output of entry count
echo "Found ".$archive->count()." entries.\n";
// loop over entries (PharData is already a list of entries in the archive)
foreach ($archive as $entry) {
    echo $entry."\n";
}
// no need to close a PharData
?>

ZIP (adapted from OP's question which is from here):
<?php
// open the archive file
$archive = new ZipArchive;
$valid = $archive->open('archive.zip');
// make sure it's valid (if not ZipArchive::open() returns various error codes)
if ($valid !== true) return;
// make sure the entry list is valid
if ($archive->numFiles === 0) return;
// example output of entry count
echo "Found ".$archive->numFiles." entries.\n";
// loop over entries
for ($i = 0; $i < $archive->numFiles; $i++) {
    $e = $archive->statIndex($i);
    echo $e['name']."\n";
}
// close the archive file (redundant as called automatically at the end of the script)
$archive->close();
?>

GZ:
Since gz (gnu Zlib) is a compression mechanism rather than an archive format, this is different in PHP. If you open a .gz file by itself (rather than treating it like a .tar) with gzopen(), any reads from it are transparently decompressed. Since this is most commonly .tar.gz, you can treat it like a .tar as above (also see this answer on another question). Or you can extract the tar with PharData::decompress() as in this answer on another question.


text:
Q: two threads one synchronize method scjp Why is the answer to this letter b? (question and answer below)
I understand 7a 7b 8a 8b, since the method is synchronized hence only one thread could execute at a time, but why is 6a 7a 6b 7b acceptable as well? shouldn't the second thread wait for the first thread to finish with the method?
public class Lockdown implements Runnable {
           public static void main(String[] args) {
             new Thread(new Lockdown()).start();
             new Thread(new Lockdown()).start();
           }
           public void run() { locked(Thread.currentThread().getId()); }
           synchronized void locked(long id) {
             System.out.print(id + "a ");
             System.out.print(id + "b ");
           }
         }

b) Set 7a 7b 8a 8b and set 6a 7a 6b 7b are both possible. (*)

A: That is correct because there are two Lockdown objects and a thread for each one. For example
Lockdown lockk = new Lockdown();
new Thread(lockk).start();  //thread1
new Thread(lockk).start();  //thread2

would cause the threads to wait the first to finish execution. So the result will always be 7a 7b 8a 8b, or something like that. Synchronized methods make threads to wait only if the threads are running on the same object.
But with the threads operating on different objects it may also output 6a 7a 6b 7b. Your example is like
Lockdown lock1 = new Lockdown();
Lockdown lock2 = new Lockdown();
new Thread(lock1).start();  //thread1
new Thread(lock2).start();  //thread2

Output:
thread1 on lock1 print -> 6a
thread2 on lock2 print -> 7a
thread1 on lock1 print -> 6b
thread2 on lock2 print -> 7b

But it can also be:
thread1 on lock1 print -> 6a
thread1 on lock1 print -> 6b
thread2 on lock2 print -> 7a
thread2 on lock2 print -> 7b

So you can get 2 different results.

A: Printing or logging is not the part of synchronization. Read this section completely :
It is similar to question :
Inconsistency in output for Producer Consumer relationship program in Java

A: Did you try running the code?
I did and I got results as
9a 9b 10a 10b

Second time I got
9a 10a 10b 9b

Which means that the threads acquire and release locks arbitrarily. You cannot predict the execution sequence until it really happens.
Note that synchronized keyword guarantees that only one thread access the code block at a time.


text:
Q: outerHeight(true) does not include margins? According to JQuery docs outerHeight(true) function returns the total height of the element including padding border and margins. I ran into a case where this promise seems to be broken. Here is a repro.
here is the html:
outer div height =

ul height (including margins) =

here

and the javascript:
var app = angular.module('application',[]);
app.directive('showHeightIn', function($log){
    return function(scope, element,attrs) {
        $('#' + attrs.showHeightIn).text($(element).outerHeight(true));
    }
});
angular.bootstrap(document, ['application']);

in this example the
 element uses the default style which adds 16px top and bottom margins. This brings outerHeight of the
 to 52px.
Now the parent
 element shows outerHeight(true) only 20px - which does not include either margin.
This question on SO talks about collapsing margins, and I understand the explanation - to a degree. My questions though is not why margins are not included.
My questions is how can I determine the height of the div as rendered. Apparently outerHeight(true) in certain cases is incorrect.
@Gaby: changing element style is not the only way to do that. You can also add 0 height block items before and after. But I am not looking for a way to prevent margin collapsing. I am looking for a universal way to determine the total height occupied by the element. I need this to avoid limitations on usage of my ng-scroll directive.

A: Adding overflow:auto on the div element will disable margin collapsing and the value will be correctly calculated.
Demo at http://jsfiddle.net/hdReR/2/

A: You should separately calculate the container height without margins, then add the max value between the container top+bottom margin and the sum of first-child's margin-top and last-child's margin-bottom.
var mVert = parseInt($('#container').css('margin-top'))
    + parseInt($('#container').css('margin-bottom'));
var mVertChildren = parseInt($('#container').children().first().css('margin-top'))
    + parseInt($('#container').children().last().css('margin-bottom'));

var realHeight = $('#container').outerHeight(false)
    + (mVert > mVertChildren ? mVert : mVertChildren);

Demo at http://jsfiddle.net/j67phdpd/2/


text:
Q: In ActiveAdmin, posting to a collection_action is being attended, actually, by the :create member action I have this ActiveAdmin registration
ActiveAdmin.register User do
  permit_params :first_name, :last_name, :email, :role

  scope :all
  scope :admin
  scope :professor
  scope :student

  config.clear_action_items!

  index do
    id_column
    column :name do |c|
      c.full_name
    end
    column :email
    column :created_at do |c|
      c.created_at.strftime("%Y-%m-%d %H:%M")
    end
    column :role
    column :login_as do |c|
      link_to "login as", login_as_admin_user_path(c.id)
    end
    actions defaults: false do |c|
      item 'Show', admin_user_path(c.id)
      span '  |  '
      item 'Edit', edit_admin_user_path(c.id)
    end
  end

  filter :first_name
  filter :last_name
  filter :email

  form do |f|
    f.inputs do
      f.input :first_name
      f.input :last_name
      f.input :email
      if f.object.new_record?
        f.input :role, as: :select, collection: [['Professor', :professor], ['Student', :student]]
      elsif f.object.admin?
        f.input :role, as: :readonly, display: 'Administrator'
      else
        f.input :role, as: :select, collection: [['Professor', :professor], ['Student', :student], ['Administrator', :admin]]
      end
    end
    f.actions
  end

  action_item :only => :index do
    link_to 'Invite User', new_admin_user_path
  end

  action_item :only => :index do
    link_to 'Bulk Invite Users', bulk_new_admin_users_path
  end

  collection_action :bulk_new, method: :get do
    # Just render - no specific implementation
  end

  collection_action :bulk_create, method: :post do
    # Also tried: raise StandardError.new 'foo'
    render nothing: true
  end

  member_action :create, method: :post do
    pparams = permitted_params[:user]
    @user = User.new(pparams)
    if @user.admin?
      flash[:error] = 'Cannot invite admin users with this method'
      render :new
    else
      @user.avoid_password_validation = true
      if @user.valid?
        @user.invite!(current_user)
        redirect_to admin_user_path(@user.id), notice: "Invitation sent to email: #{@user.email}"
      else
        render :new
      end
    end
  end

  member_action :login_as do
    new_user = User.find(params[:id])
    session["admin_user_id"] = current_user.id
    sign_in(:user, new_user)
    redirect_to root_path
  end

  member_action :resend_activation do
    @user = User.find(params[:id])
    @user.send_confirmation_instructions
  end

  show do
    attributes_table :id, :first_name, :last_name, :email, :role, :encrypted_password, :reset_password_oken, :reset_password_sent_at, :remember_created_at,
                     :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip, :last_sign_in_ip, :invitation_token, :invitation_created_at,
                     :invitation_sent_at, :invitation_accepted_at, :invitation_limit, :invited_by, :invited_by_type, :invitations_count, :created_at,
                     :updated_at
  end
end

And my routes are generated like this:
                         admin_user POST   /admin/users/:id(.:format)                              admin/users#create
                login_as_admin_user GET    /admin/users/:id/login_as(.:format)                     admin/users#login_as
       resend_activation_admin_user GET    /admin/users/:id/resend_activation(.:format)            admin/users#resend_activation
               bulk_new_admin_users GET    /admin/users/bulk_new(.:format)                         admin/users#bulk_new
            bulk_create_admin_users POST   /admin/users/bulk_create(.:format)                      admin/users#bulk_create
           batch_action_admin_users POST   /admin/users/batch_action(.:format)                     admin/users#batch_action
                        admin_users GET    /admin/users(.:format)                                  admin/users#index
                                    POST   /admin/users(.:format)                                  admin/users#create
                     new_admin_user GET    /admin/users/new(.:format)                              admin/users#new
                    edit_admin_user GET    /admin/users/:id/edit(.:format)                         admin/users#edit
                                    GET    /admin/users/:id(.:format)                              admin/users#show
                                    PATCH  /admin/users/:id(.:format)                              admin/users#update
                                    PUT    /admin/users/:id(.:format)                              admin/users#update
                                    DELETE /admin/users/:id(.:format)                              admin/users#destroy

When I reach the /admin/users/bulk_new route, which is just a form hitting /admin/users/bulk_create (Url: bulk_create_admin_users_path, I can verify that for true in the browser itself, with no url wrapping or anything like that meddling), it displays as expected.
However, when I submit (also checking in the browser's Network tab to check no redirections exist - the url is /admin/users/bulk_create), the post request is handled by the :create member action (which fails since no user data was provided) instead of being handled by the :bulk_create collection action.
What am I missing here

A: It looks like an issue with the routes, based on output of rake routes the first of them admin_user POST   /admin/users/:id(.:format)                              admin/users#create have the same format as the one you want to use as bulk_create, and rails is taking as :id bulk_create


text:
Q: Importing data from files designated in an InputString dialog box I want to use a loop to input several strings which will be used to import a file.  The number of strings to be imported will vary, so the loop should recognize the number of strings and stop after say an empty input.  Each iteration will contain a command of the kind:
Import[NotebookDirectory[] <>  StringJoin["start_", InputString[], ".dat"], HeaderLines -> 2]

which would import a file called start_XYX.dat from the notebook directory if the string XYX was entered.
Any help/ideas would be greatly appreciated.

A: This is based on pretty much the same idea as was presented by belisarius in his comment, but is more robust.
First I create two test files
start_test_1.dat
Header 1
Header 2
a b c d

start_test_2.dat
Header 1
Header 2
q w e r t y
1 2 3 4

on my desktop. I then set a path variable (you will, of course, need to set this to the path you want).
path = FileNameJoin[{$HomeDirectory, "Desktop"}];

Given these preliminaries, the code for importing is
Clear[data];
n = 0;
While[(name = InputString[]) =!= $Canceled,
  data[++n] =
    Quiet @ Import[FileNameJoin[{path, "start_" <> name <> ".dat"}], HeaderLines -> 2];
  If[data[n] =!= $Failed,
    Print[Row[{name, " imported"}]],
    data[n] =.; --n; Print[$Failed]]]

To test the code, I ran it and entered start_test_1.dat followed by Return into the 1st input dialog,start_test_2.dat followed by Return into the 2nd, and hit Escape when the 3rd appeared. The results were

test_1 imported
test_2 imported

Definition[data]

data[1] = {{a, b, c, d}}
data[2] = {{q, w, e, r, t, y}, {1, 2, 3, 4}}

Note that to end the while-loop, you hit Escape or click on the dialog's Cancel button. You do not end it by entering an empty string. Note also that you get feedback about the import, and if if fails, the bad import is cleared and the file counter is decremented, so that the import can proceed without gaps.


text:
Q: Mdi Child window frame color I'm developing an MDI application. I need to know whether I can change the window frame color of the child or not.
If yes, how do I do it using the Windows API?  I tried using SetSysColor() but was unsuccessful.

A: You have to trap the WM_NCPAINT message and paint the entire frame
yourself.
The color of the caption bar is controlled by the system
color and there is no way to change the color of one caption bar with
system calls without affecting all other windows in the system.
A simple basic sample can be found here.