text:
Q: Swift iOS: Core Image with Metal Kernel: Strange kernel behavior Hello developer friends.
The first time I ask a question on Stackoverflow.
For the first time I came across writing custom Metal kernels to create a Core Image filter.
The task seemed simple. You need to make a filter to adjust the hue, saturation and lightness of colors in the image, limited by the hue range +/- 22.5 degrees. As in applications such as Lightroom color offset adjustment.
The algorithm is outrageously simple:

*

*I pass the original pixel color and values for the range and offset of hue, saturation and lightness to the function;

*Inside the function, I transform the color from the RGB scheme to the HSL scheme;

*I check if the shade is in the target range;
If I didn't hit it, I don't apply the offset, if I hit it, I add the offset values to the hue, saturation and lightness obtained during the conversion;

*I will transform the pixel color back to the RGB scheme;

*I return the result.

It turned out to be a wonderful algorithm that has been successfully and without any problems worked out in PlayGround:
Here is the source:
struct RGB {
    let r: Float
    let g: Float
    let b: Float
}

struct HSL {
    let hue: Float
    let sat: Float
    let lum: Float
}

func adjustingHSL(_ s: RGB, center: Float, hueOffset: Float, satOffset: Float, lumOffset: Float) -> RGB {
    // Determine the maximum and minimum color components
    let maxComp = (s.r > s.g && s.r > s.b) ? s.r : (s.g > s.b) ? s.g : s.b
    let minComp = (s.r < s.g && s.r < s.b) ? s.r : (s.g < s.b) ? s.g : s.b

    // Convert to HSL
    var inputHue: Float = (maxComp + minComp)/2
    var inputSat: Float = (maxComp + minComp)/2
    let inputLum: Float = (maxComp + minComp)/2

    if maxComp == minComp {
        inputHue = 0
        inputSat = 0
    } else {
        let delta: Float = maxComp - minComp

        inputSat = inputLum > 0.5 ? delta/(2.0 - maxComp - minComp) : delta/(maxComp + minComp)
        if (s.r > s.g && s.r > s.b) {inputHue = (s.g - s.b)/delta + (s.g < s.b ? 6.0 : 0.0) }
        else if (s.g > s.b) {inputHue = (s.b - s.r)/delta + 2.0}
        else {inputHue = (s.r - s.g)/delta + 4.0 }
        inputHue = inputHue/6
    }
    // Setting the boundaries of the offset hue range
    let minHue: Float = center - 22.5/(360)
    let maxHue: Float = center + 22.5/(360)

    // I apply offsets for hue, saturation and lightness
    let adjustedHue: Float = inputHue + ((inputHue > minHue && inputHue < maxHue) ? hueOffset : 0 )
    let adjustedSat: Float = inputSat + ((inputHue > minHue && inputHue < maxHue) ? satOffset : 0 )
    let adjustedLum: Float = inputLum + ((inputHue > minHue && inputHue < maxHue) ? lumOffset : 0 )

    // Convert color to RGB
    var red: Float = 0
    var green: Float = 0
    var blue: Float = 0

    if adjustedSat == 0 {
        red = adjustedLum
        green = adjustedLum
        blue = adjustedLum
    } else {
        let q = adjustedLum < 0.5 ? adjustedLum*(1+adjustedSat) : adjustedLum + adjustedSat - (adjustedLum*adjustedSat)
        let p = 2*adjustedLum - q

        var t: Float = 0
        // Calculating red
        t = adjustedHue + 1/3
        if t < 0 { t += 1 }
        if t > 1 { t -= 1 }

        if t < 1/6 { red = p + (q - p)*6*t }
        else if t < 1/2 { red = q }
        else if t < 2/3 { red = p + (q - p)*(2/3 - t)*6 }
        else { red = p }

        // Calculating green
        t = adjustedHue
        if t < 0 { t += 1 }
        if t > 1 { t -= 1 }

        if t < 1/6 { green = p + (q - p)*6*t }
        else if t < 1/2 { green = q }
        else if t < 2/3 { green = p + (q - p)*(2/3 - t)*6 }
        else { green = p }

        // Calculating blue
        t = adjustedHue - 1/3
        if t < 0 { t += 1 }
        if t > 1 { t -= 1 }

        if t < 1/6 { blue = p + (q - p)*6*t }
        else if t < 1/2 { blue = q }
        else if t < 2/3 { blue = p + (q - p)*(2/3 - t)*6 }
        else { blue = p }

    }

    return RGB(r: red, g: green, b: blue)
}

Application in the PlayGround for example like this:
let inputColor = RGB(r: 255/255, g: 120/255, b: 0/255)

 // For visual perception of the input color
let initColor = UIColor(red: CGFloat(inputColor.r), green: CGFloat(inputColor.g), blue: CGFloat(inputColor.b), alpha: 1.0)

let rgb = adjustingHSL(inputColor, center: 45/360, hueOffset: 0, satOffset: 0, lumOffset: -0.2)

// For visual perception of the output color
let adjustedColor = UIColor(red: CGFloat(rgb.r), green: CGFloat(rgb.g), blue: CGFloat(rgb.b), alpha: 1.0)

The same function, rewritten for the Metal kernel in the Xcode project, gives a completely unexpected result.
The image after it becomes black and white. At the same time, changing the input parameters by sliders also changes the image itself. Only it is also strange: it is covered with small black or white squares.
Here is the source code in Metal kernel:
#include <metal_stdlib>

using namespace metal;

#include <CoreImage/CoreImage.h>

extern "C" {
    namespace coreimage {

        float4 hslFilterKernel(sample_t s, float center, float hueOffset, float satOffset, float lumOffset) {
            // Convert pixel color from RGB to HSL
            // Determine the maximum and minimum color components
            float maxComp = (s.r > s.g && s.r > s.b) ? s.r : (s.g > s.b) ? s.g : s.b ;
            float minComp = (s.r < s.g && s.r < s.b) ? s.r : (s.g < s.b) ? s.g : s.b ;

            float inputHue = (maxComp + minComp)/2 ;
            float inputSat = (maxComp + minComp)/2 ;
            float inputLum = (maxComp + minComp)/2 ;

            if (maxComp == minComp) {

                inputHue = 0 ;
                inputSat = 0 ;
            } else {
                float delta = maxComp - minComp ;

                inputSat = inputLum > 0.5 ? delta/(2.0 - maxComp - minComp) : delta/(maxComp + minComp);

                if (s.r > s.g && s.r > s.b) {
                    inputHue = (s.g - s.b)/delta + (s.g < s.b ? 6.0 : 0.0);
                } else if (s.g > s.b) {
                    inputHue = (s.b - s.r)/delta + 2.0;
                }
                else {
                    inputHue = (s.r - s.g)/delta + 4.0;
                }
                inputHue = inputHue/6 ;
            }

            float minHue = center - 22.5/(360) ;
            float maxHue = center + 22.5/(360) ;

            //I apply offsets for hue, saturation and lightness

            float adjustedHue = inputHue + ((inputHue > minHue && inputHue < maxHue) ? hueOffset : 0 );
            float adjustedSat = inputSat + ((inputHue > minHue && inputHue < maxHue) ? satOffset : 0 );
            float adjustedLum = inputLum + ((inputHue > minHue && inputHue < maxHue) ? lumOffset : 0 );

            // Convert pixel color from HSL to RGB

            float red = 0 ;
            float green = 0 ;
            float blue = 0 ;

            if (adjustedSat == 0) {
                red = adjustedLum;
                green = adjustedLum;
                blue = adjustedLum;
            } else {

                float q = adjustedLum < 0.5 ? adjustedLum*(1+adjustedSat) : adjustedLum + adjustedSat - (adjustedLum*adjustedSat);
                float p = 2*adjustedLum - q;

                // Calculating Red color
                float t = adjustedHue + 1/3;
                if (t < 0) { t += 1; }
                if (t > 1) { t -= 1; }

                if (t < 1/6) { red = p + (q - p)*6*t; }
                else if (t < 1/2) { red = q; }
                else if (t < 2/3) { red = p + (q - p)*(2/3 - t)*6; }
                else { red = p; }

                // Calculating Green color
                t = adjustedHue;
                if (t < 0) { t += 1; }
                if (t > 1) { t -= 1; }

                if (t < 1/6) { green = p + (q - p)*6*t; }
                else if (t < 1/2) { green = q ;}
                else if (t < 2/3) { green = p + (q - p)*(2/3 - t)*6; }
                else { green = p; }

                // Calculating Blue color

                t = adjustedHue - 1/3;
                if (t < 0) { t += 1; }
                if (t > 1) { t -= 1; }

                if (t < 1/6) { blue = p + (q - p)*6*t; }
                else if (t < 1/2) { blue = q; }
                else if (t < 2/3) { blue = p + (q - p)*(2/3 - t)*6;}
                else { blue = p; }

            }

            float4 outColor;
            outColor.r = red;
            outColor.g = green;
            outColor.b = blue;
            outColor.a = s.a;

            return outColor;

        }
    }
}

I can't figure out where I could have made a mistake.
Just in case, I attach a filter class (but it seems to work fine):
class HSLAdjustFilter: CIFilter {

    var inputImage: CIImage?
    var center: CGFloat?
    var hueOffset: CGFloat?
    var satOffset: CGFloat?
    var lumOffset: CGFloat?

    static var kernel: CIKernel = { () -> CIColorKernel in
        guard let url = Bundle.main.url(forResource: "HSLAdjustKernel.ci", withExtension: "metallib"),
              let data = try? Data(contentsOf: url)
        else { fatalError("Unable to load metallib") }

        guard let kernel = try? CIColorKernel(functionName: "hslFilterKernel", fromMetalLibraryData: data)
        else { fatalError("Unable to create color kernel") }

        return kernel
    }()

    override var outputImage: CIImage? {
        guard let inputImage = self.inputImage else { return nil }

        return HSLAdjustFilter.kernel.apply(extent: inputImage.extent, roiCallback: { _, rect in return rect }, arguments: [inputImage, self.center ?? 0, self.hueOffset ?? 0, self.satOffset ?? 0, self.lumOffset ?? 0])
    }

}

Also the function of calling the filter:
func imageProcessing(_ inputImage: CIImage) -> CIImage {

        let filter = HSLAdjustFilter()

        filter.inputImage = inputImage
        filter.center = 180/360
        filter.hueOffset = CGFloat(hue)
        filter.satOffset = CGFloat(saturation)
        filter.lumOffset = CGFloat(luminance)

        if let outputImage = filter.outputImage {
            return outputImage
        } else {
            return inputImage
        }
    }

The most depressing thing is that you can't even output anything to the console. It is unclear how to look for errors.
I will be grateful for any hints.
PS: Xcode 13.1, iOS 14-15. SwiftUI life cycle.
GitHub: https://github.com/VKostin8311/MetalKernelsTestApp

A: Welcome!
The main issue with the kernel code is the use of integer literals:
The Metal Shading Language is based on C++, which doesn't have the same type inference system as Swift. So when you write 1/3 it will actually perform integer division, so that something like float t = adjustedHue + 1/3 would equal adjustedHue + 0. You have to use float literals here: adjustedHue + 1.0/3.0.
I created a pull request on your sample project with various fixes and improvements. Please let me know if something is unclear.
As for debugging: Debugging kernel code is unfortunately not possible with breakpoints and direct print statements. I usually use pixel colors for printf-debugging like this:
if (<condition I want to check>) { return float4(1.0, 0.0, 0.0, 1.0); }

All pixels that meet the condition become red in this case, which you can use to verify assumptions, etc.

A:
The most depressing thing is that you can't even output anything to
the console. It is unclear how to look for errors. I will be grateful
for any hints.

For developing and debugging metal shaders, you should use Xcode shader profiler.
I'm writing from my phone right now, from what I can see there is an mistake in your shader code:
if(maxComp == minComp)

Floating point numbers should always be compared with an epsilon value.


text:
Q: C# Static method in interface cannot be accessed from the implementing class The method SomeStaticMethod from interface IA is not directly accessible from the class A that implemented the interface. Am I missing something?
public interface IA {
    public static int SomeStaticMethod() => 4;
}

public class A : IA {
    public static void Bidule() {
        SomeStaticMethod(); //DO NOT COMPILE
        IA.SomeStaticMethod(); //COMPILES
    }
}

If the interface IA is changed to a class, it works.
public class IA {
    public static int SomeStaticMethod() => 4;
}

public class A : IA {
    public static void Bidule() {
        SomeStaticMethod(); //NOW it works
    }
}

A: A class can implement multiple interfaces. If you defined a static method with the same signature in both interfaces, the compiler couldn't decide which of those should be invoked. It's one of the (many) reasons why most OO languages try to avoid multiple-inheritance, useful as it can be.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Decryption using PBEWithMD5AndTripleDES in PHP I am working on integrating an API to our web-application. On the initial request, the API returns a response that is encrypted using PBEWithMD5AndTripleDES encryption, and then base 64 encoded. I have an encryption password that is provided to me beforehand. Because of my lack of experience and PBEWithMD5AndTripleDES documentation, I am struggling to decrypt the response. I have tried using  phpseclib without any luck.
This is my code with phpseclib
        $res = $response->getBody()->getContents();
        $res = base64_decode($res);
        // this is provided by vendor
        $password = self::PASSWORD;
        // I tried this too.
        //$password = md5(utf8_encode($password), true);

        $tripleDes = new TripleDES(TripleDES::MODE_CBC);
        $tripleDes->setKey($password);
        $ddd = $tripleDes->decrypt($res);

        // this is returning false
        var_dump($ddd); die();

Can you please provide me some examples of how to use PBEWithMD5AndTripleDES in PHP or point me to some direction or documentation.

A: PBEWithMD5AndTripleDES uses an MD5 based algorithm for key / IV derivation, which expects a password, a salt and an iteration count as parameters. For encryption TripleDES in CBC mode (des-ede3-cbc) with a 24 bytes key is applied.
PBEWithMD5AndTripleDES is an Oracle proprietary extension of the password-based encryption defined in PKCS#5 (RFC 8018) to support longer keys,  here. Because it is proprietary and because of the outdated algorithms like MD5 and the relatively slow TripleDES compared to AES, it should not be used for new implementations, but only for compatibility with legacy code.
I have not found any PHP library on the web that supports PBEWithMD5AndTripleDES out-of-the-box (only for the different PBEWithMD5AndDES, e.g. here). For a custom implementation you actually only need the derivation of the key / IV. So if you don't find an implementation either, but you have compelling reasons to use this algorithm: Here is a Java code that implements the derivation. A port to PHP could be:
function deriveKeyIV($key, $salt, $count){

    $result = "";
    for ($var = 0; $var < 4; $var++){
        if($salt[$var] != $salt[$var + 4])
        break;
    }
    if ($var == 4){
        for ($var = 0; $var < 2; $var++){
            $tmp = $salt[$var];
            $salt[$var] = $salt[3 - $var];
            $salt[3 - 1] = $tmp;
        }
    }
    for ($var = 0; $var < 2; $var++){

        $toBeHashed = substr($salt, $var * (strlen($salt) / 2), strlen($salt) / 2);
        for ($var2 = 0; $var2 < $count; $var2++){
            $toBeHashed = hash ("MD5", $toBeHashed . $key, TRUE);
        }
        $result = $result . $toBeHashed;
    }

    return $result;
}

The function returns 32 bytes, of which the first 24 bytes are the key and the last 8 bytes are the IV. With this key and IV the encryption with TripleDES in CBC mode can then be performed.
Example:
$keyIv = deriveKeyIV(hex2bin("01026161afaf0102fce2"), hex2bin("0788fe53cc663f55"), 65536);
$key = substr($keyIv, 0, 24);
$iv = substr($keyIv, 24, 8);

print(bin2hex($key) . "\n");
print(bin2hex($iv) . "\n");
print(openssl_encrypt("The quick brown fox jumps over the lazy dog", "des-ede3-cbc", $key, 0, $iv));

Output:
543650085edbbd6c26149c53a57cdd85871fd91c0f6d0be4
d7ffaa69502309ab
m4pye0texirKz1OeKqyKRJ5fSgWcpIPEhSok1SBDzgPthsw9XUuoiqXQBPdsVdUr

As reference I used a Java implementation, more precisely the implementation of PBEWithMD5AndTripleDES of the SunJCE provider, which gives the same result.
Note that the original implementation of PBEWithMD5AndTripleDES only allows a salt that is exactly 8 bytes in size (although the derivation function can handle larger salts), otherwise an exception is thrown (salt must be 8 bytes long). To add this constraint, the following can be added at the beginning of deriveKeyIV:
if (strlen($salt) != 8) {
    throw new Exception('Salt must be 8 bytes long');
}


text:
Q: Jmeter Recording Controller is not working when use for url localhost I am new to Jmeter.
I used recording controller to record the script .When I record url like www.google.com then its recording but when I record url localhost/test/users/login then its not getting record.I am using xampp apache local server at port 80,443
I did setting in browser

I have refer this link
https://jmeter.apache.org/usermanual/jmeter_proxy_step_by_step.pdf

A: Remove from firefox configuration in No Proxy For:

localhost, 127.0.0.1

And ensure you start Recorder


text:
Q: Redis Lua script - HMGET returned bulk contains nil but is not recognized as nil Sorry for the vague title. Hopefully the examples below explain my confusion.
Try evaluating each of the four Lua scripts below in Redis. My question is why the ternary operation that sets a value to 0 if HMGET returns nil doesn't work in the 4th script.
local bulk = {nil,nil,nil}
return bulk[1] -- nil (good)

-- Proof that ternary operator works
local bulk = {nil,nil,nil}
local rate = (bulk[1] == nil and 0 or bulk[1])
return rate -- 0 (good)

-- Proof that first element in HMGET results is nil
local bulk = redis.call('hmget', 'k1', 'f1', 'f2')
return bulk[1] -- nil (good)

-- Why does ternary op fail on HMGET results?
local bulk = redis.call('hmget', 'k1', 'f1', 'f2')
local rate = (bulk[1] == nil and 0 or bulk[1])
return rate -- nil (bad, want 0)

A: Because bulk[1] is false, NOT nil.
From the doc:

Redis Nil bulk reply and Nil multi bulk reply -> Lua false boolean type

In Redis, HMGET returns Nil reply for the second field, i.e. bulk[1], and it's converted to false when the reply is passed to Lua. So your 4th script doesn't work, since bulk[1] == nil is false.

Lua boolean false -> Redis Nil bulk reply.

In your 3rd script, bulk[1] of type false, is returned, and Redis convert false to a Nil reply


text:
Q: A surjective map $S^{2} \longrightarrow S^{2}$ Is there any continuous surjective map  $S^{2} \longrightarrow S^{2}$ such that it sends one of the meridians of the first sphere into the south pole of the second one?
I can see that is true, but I'm having a hard time figuring out a proper "analytical" definition (with some kind of coordinates etc.).
EDIT: For a meridian I mean the shortest arc from the north pole to the south pole (with poles included).

A: I will prove that the following map meets the requirements:

$$\cases{X=2xy\\Y=-2yz\\Z=2y^2-1}\qquad\text{if $y>0$}$$  and
  $$\cases{X=0\\Y=0\\Z=-1}\qquad\text{otherwise}$$

In spherical coordinates (with the usual convention $0\leq \theta\leq\pi$ and $0\leq\phi\leq 2\pi$): $$f:(\theta,\phi)\mapsto \cases{(2\theta,\phi)& if $\theta\leq \frac{\pi}{2}$\\(\pi,0) & otherwise}$$
sends the equator to the south pole.
If you want to send a meridian to the SP, all you need is to send it first to the equator, and then apply the above map.
In Cartesian coordinates, the rotation represented by the following matrix sends the meridian of equation $\cases{y=0\\x^2+z^2=1}$ to the equator $\cases{z=0\\x^2+y^2=1}$:
$$M=\left(\matrix{1&0&0\\0&0&-1\\0&1&0}\right)$$
Now

*

*Start with Cartesian $\left(\matrix{x&y&z}\right)$.

*Apply $M$ to get $\left(\matrix{x&-z&y}\right)$.

*Turn to spherical: $$\theta =
   \arctan\left(\frac{\sqrt{x^2 + z^2}}{y}\right),
  \varphi = \arctan\left(\frac{-z}{x}\right)$$ (note that this change of variables formula is compatible with the
convention $0\leq\theta\leq \pi$ on the northern hemisphere only, but
this is sufficient for our purposes)

*Apply the map $f$ to get $$\theta =\cases{ 2\arctan\left(\frac{\sqrt{x^2 + z^2}}{y}\right) & if $y>0$\\
  \pi&otherwise}$$

*Turn back to Cartesian $$\cases{X=\sin\left(2\arctan\left(\frac{\sqrt{x^2 + z^2}}{y}\right)\right)\cdot\cos\left(\arctan\left(\frac{-z}{x}\right)\right)\\Y=\sin\left(2\arctan\left(\frac{\sqrt{x^2 + z^2}}{y}\right)\right)\cdot\sin\left(\arctan\left(\frac{-z}{x}\right)\right)\\Z=\cos\left(2\arctan\left(\frac{\sqrt{x^2 + z^2}}{y}\right)\right)}\qquad\text{if $y>0$}$$

*Apply $\sin 2t=2\sin t\cos t$ to get the announced formula.

A: I thought of a map that maybe works.
Let $S^{2} \subset \mathbb{R}^{3}$ be the unit sphere in the space, with center $(0,0,0)$. I put on this the following coordinates:
$t \in [-1,1]$ indicates a point on the line from $(-1,0,0)$ to $(1,0,0)$. If I fix a $t$ of this set, I consider the circle with center $(t,0,0)$, parallel to the $yz$ plane and with radius $1-|t|$. Now, I take $\theta \in [0,2\pi]$ as the angle with the line passing trough the center and parallel to the $z$ axis in the $xz$ plane (such that the point $(0,0,-1)$ would have coordinates $(t,\theta)=(0,0)$, the point $(0,0,1)$ would have $(t,\theta)=(0,\pi)$ and so on.).
Now, the map I was looking for could be
$$f:(t,\theta)\mapsto \cases{(t,2\theta)& if $0 \leq \theta \leq \pi$\\(t,2\pi) & if $\pi \leq \theta \leq 2\pi$.}$$


text:
Q: Jersey 2 getLinks() returns empty set despite links being in the resource EDIT shorter version
Ok so looking at my own post I realize this is perhaps not the shortest thing to read, so I thought I would write a more concise version with some more hands-on details.
I am using Jersey 2 client framework to code against the Documentum REST API, hosted for the time being on my local machine. If I execute the following code:
WebTarget target = client.target("http://localhost:8080/dctm-rest/repositories/repo");
Response response = t.request().get();

and the XML which is returned looks like this
<?xml version="1.0" encoding="UTF-8"?>
<repository xmlns="http://identifiers.emc.com/vocab/documentum" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <... metadata entries></>
    <links>
        <link rel="self" href="http://localhost:8080/dctm-rest/repositories/repo"/>
        <link rel="http://identifiers.emc.com/linkrel/users" href="http://localhost:8080/dctm-rest/repositories/darwin_test/users"/>
        <... more links />
    </links>
</repository>

... then what do I have to do in order to get the links in the response in the following manner:
Link self = response.getLink("self");

The above command just ends up with self being null.
END EDIT
I've tried my best finding a solution to this but with no luck so far.
Basically I am consuming a REST webservice which by default returns JSON formatted resources, which is pretty nice (alot nicer than xml anyway). I am using Jersey 2.4.1 to consume the service, and while I am pretty new to coding against REST-services, I haven't had any real issues besides this (and this is really more Jersey-related than REST as far as I can tell).
Basically, I am having no luck whatsoever in utilizing the Jersey 2 API for retrieving and traversing links, which are returned by the service. Jersey 2 has the following (short) example in its documentation:
// server side - adding links to a response:
Response r = Response.ok().
    link("http://oracle.com", "parent").
    link(new URI("http://jersey.java.net"), "framework").
    build();

Which imho is the equivalence of the following returned data:
<link rel="parent" href="http://oracle.com"/>
<link rel="framework" href="http://jersey.java.net"/>

Now to get the links for these relations, the clientside code in the documentation looks like this:
// client-side processing:
final Response response = target.request().get();
URI u = response.getLink("parent").getUri();
URI u = response.getLink("framework").getUri();

I think this is pretty straightforward. Now my service, in the URL that my WebTarget object is pointing at, has roughly 10 links in the following JSON format:
{
    ... <metadata before the links> ...

    "links" :
    [
        {
            "rel"  : "some relation",
            "href" : "some http url"
        }
        ... about 10 more entries like this
    ]
}

The problem is that if I do the client-side equivalence of what was in the documentation:
WebTarget t = client.target("url");
t.request().get().getLinks();

..then I get back nothing but an empty Set<Link>.
I suspect it might have to do with enabling JSON-binding in the Client somehow, but I have tried adding the dependency for MOXy, which appearently should be self-enabled if it's in the classpath, and that didn't help.
I'm sure I am missing something extremely basic but I've been searching all day, testing different media-type requests and anything I can think of but with no luck. And while my application is working fine without this sort of link-processing, I still want to get this working.
Thanks for any help on this.
// Andreas
EDIT Response to user1888440
I agree, the links are indeed in the entity returned when the resource is queried. This also aligns with the way I've been processing resources, where I use:
JsonObject o = Json.createReader(target.request().get().readEntity(InputStream.class)).readObject();

.. and then query the object for links in the following manner: I need to first get the "links"-JsonArray from the JsonObject o, then iterate over all links found, compare the "rel"-description with what I'm after and return the correct "href"-value.
However I think there should be a smoother way to get to the links in an entity, especially if we compare this procedure with the following:
response = target.request().get();
URI u = response.getLink("parent").getUri();
URI u = response.getLink("framework").getUri();

And I get what you're saying, that the above getLink("rel") / getLinks() methods only apply to links in the header of the response. But surely there must be some equivalent way of processing links inside an entity, which isn't as verbose as what I've described above?
PS: The example you suggested, to read an resource entity into a Map:
Map entity = t.get( Map.class );

.. doesn't work and results in a null value for entity.

A: The vendor is sending you the links in the entity that is embedded in the response not links in the response itself. Try this:
Map entity = t.get( Map.class );
Map<String,String> links = (Map<String,String>)entity.get( "links );
URI uriSelf = URI.create( links.get( "self" ) );

You see the links are in the entity not in the header of the request. The response links are for header links. You can also make a more specific object, this is just using maps to get at the property data.


text:
Q: Admob or Adsense for my android apps? I have 7 apps on the market - all free. In total I have had 10k impressions and have made $11. What do you think of this? Search 'Lewicki' to see my apps. Thanks

A: I have marginally better outcome with AdSense after switching from Admob. Now - Admob become Google after my switch so I don't know if that holds true. Impressions rate about right based on my experience. To make any sort of decent money with this you need really popular app. Something with 1/2M users (say Angry Birds)


text:
Q: r legend doesn´t adjust when the layout of graphs change I have been using the legend function and it used to work good, and for good means when I plot 2 graphs using layout(1:2) and I add a legend this fits the size of the graph, but now, when I plot a graph, and then add a legend, the legend keeps its size as if the layout was 1:1
library(stats,xts,zoo)
x1 = stats::ts(rnorm(14),st=2014,freq=52*7)
x2 = stats::ts(rnorm(14),st=2014,freq=52*7)
x3 = stats::ts(rnorm(14),st=2014,freq=52*7)
x4 = stats::ts(rnorm(14),st=2014,freq=52*7)
d = data.frame(x1,x2,x3,x4)

layout(1:2)
plot(zoo::as.zoo(xts::xts(d,Sys.Date()+1:14)),
     plot.type='single',
     col=c(0,1,2,3,4),
     lty=c(1,1,2,1,3),
     lwd=c(1,2,2,2,3),
     ylab="Sales", xlab = "Time", main = "Product 1 sales",
    )
    legend("topleft", cex=.8,bty="n", col=c(1,2,4,3), c("Target", "nnet",
           "sequential", "GPU"), lty = c(1,2, 3,1),  bg ="0")

I can´t add images to show because I don´t have enough reputation.
*** This example was run in R-studio displaying the graph as I already said, then I tried to run it in the r console and it works fine.


text:
Q: Obtain Worksheet COMObject in Python I have been trying to add pushbuttons to dynamically created excel sheets using win32com from inside python. The main problem i am facing is that i am unable to obtain the Worksheet COMObject on which i can apply the Worksheet methods. I have got the following code so far:
from win32com.client import DispatchEx, Dispatch
excel = Dispatch('Excel.Application')
wb = excel.Workbooks.Open('some/path/')
ws = wb.Worksheets.Add()
print(ws)
ws.Buttons.Add(786, 323.25, 109.5, 29.25)

This gives the following one output and one error:
<COMObject Add>
AttributeError: 'function' object has no attribute 'Add'

I was expecting that 'ws' to be a worksheet COMObject on which i can directly add a pushbutton using the code above. Kindly explain to me what i'm doing wrong here as well as a method to obtain Worksheet object on which the above code snippet would work. Thanks.

A: ws.Buttons is a method that returns a COMObject when called. So you need to add parentheses directly after it.
from win32com.client import DispatchEx, Dispatch
excel = Dispatch('Excel.Application')
wb = excel.Workbooks.Open('some/path/')
ws = wb.Worksheets.Add()

# Show the difference between `ws.Buttons` and `ws.Buttons()`
print(type(ws.Buttons))
print(type(ws.Buttons()))

# Add button to worksheet
ws.Buttons().Add(786, 323.25, 109.5, 29.25)


text:
Q: Reactjs: The value of the input element, required for a controlled component In my project, there is an input field to add email tags. Now it shows an error

import React, { useState } from "react";
import ReactDOM from "react-dom";
import Chip from "@material-ui/core/Chip";
import TextField from "@material-ui/core/TextField";

interface details{
    item: string
}

// type Props = {
//     test: string,
//     // error: string,
//   };

export const TagActions = () => {
    // var { test } = props
    const [items, setItem] = useState<string[]>([]);
    const [value, setValue] = useState('')
    const [error, setError]= useState('')

    const handleDelete = (item:any) => {
        const result = items.filter(i => i !== item)
        setItem(result)
      };

    const handleItemEdit = (item:any) =>{
        const result = items.filter(i => i !== item)
        setItem(result)
        setValue(value)

    };

    const handleKeyDown = (evt:any) => {
        if (["Enter", "Tab", ","].includes(evt.key)) {
          evt.preventDefault();

          var test = value.trim();

          if (test && isValid(test)) {
            items.push(test)
            setValue("")

          }
        }
    };

    const isValid = (email:any)=> {
        let error = null;

        if (isInList(email)) {
          error = `${email} has already been added.`;
        }

        if (!isEmail(email)) {
          error = `${email} is not a valid email address.`;
        }

        if (error) {
            setError(error);

          return false;
        }

        return true;
    }

    const isInList = (email:any)=> {
        return items.includes(email);
      }

    const isEmail = (email:any)=> {
        return /[\w\d\.-]+@[\w\d\.-]+\.[\w\d\.-]+/.test(email);
    }

    const handleChange = (evt:any) => {
        setValue(evt.target.value)
        // setError("")

    };

    const handlePaste = (evt:any) => {
        evt.preventDefault();

        var paste = evt.clipboardData.getData("text");
        var emails = paste.match(/[\w\d\.-]+@[\w\d\.-]+\.[\w\d\.-]+/g);

        if (emails) {
          var toBeAdded = emails.filter((email:any) => !isInList(email));

            setItem(toBeAdded)

        }
    };

    return (
        <>

          <TextField id="outlined-basic" variant="outlined"
          InputProps={{
            startAdornment: items.map(item => (
              <Chip
                key={item}
                tabIndex={-1}
                label={item}
                onDelete={() => handleDelete(item)}
                onClick={() => handleItemEdit(item)}
              />
            )),

          }}
            ref={items}
            value={value}
            placeholder="Type or paste email addresses and press `Enter`..."
            onKeyDown={(e) => handleKeyDown}
            onChange={(e) => handleChange}
            onPaste={() => handlePaste}
          />

          {error &&
{error}
}
        </>
      );
}

I already tried some solutions But the expected result did not come. I don't know if there are other ways to do such functions because I am a beginner in react typescript. so I don't know how to fix this. Please give me some valuable suggestions to fix this problem.

A: You are passing items as ref, but you can only pass variable returned by useRef there. For example:
const [string, setString] = useState<string>("")
const divRef = useRef<HTMLDivElement>(null)

return
text
 // not ok
return
text
 // ok


text:
Q: HTML Pattern - regex not working I'm trying the pattern attribute for the first time, and I can't get it to work (my browser does support it, though).
Right now I have:
input type="text" pattern="[a-zA-Z0-9]{6}" name="formName"

The first problem is that is doesn't notify me if it's blank; the second problem is that if I do type in something, it won't accept it. I want it to accept alphanumeric characters and be exactly 6 characters is length. I tried it with forward slashes and a few other variations.

A: Works for me here : http://jsfiddle.net/barbuslex/nR6yg/
<form>
    <input type="text" pattern="[a-zA-Z0-9]{6}" name="formName" />
    <input type="submit" value="OK" />
</form>

I use Google Chrome

A: As Duikboot already pointed out, the right way to do it is:
<input type="text" name="formField" pattern="[a-zA-Z0-9]{6}" required>

The required attribute causes the validation to fail, when the field is empty.
The pattern attribute defines the regex to test against, when the field is not empty.
(Your initial pattern seems to work fine.)
More info can be found here.
This is simple enough so as not to require a demo, but nonetheless you can find one here.

A: You simply need to add the required attribute to your tag, which will notify the user if they attempt to send the form with that very field blank.
<input type="text" pattern="[a-zA-z0-9]{6}" name="formName" required>

A: Try this code its working perfectly
<html>
<body>
<form action="demo_form.asp">
  Country code: <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
  <input type="submit">
</form>
</body>
</html>

Enter invalid country code and click submit button. Then You can get a message (title="Three letter country code")


text:
Q: Is it reasonable to try and fix these kernel boot lags? I've noticed the bootup process pauses for a while. Can I fix this? Is it even worth trying? This system used to boot up faster.
uname -rp:
4.19.25-041925-generic x86_64

(I actually rolled back from 4.20.12 but there it took even longer.)
dmesg:
...

[    5.532700] Console: switching to colour frame buffer device 240x67
[    5.556565] i915 0000:00:02.0: fb0: inteldrmfb frame buffer device
[    9.405339] ata1.00: qc timeout (cmd 0x47)
[    9.407728] ata1.00: READ LOG DMA EXT failed, trying PIO
[    9.407737] ata1.00: NCQ Send/Recv Log not supported
[    9.407742] ata1.00: ATA-10: FORESEE 128GB SSD, V3.15, max UDMA/133

...

[   18.675961] wlp1s0: associated
[   19.020500] IPv6: ADDRCONF(NETDEV_CHANGE): wlp1s0: link becomes ready
[   29.000586] Bluetooth: RFCOMM TTY layer initialized
[   29.000597] Bluetooth: RFCOMM socket layer initialized
[   29.000610] Bluetooth: RFCOMM ver 1.11
[   31.806813] rfkill: input handler disabled

A: Note: You're using an unsupported kernel. 4.19 is known to corrupt file systems. Put the standard kernel back.
From what little log detail that you left for us to review, it looks like you might be getting NCQ errors on your disk. You might look at this more closely to see if there are a bunch more NCQ errors...
sudo grep -i ncq /var/log/syslog* # search for NCQ errors
If you find a bunch, then...
sudo -H gedit /etc/default/grub # edit the grub settings
Find the line near the top that says "quiet splash", and change it to read...
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash libata.force=noncq"
Save the file and then...
sudo update-grub # update grub files
reboot # reboot the computer


text:
Q: Website url while enabling places API in my android application I want to use google places API. I logon to code.google.com/apis/console. When I'm trying to enabling access to places API it asks for Company url and organization. I don't have any website, So how do I use it?
I asked my friends, and give their url and name. Now it will show error message as Invalid website url. Please help me to enable the places API service

A: Not sure if you still care, but you probably just left out "http://" before the URL. This causes it to say "invalid website URL". Very annoying, I know.

A: The problem is in the URL. I omit the "http://" before the URL. Now it solved my issue


text:
Q: Can Postman access posted values in a test I have postman set up to post data to an endpoint.  Ex:
{
  "gender": "f",
  "firstName": "bob",
  "lastName": "smith"
}

I have a test that extracts information from the response and stores it in environment variables.
Is there a way to access the values that were posted as part of the test.  Something like:
pm.request.parameters("gender")

A: As per the postman sandbox documentation, you can do the following:
var reqBody = JSON.parse(pm.request.body);
... // Access reqBody;

A: To get access to that specific property:
JSON.parse(pm.request.body.raw).gender

And the test could be:
pm.test("Check request data", () => {
    pm.expect(JSON.parse(pm.request.body.raw).gender).to.eql('f')
})


text:
Q: Angular 2 - What to do if modules need each other I have a case, where I have two modules, who have there own Pipe-definitions. One Module is a customer module, the other a product module. In products I want to use customer pipes and vice versa.
If modules in Angular 2 import each other like the following:
Example Root Module:
@NgModule({
  imports: [
    BrowserModule, AModule, BModule
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

Example Module B:
@NgModule({
    imports: [BModule],
    declarations: [

        ],
        exports: []
})
export class AModule { }

Example Module A:
@NgModule({
    imports: [AModule],
    declarations: [

        ],
        exports: []
})
export class BModule { }

The browser throws an error:

Uncaught Error: Unexpected value 'undefined' imported by the module
  'BModule'

I could create a SharedModule, that declares both Pipes and import that module into A and BModule. But this would not be SOLID anymore, because customer pipes and product pipes just belong into there own module and not in another shared module.
Any proposals?
I googled, but did not find anything :(


text:
Q: QBO3 Queue Paused and Won't Restart In a QBO3 system, the Design > Configuration > Queuing page includes several queues in a Paused status.  When I attempt to start the queue via the GUI, it very quickly reverts to a Paused status. When I recycle the Queue Service, and then attempt to start the queue via the GUI, it again quickly reverts to a Paused status.  Here are the properties of one of the paused queues:

A: When a queue is paused, you can determine the root cause of the pause from the Debug Queue Log. From Design > Configuration > Queuing, click on the search icon under the queue's Debug Log column.
There are two common reasons for a queue being automatically paused.
Pause after X consecutive errors
A queue may be configured to paused after a certain number of consecutive errors. This is typically done to ensure that QBO3 does not 'spin it wheels' when there is something configured improperly.
To control the characteristics of such pauses, edit the queue, and set the following fields under the Queue Retry section:

*

*Pause after: enter the number of consecutive failures that should cause a pause. Leave blank to avoid pausing

*Restart: enter the number of restarts that will be allowed. This is useful for queues that interface with third party systems that may be down for a period of time.

*

*After X {minutes | hours | days}: determines how long the queue must wait before restarting.

Queue Configuration Error
A queue may be configured with incorrect information, such as:

*

*a missing IQueue plugin (e.g. the installation is missing a IQueue plugin like ServiceBroker or SNS)

*a missing Schedule (e.g. the Queue.Schedule is defined, but there is no matching entry in the Schedule table.  Run Design > Packages > Queue Initialization for standard schedules.)

For example, the Debug log for a queue with an invalid schedule would display an error along these lines:

FileExport, queue paused on 6/2/2016 9:52:31 AM. Pause count 1. Resume
  count . No resume date. Schedule Access Error Either this record does
  not exist, or you do not have access to it. Object 'Schedule',
  ObjectID '0'


text:
Q: How to add columns to data.frame based on vector length I have a function runBootstrap whose output result is a vector of variable length (depending on # of values for cat, which itself is a product of test). Apologies that this isn't "minimal".
require(dplyr)

test <- function(combo) {
  if(combo[1] == 4) {
    cat <- 4
  } else if((combo[1] == 3 & combo[2] == 2) | (combo[1] == 2 & combo[2]     == 2)) {
    cat <- 3
  } else if((combo[1] == 2 & combo[2] == 1) | (combo[1] == 1 & combo[2]     == 2)) {
    cat <- 2
  } else {
    cat <- 1
  }
}

arg1.freqs <- c(0.5, 0.2, 0.1, 0.1)
arg2.freqs <- c(0.8, 0.2)

runBootstrap <- function(arg1.freqs, arg2.freqs) {
  sim.df <- data.frame(x1 = 1:10000, y1 = NA)
  sim.df$x1 <- sample(1:4, 10000, replace = TRUE,
                      prob = arg1.freqs)
  sim.df$y1 <- sample(1:2, 10000, replace = TRUE,
                      prob = arg2.freqs)
  sim.df$cat <- NA
  for(i in 1:nrow(sim.df)) {
    combo <- c(sim.df[i, 1], sim.df[i, 2])
    sim.df$cat[i] <- test(combo)
  }
  sim.df <- sim.df %>%
    select(cat) %>%
    group_by(cat) %>%
    summarise(n = n()) %>%
    mutate(freq = n / sum(n))
  sim.df <- as.data.frame(sim.df)
  result <- c(sim.df[1, 3], sim.df[2, 3])
}

In this current version there are only two values for cat so result is a vector of length 2; in a future version I will adjust code so that length(result) will equal # values of cat.
When using the function in a for loop, I would like to use the vector values to create new columns in an already existing data.frame df1. The code I've tried thus far is as follows:
df1$result <- NA
for (i in 1:nrow(df1)) {
  df1$result[i] <- runBootstrap(arg1.freqs, arg2.freqs)
}

This clearly doesn't work unless the result vector is length = 1. But I don't know the length of the vector until the function runs (although once it runs it will be same length each iteration).
What I would like to achieve is the following:
Example 1: if length(result) == 2
  df1.col x1 x2
1       1  1  1
2       2  2  2
3       3  3  3
4       4  4  4
5       5  5  5
6       6  6  6

Example 2: if length(result) == 3
  df1.col x1 x2 x3
1       1  1  1  1
2       2  2  2  2
3       3  3  3  3
4       4  4  4  4
5       5  5  5  5
6       6  6  6  6

Thanks for any advice or direction.

*

*edited for clarification

*UPDATE - edited with solution

I got it to work as I wanted by creating a blank list, populating, then using rbind as follows:
appendResults <- function(df1, arg1, arg2) {
  my.list <- vector("list", nrow(df1))
  for (i in 1:nrow(df1)) {
    arg1.freqs <- as.numeric(arg1[i, 3:6])
    arg2.freqs <- as.numeric(arg2[i, 3:4])
    my.list[[i]] <- runBootstrap(arg1.freqs, arg2.freqs)
  }
  result.df <- do.call(rbind, my.list)
  df2 <- do.call(cbind, list(df1, result.df))
}

A: Check this one, not sure what the result looks like, but this creates empty columns, equal to the length of results, with NAs:
# fake data frame
df1 <- data.frame(x = c(1,2,3), y = c("a", "b", "c"))

# say result has length 3
res <- c(5,6,7)

# make columns with names x1, ..., x + length of res
# and assign NA values to those column
df1[ , paste("x", 1:length(res), sep = "")] <- NA


text:
Q: How to set OPENCV_ENABLE_NONFREE option? I'm trying to install opencv with the non-free features enabled. All the documentation I find says to "build it with cmake with the OPENCV_ENABLE_NONFREE option enabled."
I have no idea what that means. I barely understand cmake at all. I've been following these instructions. They seem pretty clear. However, I don't understand where in the process I'm supposed to enable that option. Is that option set in some configuration file? Is it a command line option? I'm afraid I just don't understand what I'm supposed to do.


text:
Q: memoir class table of content formatting How can I replace Chapter 1 with Chapter One in the table of contents when using the memoir class?
I tried the following but it does not work:
\documentclass[12pt,a4]{memoir}
\usepackage[centertags]{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{setspace}
\usepackage{graphicx}
\usepackage{morefloats}
\usepackage[scriptsize]{subfigure}
\usepackage[table,xcdraw]{xcolor}
%\usepackage{caption}
\usepackage{epsfig}
\usepackage{multirow}
\usepackage{multicol}
\usepackage{setspace}
%\usepackage[compact]{titlesec}
\usepackage{wrapfig}
\usepackage[left=3cm,top=2.5cm,right=2.5cm,bottom=2.5cm]{geometry}
\usepackage[square]{natbib}
\usepackage{soul}
\usepackage{afterpage}

\makeatletter
\renewcommand\@biblabel[1]{#1.}
\makeatother

\newif\ifendLOF

\newcommand*{\lofheader}{
\ifendLOF\else\hbox to \linewidth%
  {{~\ul{Figure}}~\hfill{\ul{Description}}~\hfill{\ul{Page}}}\par%
  \vspace{12pt}%
  \afterpage{\lofheader}
\fi}%

\newif\ifendLOT

\newcommand*{\lotheader}{
\ifendLOT\else\hbox to \linewidth%
  {{~\ul{Table}}~\hfill{\ul{Description}}~\hfill{\ul{Page}}}\par%
  \vspace{12pt}%
  \afterpage{\lotheader}
\fi}%

 \renewcommand\cftchaptername{\chaptername~}

\begin{document}
\DoubleSpacing
\chapterstyle{brotherton}
\renewcommand\bibname{References}
Title page goes here
\newpage
\pagestyle{plain}
\pagenumbering{roman}
\addcontentsline{toc}{chapter}{Dedication}
Dedication goes here
\newpage
\addcontentsline{toc}{chapter}{Acknowledgment}
Acknowledgment goes here
\newpage
\tableofcontents
\newpage
\addcontentsline{toc}{chapter}{List of Figures}
\listoffigures
\addtocontents{lof}{\protect\lofheader}
\endLOFtrue
\newpage
\addcontentsline{toc}{chapter}{List of Tables}
\listoftables
\addtocontents{lot}{\protect\lotheader}
\endLOTtrue
\newpage
\addcontentsline{toc}{chapter}{Abstract}
Abstract goes here
\newpage
\pagenumbering{arabic} \setcounter{page}{1}
\chapter{Test1}
This is the first chapter.
\section{this is section 1.1}
This is a test
\chapter{Test2}
This is the second chapter.
\section{this is section 2.1}
This is a test
\chapter{Test3}
This is the third chapter.
\section{this is section 3.1}
This is a test

\SingleSpacing
\setlength{\bibsep}{\baselineskip}
\newpage

\bibliography{Thesis}
\bibliographystyle{ieeetr}

\end{document}

A: Try the following:
\documentclass[article,twocolumn,12pt]{memoir}

\renewcommand*{\cftchaptername}{Chapter\space}% p. 151, memmanual
\renewcommand*{\chapternumberline}[1]{%
\cftchaptername\protect\NumToName{#1}\space--\space}% p. 152, memmanual

\title{Document Title}
\author{First Name and Surname}
\date{\today}

\renewcommand{\maketitlehookd}[1]{\tableofcontents*}
% Show the toc in one-column after the date.

\begin{document}

\maketitle

\chapter{Capítulo primero}
xx\dotfill xx

\section{Sección 1.1}
xx\dotfill xx

\subsection{Sub--sección 1.1.1}
xx\dotfill xx

\subsubsection{Sub--sub--sección 1.1.1.1}
xx\dotfill xx

\chapter{Capítulo segundo}
xx\dotfill xx

\section{Sección 2.1}
xx\dotfill xx

\subsection{Sub--sección 2.1.1}
xx\dotfill xx

\subsubsection{Sub--sub--sección 2.1.1.1}
xx\dotfill xx

\end{document}


text:
Q: How to set 'ColumnWidth' using ActiveXObject("Excel.Application")? I'm using ActiveXObject("Excel.Application") to export html table to Exel in IE Explorer,here is my code:
var curTbl = document.getElementById(tableId);
var oXL = new ActiveXObject("Excel.Application");
var oWB = oXL.Workbooks.Add();
var xlsheet = oWB.Worksheets(1);
var sel = document.body.createTextRange();
sel.moveToElementText(curTbl);
sel.execCommand("Copy");
xlsheet.Paste();
var fname = oXL.Application.GetSaveAsFilename(name+".xls", "Excel Spreadsheets (*.xls), *.xls");
oWB.SaveAs(fname);
oWB.Close(savechanges = false);
oXL.Quit();
oXL = null;

I searched this and get this.
xlsheet.ActiveSheet.Columns(startcol+":"+endcol).ColumnWidth = 22;

But it didn't work and 'ActiveSheet' is undifined.Help ,thank you.

A: Finally,i find an answer.Use
xlsheet.columns.AutoFit();

or
var myRange = xlsheet.Range(xlsheet.Cells(2, 1), xlsheet.Cells(2, 7));
myRange.Columns.AutoFit();
myRange.Rows.AutoFit();


text:
Q: Is is possible to clone a application server in Websphere I have deployed an application on server1 in Websphere 8.5.5
Can I clone it to create server2 with the same application deployment and datasources.

A: In case you are in an ND environment you can create a server template (From the console: Websphere Application Servers > Templates > New ) based on the server1 and then create server2 based on this template.
This way you easily get all configuration of server1 (datasources, jvm arguments etc) into server2.

A: You can install WAS at same level on second machine and then use "manageprofiles -backupProfile" and "manageprofiles -restoreProfile" commands to move profile to machine2. Then use the AdminTask.changeHostName ('[-interactive]') to change hostname on the machine.
You can change nodename to different nodename using renameNode.bat also. The only thing is there will be no command to change cellname and you will have same cellname as original server.
For more details please review the link below :
http://www-01.ibm.com/support/docview.wss?uid=swg27020204


text:
Q: How to convert wrappedArray column in spark dataset to java array? In my project I got a column after applying collect_list aggregate function, which is of format wrappedArray , I wanted to know is there anyway to convert that wrappedArray to normal array or list So that I can iterate over that column and extract values row by row in that column?
Language:- JAVA
Using Apache spark library
By this I am getting that column which is of wrappedArray type
dataset.groupBy( "department","salary","tag")
.agg(collect_list(col("id")));

dataset.foreach(row ->
      row.getAs("id)")

);

I am confused how should I proceed further to iterate in that column.

A: If you have a WrappedArray there are several ways to convert it to a Java collection.
You can leverage scala.collection.JavaConverters helper methods:
WrappedArray<Long> wrappedArray = row.getAs("ids");
List<Long> list = scala.collection.JavaConverters.seqAsJavaList(wrappedArray.seq());

Alternatively, you can use the Row.getList method to obtain directly a Java List:
List<Long> list = row.getList(row.fieldIndex("ids"));


text:
Q: Trying to get my navbar button to work when the screen is in tab or on mobile mode So I have my navbar and i have a button so when the screen is shrunk down to a certain size the navbar becomes the button with the three lines that should be a dropdown and it is not working. I am trying to have it act as a dropdown that I can then use the links to the other pages for to navigate this page. The button shows up when it's needed and it is a button, when hovered on or clicked it changes to grey. However clicking it does northing.
My HTML and CSS:

/* navbar styling */

.navbar {
  position: fixed;
  width: 100%;
  z-index: 999;
  padding: 30px 0;
  font-family: 'Ubuntu', sans-serif;
  transition: all 0.3s ease;
}

.navbar.sticky {
  padding: 15px 0;
  background: crimson;
}

.navbar .max-width {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar .logo a {
  color: #fff;
  font-size: 35px;
  font-weight: 600;
}

.navbar .logo a span {
  color: crimson;
  transition: all 0.3s ease;
}

.navbar.sticky .logo a span {
  color: #fff;
}

.navbar .menu li {
  list-style: none;
  display: inline-block;
}

.navbar .menu li a {
  display: block;
  color: #fff;
  font-size: 18px;
  font-weight: 500;
  margin-left: 25px;
  transition: color 0.3s ease;
}

.navbar .menu li a:hover {
  color: crimson;
}

.navbar.sticky .menu li a:hover {
  color: #fff;
}

/* menu btn styling */

.menu-btn {
  color: #fff;
  font-size: 23px;
  cursor: pointer;
  display: none;
}

.scroll-up-btn {
  position: fixed;
  height: 45px;
  width: 42px;
  background: crimson;
  right: 30px;
  bottom: 10px;
  text-align: center;
  line-height: 45px;
  color: #fff;
  z-index: 9999;
  font-size: 30px;
  border-radius: 6px;
  border-bottom-width: 2px;
  cursor: pointer;
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s ease;
}

.scroll-up-btn.show {
  bottom: 30px;
  opacity: 1;
  pointer-events: auto;
}

.scroll-up-btn:hover {
  filter: brightness(90%);
}

    Edward Wynman
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="true" aria-label="Toggle navigation">

    </button>

          Home

          About

          Courses

          Projects

            Resume

            Contact

A: It is pretty easy to fix with the use of some Javascript, as you can see with this snippet, you can now make it collapse and uncollapse when clicking the button.

var navbar = document.getElementById("navbarNav");

function hideShow() {
  if (navbar.style.display == "block") {
    navbar.style.display = "none";
  } else {
    navbar.style.display = "block";
  }
}
/* navbar styling */

.navbar {
  position: fixed;
  width: 100%;
  z-index: 999;
  padding: 30px 0;
  font-family: 'Ubuntu', sans-serif;
  transition: all 0.3s ease;
}

.navbar.sticky {
  padding: 15px 0;
  background: crimson;
}

.navbar .max-width {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar .logo a {
  color: #fff;
  font-size: 35px;
  font-weight: 600;
}

.navbar .logo a span {
  color: crimson;
  transition: all 0.3s ease;
}

.navbar.sticky .logo a span {
  color: #fff;
}

.navbar .menu li {
  list-style: none;
  display: inline-block;
}

.navbar .menu li a {
  display: block;
  color: #fff;
  font-size: 18px;
  font-weight: 500;
  margin-left: 25px;
  transition: color 0.3s ease;
}

.navbar .menu li a:hover {
  color: crimson;
}

.navbar.sticky .menu li a:hover {
  color: #fff;
}

/* menu btn styling */

.menu-btn {
  color: #fff;
  font-size: 23px;
  cursor: pointer;
  display: none;
}

.scroll-up-btn {
  position: fixed;
  height: 45px;
  width: 42px;
  background: crimson;
  right: 30px;
  bottom: 10px;
  text-align: center;
  line-height: 45px;
  color: #fff;
  z-index: 9999;
  font-size: 30px;
  border-radius: 6px;
  border-bottom-width: 2px;
  cursor: pointer;
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s ease;
}

.scroll-up-btn.show {
  bottom: 30px;
  opacity: 1;
  pointer-events: auto;
}

.scroll-up-btn:hover {
  filter: brightness(90%);
}

    Edward Wynman
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="true" aria-label="Toggle navigation" onclick="hideShow()">

    </button>

          Home

          About

          Courses

          Projects

            Resume

            Contact


text:
Q: react native sound typescript not working import Sound from 'react-native-sound';
import Tab from '../router/bottomTabNav';
import {Button} from 'react-native';
import mp3 from './Sound5/5.mp3';

interface mp3 {
  mp3: mp3;
}

function AudioClock() {
Sound.setCategory('Playback');
const audioFile = new Sound((mp3), (error) => {
  if (error) {
    console.log('failed to load the sound', error);
    return;
  }

  // loaded successfully
  console.log('duration in seconds: ' + audioFile.getDuration() + 'number of channels: ' + audioFile.getNumberOfChannels());

  audioFile.setVolume(1);
audioFile.setPan(1);

 audioFile.play((success) => {
    if (success) {
      console.log('successfully finished playing');
    } else {
      console.log('playback failed due to audio decoding errors');
    }
  });
});

      <Button
        title="Say time"
        onPress={Tab}
      />
}

updated the asset.d.ts and tsconfig.json respectively

declare module "*.mp3" {
    const value: any;
    export default value;
  }

"include": [
      "src/*",
      "types/*"

on click of Tab, no sound, if in the beginning i do
const audioFile = new Sound((Sound.mp3), (error) => {
instead of const audioFile = new Sound((mp3), (error) => {

there is a mp3 type error. either way i know importing on typescript broken for audio but i thought this would work.

it's such simple functionality but so problematic in typescript it seems. i did leverage this code from an alarm clock function so let me know if anything suspect there, although i do see it as a wider. ts mp3 issue. lmk thanks

A: I am not pursuing this further for i had a book between stripe payments/swift and react-native-sound that was too problematic, broke my system thrice over, so i am abandoning this side project for now. Anyone else experience such. Shit, we say problematic like we so influential who the loon when he loom above the damner referential, not to mention i couldnt get the native-sound to work in the first place although an xCode import and adding references and components was starting to work, a file didnt have sound, wrong file type and button reference, didnt call release, you know the plain o gambit. Even the kubrikian elegence of futurist elva classico nutly bliss isnt tatermaib dalvi worth me jumpi outhf a window like a god dam metal jacket psh


text:
Q: Change all nonzero numbers in big.matrix to 1 How do I change all nonzero values to 1 while using an object of class big.matrix? If I convert to normal matrix, the object size is over 2gb (10^7 columns, 100 rows), so this is not feasible.
Thanks!

A: You can use Rcpp to do that (put this code in an .cpp file and source it with Rcpp::sourceCpp):
// [[Rcpp::depends(BH, bigmemory)]]
#include <bigmemory/MatrixAccessor.hpp>
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void to_one(SEXP bm_addr) {

  XPtr<BigMatrix> xptr(bm_addr);
  MatrixAccessor<double> macc(*xptr);

  for (size_t j = 0; j < macc.ncol(); j++)
    for (size_t i = 0; i < macc.nrow(); i++)
      if (macc[j][i] != 0) macc[j][i] = 1;
}

/*** R
library(bigmemory)
r <- 100
c <- 10000
bm <- matrix(sample(0:4, r * c, replace = TRUE), r, c)
bm <- as.big.matrix(bm, type = "double")
bm[, 1]
to_one(bm@address)
bm[, 1]
*/


text:
Q: semicolon/curly bracket syntax error in java When I try the below code, I get the following exception:

Syntax error on token ";", { expected

public int getValue(int row, int column) ;
    return row + column;

But when I change it to the below code, I get this exception:

Abstract methods do not specify a body

public int getValue(int row, int column) {
    return row + column;
}

How can I write this without getting a syntax error?

A: I made an example that is working, I hope it helps. If you have any questions most comment will try to help.
public class Test {
    private int array[][] = new int[10][10];
    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.getValue(1, 5));
        System.out.println(test.getValue2(2, 3));
    }

    //Get the value of parameters
    public int getValue(int row, int column){
        return (row+column);
    }
    //Get the value of an attribute
    public int getValue2(int row, int column){
        return array[row][column];
    }

}

If you are wanting to make a statement on an interface it looks like this:
public interface TestInterface {
    default int getValue(int row, int column){
        return row + column;
    }
}

If this is the goal then you have some architectural problem, but I think it's just the name "interface" instead of "class."

A: I think this is an interface class, thats why you are getting "Abstract methods do not specify a body" error. Please go through this link, It may give you good understanding about interface in java.


text:
Q: Where's the syntax error in this (f)lex snippet? I'm having a great time doing a lexer using flex. Problem is, my code editor doesn't color the syntax of the file, and it seems my rule has an error in it. Since I'm not too sure about how to use single quotes and double quotes inside intervals, I thought I'd share that snippet with you:
[^\\\'\n]+
{
    wchar_t* string;
    utf8_decode(yytext, &string);
    yyextra->append(string);
    free(string);
}

Flex tells me there's an 'unrecognized rule' on the utf8_decode line. If I remove the whole rule, things look fine again.
Can anyone tell what I'm doing wrong here?

A: The action must begin on the same line as the pattern.  So use
[^\\\'\n]+ {
    wchar_t* string;
    utf8_decode(yytext, &string);
    yyextra->append(string);
    free(string);
}


text:
Q: how to use grep to match partial occurrence of searched string my text file :
vol0 0.9 vol2 1.2 vol3 3 vol1_1 1.4 voll_2 5
vol1 1 vol2 1.2 vol3 3 vol1_1 1.4 voll_2 5
vol2 1.3 vol2 1.8 vol3 3.2 vol1_1 1.2 voll_2 4.8
....

How to grep lines with vol1 ,i.e only 2nd line. From what i am doing, it is taking all the three line.

A: I'm assuming you only want to match "vol1" as a distinct word, not "vol1_1",
With grep, use the -w flag (and since you're not searching for a regex, add -F)
grep -Fw vol1 filename

With Tcl, regular expressions can include the \y zero-width constraint that matches at the start or end of a word:
set fh [open $filename r]
while {[gets $fh line] != -1} {
    if {[regexp {\yvol1\y} $line]} {
        puts $line
    }
}
close $fh


text:
Q: Null reference exceptions on properties of a newly instantiated class? What's going on here? I'm toying around with a 3rd party library and something has me absolutely puzzled.
When I instantiate this class, immediately all of the properties of the class throw exceptions before any more code even runs.  Why is this happening?  It's not just this TypedSegmentPWK class, it's all of the typedsegment classes.. of which there are many.

Simple instantiation fails
Imports OopFactory.X12.Parsing
Imports OopFactory.X12.Parsing.Model
Imports OopFactory.X12.Parsing.Model.Typed

....

Dim test As New TypedSegmentPWK
test.PWK04_EntityIdentifierCode = "blah"

Assigning a value to PWK04_EntityIdentifierCode or any other property of test fails with a null reference exception.
TypedSegmentPWK:
Namespace OopFactory.X12.Parsing.Model.Typed
Public Class TypedSegmentPWK
    Inherits TypedSegment

    Public Sub New()

    Public Property PWK01_ReportTypeCode As String
    Public Property PWK02_ReportTransmissionCode As String
    Public Property PWK03_ReportCopiesNeeded As Integer?
    Public Property PWK04_EntityIdentiferCodeEnum As EntityIdentifierCode
    Public Property PWK04_EntityIdentifierCode As String
    Public Property PWK05_IdentificationCodeQualifier As String
    Public Property PWK05_IdentificationCodeQualifierEnum As IdentificationCodeQualifier
    Public Property PWK06_IdentificationCode As String
    Public Property PWK07_Description As String
    Public Property PWK08_ActionsIndicated As String
    Public Property PWK09_RequestCategoryCode As String
End Class

End Namespace
TypedSegment:
Namespace OopFactory.X12.Parsing.Model
Public MustInherit Class TypedSegment
    Protected Sub New(segmentId As String)

    Public Event Initialized As EventHandler
    Public Event Initializing As EventHandler

    Protected Overridable Sub OnInitialized(e As EventArgs)
    Protected Overridable Sub OnInitializing(e As EventArgs)
End Class

End Namespace
Full source here: https://github.com/KeyMarkInc/OopFactory.X12

A: All the properties reference _segment defined in TypedSegment, e.g.
public string PWK04_EntityIdentifierCode
{
    get { return _segment.GetElement(4); }
    set { _segment.SetElement(4, value); }
}

However, the _segment variable is not initialized until TypedSegment.Initialize(Container parent, X12DelimiterSet delimiters) is called...
internal void Initialize(Container parent, X12DelimiterSet delimiters)
{
    OnInitializing(new EventArgs());
    _segment = new Segment(parent, delimiters, _segmentId);
    OnInitialized(new EventArgs());
}

This is an internal method, so presumably something in this framework is supposed to call it, and not you as the user.  So, I would guess the answer is that you are using the TypedSegmentPWK class incorrectly, although I don't know what the correct way is.


text:
Q: Stackoverflow, Serverfault... Is each of them a standalone app? I am not sure here is the right place to ask it. I have compared stackoverflow.com, serverfault.com, superuser.com homepages. The HTML code is exactly the same except some labels / images /css to customize the display and of course the topics listed.
I was wondering how it works behind:

*

*Is there only a single app, a single database and query/display rules depending on the domain accessed ?

*Are these websites duplicated apps with a common database ?

*Are these websites duplicated apps with each a dedicated database ?

Thanks for your answers

A: Each Stack Exchange site shares a common codebase, but they have different styling (CSS and images) and a separate database.

A: Every web server we have (11 of them) runs the same application in IIS for every SE site.  The same exact code that runs meta also runs Stack Overflow.
In fact one web server, a single app pool even can run every SE site we have, it's just a matter of where our load balancer sends traffic.  Currently it looks like this:

*

*Stack Overflow: Webs 1-6

*Everything but SO/Meta: Webs 7-9

*Meta: Webs 10-11

....but all the servers are identical, it's just a matter of where the traffic is directed.  When a request comes in, the app determines (based on the host) which site you're asking for, and gets the appropriate database from there.  That along with settings for each site including which content folder (for CSS/images) just set some properties in the response, like where the stylesheet is, whether some things are enabled (like MathJax), etc.
Note: this applies only to our Q&A sites, Careers, stackexchange.com, the OpenID provider, StackAuth, Area51, API, APIv2 and Status are separate applications (but can also be deployed identically to all servers...the entire IIS config is the same for the entire web tier).
Each site does have it's own database, that includes meta sites (so 2 DBs per site, including meta).
There are many more things happening behind the scenes and many more per-site-settings specifics, but the above is a general high level view of what's going on.

For kicks, here's a look at our web tier...I post this because we're about to make some major changes to how things work, and it'll be interesting to see how CPU/memory drops as a result.

A: Each SE site runs on the same engine/codebase.
They have different configurations and CSS, as well as separate databases.


text:
Q: Insert new post for each user infinite loop error I wrote this little function to automatically create a post for every user of the blog but it creates an infinite loop (I disabled it to stop it creating new posts). I'm not very skilled in php, I guess the error is in the use of wp_insert_post inside the foreach, but it doesn't work simply putting it outside the braces. How can I make this function insert JUST ONE post for each author? Thanks.
$blogusers = get_users();
foreach ($blogusers as $user) {
    $my_post = array(
    'post_title'    => $user->display_name,
    'post_content'  => 'Bla bla bla.',
    'post_status'   => 'publish',
    'post_author'   => $user->ID,
    'post_type'     => 'custom'
    );

    wp_insert_post( $my_post );
}

A: With that function in functions.php it is going to run on every page load and every time it runs it is going to insert a post for every user in your database. It isn't an infinite loop. You are just running it all the time.
You need to run that one time and one time only to populate your DB with posts existing users. If you have low traffic on your blog you can just paste it in, load the page, and immediately remove it. If you have much traffic you will need a different strategy.
If you want to insert a post for new users, you need to hook a similar function into the user registration system. Something like...
function create_user_post($user_id) {
    $user = get_userdata($user_id);
    $my_post = array(
    'post_title'    => $user->display_name,
    'post_content'  => 'Bla bla bla.',
    'post_status'   => 'publish',
    'post_author'   => $user->ID,
    'post_type'     => 'custom'
    );

    wp_insert_post( $my_post );
}
add_action('user_register','create_user_post');

I just made that up off the top of my head, but I think it will work. You are just complicated enough with this that it might take some implementing and then debugging. :)
For reference: get_userdata, user_register


text:
Q: QuickLook Plugin UTI on Big Sur not working properly I have a strange issue with a QuickLook generator I'm building for Google Drive.
The "*.gdoc" files on my computer have a UTI of be.gdoc.quicklook as shown by running mdls -name kMDItemContentType /Volumes/GoogleDrive/My\ Drive/*.gdocin terminal
And my QL generator qlmanage -m correctly shows that be.gdoc.quicklook -> /Users/itai/Library/QuickLook/GoogleDriveGenerator.qlgenerator
Moreover, when I run qlmanage -p -c "be.gdoc.quicklook" some_file.gdoc I get the correct preview of the file contents using the generator
But when I run qlmanage -p some_file.gdoc my custom generator isn't invoked. Likewise, when I press spacebar in finder my custom generator is not invoked
$ qlmanage -p dummy.gdoc
Testing Quick Look preview with files:
    dummy.gdoc
2021-09-03 16:06:26.637 qlmanage[74068:14229274] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x6e03, name = 'com.apple.coredrag'
See /usr/include/servers/bootstrap_defs.h for the error codes.
2021-09-03 16:06:26.678 qlmanage[74068:14229274] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x854b, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.

$ qlmanage -p dummy.gdoc -c "be.gdoc.quicklook"
Testing Quick Look preview with files:
    dummy.gdoc
    - force using content type UTI: be.gdoc.quicklook
2021-09-03 16:06:33.320 qlmanage[74083:14229555] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x6703, name = 'com.apple.coredrag'
See /usr/include/servers/bootstrap_defs.h for the error codes.
2021-09-03 16:06:33.356 qlmanage[74083:14229555] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x7e03, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.

The permission denied error is not related in my opinion because in the -c case everything works. Moreover, qlmanage -p some_picture.jpeg also shows that permission denied error, so it seems to be an error that shows up even for System plugins.
Please note that this same plugin worked just fine on Mojave. Note also that I have other custom QL plugins that seem to work just fine on their respective UTI files


text:
Q: Factors (the data structure) in R I am teaching myself R using a textbook written by Richard Cotton and have gotten to the chapter on factors. The book says that  for
heights <- data.frame(height_cm = c(153, 181, 150, 172, 165, 149, 174, 169, 198, 163),
                      gender = c("female", "male", "female", "male", "male",
                                 "female", "female", "male", "male", "female"))

heights$gender is a factor but whenever I call class(heights$gender) it returns "character". My question is: why is it a character vector instead of a factor like the textbook says it should be?


text:
Q: Dispatcher.Invoke hangs in WordAddin I have written a WordAddIn that allows the user to call on some metadata for the current document. Via a custom button in the ribbon, they can call a WPF. The WPF calling is realized as follows:
        System.Windows.Application app = null;

and then in the method called by the button:
if (app == null)
{
    app = new System.Windows.Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
    app.Run();
}
MainWindow win = new MainWindow(graph);
app.Dispatcher.Invoke((Action)(() => { win.Show(); }));

The first time the button is clicked after Word started, nothing happens and it becomes impossible to edit content in the word document. The second time the button is clicked the WPF object loads and is shown, this works for any button click afterwards too. So it seems the first time the dispatcher is called, it hangs. How do I prevent this?

A: I'm not sure why you want to dispatch the call anyway since this is the same thread. You only need to marshall calls to UI thread when the "current" thread is not a UI thread, which is not your case - you only have one thread.
Secondly, Application.Run is a blocking method and should not be called in the Add-In context. You can't create a WPF application inside Add-In application. BTW, Application.Run always runs on the current thread, which in your case is the same one Word Add-In runs on. And this how it is supposed to be.
If I understand you correctly, you are creating a WPF application because you don't want to use WinForms technology but WPF. Do it without Application.Run and do not dispatch calls because there is no reason to do so.

A: I got help with this in the Microsoft WPF forums. Creating and calling app in a new thread does the trick, as app does indeed block the current thread it is called in.
                    if (app == null)
                    {
                        Thread thread = new Thread(new ThreadStart(() =>
                            {
                                app = new System.Windows.Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
                                autoResetEvent.Set();
                                app.Run();
                            }));
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                    }
                    else
                    {
                        autoResetEvent.Set();
                    }
                    autoResetEvent.WaitOne(); //wait until app has been initialized on the other thread
                    app.Dispatcher.Invoke((Action)(() => { new MainWindow(graph).Show(); }));
                    }


text:
Q: Select groups with the three biggest values Consider this data:
---+-----------+-------+--+
| id |   name    | grade |  |
+----+-----------+-------+--+
| 13 | Maria     |    10 |  |
| 18 | Lorenzo   |    10 |  |
|  2 | Cissa     |    10 |  |
|  3 | Neto      |     9 |  |
| 15 | Gabriel   |     9 |  |
| 10 | Laura     |     9 |  |
| 12 | Joãozinho |     8 |  |
| 16 | Sergio    |     8 |  |
|  8 | Adriele   |     8 |  |
|  6 | Jorgito   |     8 |  |
|  5 | Aline     |     8 |  |
|  1 | Cintia    |     8 |  |
| 19 | Fabiana   |     7 |  |
| 11 | Vinicius  |     7 |  |
|  9 | Tatiane   |     7 |  |
|  7 | Chico     |     7 |  |
|  4 | Marcos    |     7 |  |
| 14 | Pedro     |     6 |  |
| 17 | Mauricio  |     6 |  |
| 20 | Leonardo  |     6 |  |
+----+-----------+-------+--+

I need the students with the three biggest grades. I think I need to group the data by grade and limit to the top 3 groups.
"SELECT * FROM student GROUP BY grade LIMIT 3" only gives me 3 rows, that's not what I want.
I've tried to use HAVING to filter the groups, but without success. I don't want to set the filter grade>MAX(grade)-2, because theoretically I will not know the grades. But this filter didn't work anyway.
I'am using MySQL. Please help!

A: You can do this using a join:
select s.*
from student s join
     (select grade
      from student
      group by grade
      order by grade desc
      limit 3
     ) g3
     on s.grade = g3.grade;

In most databases, you an do this using in:
select s.*
from student s
where s.grade in (select grade
                  from student
                  group by grade
                  order by grade desc
                  limit 3
                 );

However, MySQL seems to reject this syntax.

A: select s1.*
from students s1
  join (select distinct grade from students
        order by grade desc limit 3) s2 on s1.grade = s2.grade

Alternatively:
select *
from students
where grade >= (select distinct grade from students
                order by grade desc limit 2,1)

A: select s.*
from student s join
     (select top 3 grade
      from student
      group by grade
      order by grade desc
     ) g3
     on s.grade = g3.grade;


text:
Q: Find top N elements in a Multiset from Google Collections? A Google Collections Multiset is a set of elements each of which has a count (i.e. may be present multiple times).
I can't tell you how many times I want to do the following

*

*Make a histogram (exactly Multiset)

*Get the top N elements by count from the histogram

Examples: top 10 URLs (by # times mentioned), top 10 tags (by # times applied), ...
What is the canonical way to do #2 given a Google Collections Multiset?
Here is a blog post about it, but that code is not quite what I want.  First, it returns everything, not just top N.  Second, it copies (is it possible to avoid a copy?). Third, I usually want a deterministic sort, i.e. tiebreak if counts are equal.  Other nits: it's not static, etc.

A: I wrote methods with the basic functionality you're asking for, except that they perform copies and lack deterministic tie-breaking logic. They're currently internal to Google, but we may open-source them at some point. This Guava issue has the method signatures.
Their algorithm is similar to the blog post: sorting a list of entries. It would be faster, but more complicated, to use a better selection algorithm.
EDIT: since Guava 11, this is implemented

A: To give another perspective for people to comment on, I'll post a slightly modified version of the blog post I referenced:
package com.blueshiftlab.twitterstream.summarytools;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multiset;
import com.google.common.collect.Ordering;
import com.google.common.collect.Multiset.Entry;

public class Multisets {
    // Don't construct one
    private Multisets() {
    }

    public static <T> ImmutableList<Entry<T>> sortedByCount(Multiset<T> multiset) {
        Ordering<Multiset.Entry<T>> countComp = new Ordering<Multiset.Entry<T>>() {
            public int compare(Multiset.Entry<T> e1, Multiset.Entry<T> e2) {
                return e2.getCount() - e1.getCount();
            }
        };
        return countComp.immutableSortedCopy(multiset.entrySet());
    }

    public static <T> ImmutableList<Entry<T>> topByCount(Multiset<T> multiset,
            int max) {
        ImmutableList<Entry<T>> sortedByCount = sortedByCount(multiset);
        if (sortedByCount.size() > max) {
            sortedByCount = sortedByCount.subList(0, max);
        }

        return sortedByCount;
    }
}


text:
Q: The intersection assumption in the definition of direct sums Let $W_1,W_2,\ldots,W_k$ be subspaces of a vector space $V$. We define the sum of these spaces to be the set
$$\{v_1+v_2+\cdots+v_k:v_i\in W_i\text{ for }1\leq i\leq k\},$$
which we denote by $W_1+W_2+\cdots+W_k$ or simply by $\sum_{i=1}^k W_i.$ If, in addition, $W_j\cap\sum_{i\not=j}W_i=\{\mathbf 0\}$ for each $j$, then we call $V$ the direct sum of $W_1,W_2,\ldots,W_k$ and write $V=W_1\oplus W_2\oplus\cdots\oplus W_k$. What I'm concerned about is whether we can prove that the intersection of all subspaces in the direct sum is the zero space, that is,
$$\bigcap_{i=1}^k W_i=\{\mathbf 0\}.$$
I think this is weaker than the statement that each subspace intersects the sum of the other subspaces only in the zero vector but don't know how to justify it. Please give me some help. Thank you.

A: $\{\mathbf 0
\}\subseteq W_j\cap W_l\subseteq W_j\cap\sum_{i\not=j}W_i=\{\mathbf 0\}$ for all $l\not=j$. Thus also $\bigcap_{i=1}^k W_i=\{\mathbf 0\}$.
Moreover, let $V=\mathbb{R}^2$, $W_1=\mathbb{R}(1,0)$, $W_2=\mathbb{R}(0,1)$, $W_3=\mathbb{R}(1,1)$. The $W_1\cap W_2\cap W_3=\{(0,0)\}$, but $W_3\cap (W_1+W_2)=W_3\not=\{(0,0)\}$.

A: It suffices to see that for $i\neq j$, we have $W_i \cap W_j=\{0\}$ (if we add more sets to the intersection, it can only get smaller, but since all the $W_k$ contain $0$, the intersection remains the zero space).
The inclusion "$\supseteq$" is easy, as both $W_i$ and $W_j$ contain $0$.
The other inclusion "$\subseteq$" follows from the direct sum:
$$W_i\cap W_j\subseteq W_i \cap \sum_{k\neq i} W_k = \{0\}.$$

A: Your concern is right.
Whenever , we are taking about the direct sum of subspaces , then it means also that the sum of the subspaces which are orthogonal complements of each others.
Then from this we can directly deduce that $\bigcap_{i=1}^k W_i=\{0\}.$
Whenever, "orthogonal complement" can't be usable,
Then, clearly, it's the obvious fact that $\{0\} \subseteq \bigcap_{i=1}^k W_i $ , as each $ W_i $ is a subspace.
Now, if possible let there be some non zero vectors (e.g. vector $a $) other than $ 0 $ in $\bigcap_{i=1}^k W_i $ , so, in each $ W_i $ .
Then, $W_j\cap\sum_{i\not=j}W_i $ should contain non zero vectors other than $ 0 $ , as , $W_j\cap\{0, a+0+0+......\text { 0's k-2 times } \} ⊂ W_j\cap\sum_{i\not=j}W_i $,(since each $ W_i $ contains vector $ a $)
But this is a contradiction to $W_j\cap\sum_{i\not=j}W_i = \{0\} $.
So, $\bigcap_{i=1}^k W_i=\{0\}.$


text:
Q: NullPointerException , while trying to retrieve values from JSON object , usin facebook graph api? I am trying to retrieve values from Json Object but getting Exception.I am trying to fetch my facebook profile info , using  facebook graph api.
ProfileRequestListner.java
public void onComplete(final String response, final Object state)
{

    try
    {
        // process the response here: executed in background thread
        Log.d("Facebook-Example", "Response: " + response.toString());
         JSONObject json = Util.parseJson(response);

        final String name = json.getString("name");

      Bundle b = new Bundle();
       b.putString(SoapboxApplication.FIRST_NAME, name);
      //  b.putString(SoapboxApplication.LAST_NAME,last_name);
       com.android.soapbox.SoapboxApplication.mListener.**ProfileInfoAvailable**(b);
    }

    catch (JSONException e)
    {
        Log.w("Facebook-Example", "JSON Error in response");
        Log.e("Facebook-Example", "JSON Error in response"+e.fillInStackTrace());
    }
    catch (FacebookError e)
    {
        Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
    }
}

ProfileInfoAvailable(Bundle b) is defined as
public class ProfileInfoListner extends Activity implements ProfileEventListener
{
public EditText mFirstNameTextBox  ;
public TextView mLastNameTextBox;

public void ProfileInfoAvailable(Bundle b)
{
 Log.e("Facebook-Example", "HGGGGGGGGGGGGGGGGGGG");

try
{
    for (String key : b.keySet())
    {
        if(key.compareTo(SoapboxApplication.FIRST_NAME) == 0)
        {
            Log.e("Facebook-Example", "IIIIFFFFFFFFFFFFFFF");
            //Assuming mFirstNameTextBox points to the textbox on PRofile screen

            mFirstNameTextBox.setText(b.getString(key));

        }
        else if(key.compareTo(SoapboxApplication.LAST_NAME) == 0)
        {

            //Assuming mLastNameTextBox points to the textbox on Profile screen
            mLastNameTextBox.setText(b.getString(key));

        }
}
}
catch(NullPointerException c)
{
    Log.e("EEEEERRROOROROROORR",""+c.fillInStackTrace());
}

}
}

What wrong with that.??
Any help would be highly appropriated.

A: What is null is the EditText mFirstNameTextBox (and the following TextView) also, since you are not initializing them to anything as I can see.
If you are defining those in an XML file, use a LayoutInflater and the method findViewById() to obtain the reference to those resources.


text:
Q: Change and wrap keyword integers without loop in C I'm writing a program that accepts a string at the command prompt then converts each character of the string to corresponding 0-25 digit of the alphabet. Each digit is then used to encipher each character of another string the user enters after being prompted by the program. Each alphabetic character of the second string should match the order of the string of integers and the string of integers will wrap if the second string is longer. The goal of the program is the use the first string as a key to shift each character of a message (the second string).
Example (desired output):
User runs program and enters keyword: bad
User is prompted to enter string of alphabetical characters and punctuation only: Dr. Oz
Program converts keyword 'bad' into 1,0,3
Program enciphers message into Er. Ra
What I actually get is:
… T.B.S. …

I've tried many things but unfortunately I can't seem to figure out how to loop and wrap the key without looping the second message. If you run the program you will see my problem.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int shift(char key1);

int main(int argc, string argv[]) // user enter number at cmd prompt
{
    if (argv[1] == '\0')
    {
        printf("Usage: ./vigenere keyword\n");
        return 1;
    }
    string key = argv[1]; // declare second arg as string
    for (int i = 0, n = strlen(key); i < n; i++)
        if (isdigit(key[i]) != 0 || argc != 2)
        {
            printf("Usage: ./vigenere keyword\n");
            return 1;
        }
    string text = get_string("plaintext: ");
    printf("ciphertext: ");
    int k;
    char t;

    for (int j = 0, o = strlen(text); j < o; j++)
    {
        t = text[j];
        for (int i = 0, n = strlen(key); i < n; i++)
        {
            k = shift(key[i]);
            if (isupper(t))
            {
                t += k;
                if (t > 'Z')
                {
                    t -= 26;
                }
            }
            if (islower(t))
            {
                t += k;
                if (t > 'z')
                {
                    t -= 26;
                }
            }
            printf("%c", t);
        }
    }

    printf("\n");
}

int shift(char key1)
{
    int k1 = key1;
    if (islower(key1))
    {
        k1 %= 97;
    }
    if (isupper(key1))
    {
        k1 %= 65;
    }
    return k1;
}

I appreciate any help and suggestions but please keep in mind the solution should match the level of coding my program suggests. There may be many advanced ways to write this program but unfortunately we are still in the beginning of this course so showing new methods (which I will definitely try to understand) may go over my head.

A: Here's a modified version of your code, with changes based on my comments:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int shift(char key1);

int main(int argc, string argv[]) // user enter number at cmd prompt
{
    if (argc != 2 || argv[1][0] == '\0')
    {
        fprintf(stderr, "Usage: ./vigenere keyword\n");
        return 1;
    }
    string key = argv[1]; // declare second arg as string
    for (int i = 0, n = strlen(key); i < n; i++)
    {
        if (!isalpha(key[i]))
        {
            fprintf(stderr, "Usage: ./vigenere keyword\n");
            return 1;
        }
    }
    string text = get_string("plain text: ");
    printf("ciphertext: ");

    int keylen = strlen(key);
    int keyidx = 0;
    for (int j = 0, o = strlen(text); j < o; j++)
    {
        int t = text[j];
        if (isupper(t))
        {
            int k = shift(key[keyidx++ % keylen]);
            t += k;
            if (t > 'Z')
                t -= 26;
        }
        else if (islower(t))
        {
            int k = shift(key[keyidx++ % keylen]);
            t += k;
            if (t > 'z')
                t -= 26;
        }
        printf("%c", t);
    }

    printf("\n");
}

int shift(char key1)
{
    if (islower(key1))
        key1 -= 'a';
    if (isupper(key1))
        key1 -= 'A';
    return key1;
}

The test for exactly two arguments and for a non-empty key are moved to the top.  This is slightly different from what was suggested in the comments.  The error messages are printed to standard error, not standard output.  I'd probably replace the second 'usage' message with a more specific error — the key may only contain alphabetic characters or thereabouts.  And the errors should include argv[0] as the program name rather than hard-coding the name.  The key validation loop checks that the key is all alphabetic, rather than checking that they are not digits — there are more character classes than digits and letters.  The code uses keyidx and keylen to track the length of the key and the position in the key.  I use single-letter variable names, but usually only for loop indexes or simple pointers (usually pointers into strings); otherwise I use short semi-mnemonic names.  There are two calls to shift() so that keyidx is only incremented when the input character is a letter.  There are other ways that this could be coded.
One very important change not foretold in the comments is the change of type for t — from char to int.  When it is a char, if you encrypt letter z with a letter late in the alphabet (e.g. y), the value 'z' + 24 overflows the (signed) char type prevalent on Intel machines, giving a negative value (most typically; formally, the behaviour is undefined).  That leads to bogus outputs.  Changing to int fixes that problem.  Since the value of t is promoted to int anyway when passed to printf(), there is no harm done in the printing.  I used the prompt plain text: with a space so that the input and output align on the page.
I decided not to use the extra local variable k1 in shift().  I also used subtraction instead of modulus as noted in the comments.
Given the program cc59 created from cc59.c, a sample run is:
$ cc59 bad
plain text: Dr. Oz
ciphertext: Er. Ra
$ cc59 zax
plain text: Er. Ra
ciphertext: Dr. Oz
$ cc59 ablewasiereisawelba
plain text: The quick brown fox jumps over the lazy dog. Pack my box with five dozen liquor jugs. The five boxing wizards jump quickly. How vexingly quick daft zebras jump. Bright vixens jump; dozy fowl quack.
ciphertext: Tip uqius fisef fkb uvmpt zzar lpi cehq dkk. Abck nj fkx oqxy jqne zskfn ljbykr bckj. Xpw fezp coxjyk sirivuw rmml ufjckmj. Lkw nmbzrody mytdk dbqx vetzej ncep. Xvthht wtbank rydt; lgzu jzxl qvlgg.
$ cc59 azpweaiswjwsiaewpza
plain text: Tip uqius fisef fkb uvmpt zzar lpi cehq dkk. Abck nj fkx oqxy jqne zskfn ljbykr bckj. Xpw fezp coxjyk sirivuw rmml ufjckmj. Lkw nmbzrody mytdk dbqx vetzej ncep. Xvthht wtbank rydt; lgzu jzxl qvlgg.
ciphertext: The quick brown fox jumps over the lazy dog. Pack my box with five dozen liquor jugs. The five boxing wizards jump quickly. How vexingly quick daft zebras jump. Bright vixens jump; dozy fowl quack.
$

The decrypting keys were derived by matching the 'encrypting' letters in row 1 with the decrypting letters in row 2 of the data:
abcdefghijklmnopqrstuvwxyz
azyxwvutsrqponmlkjihgfedcb

With encryption and decryption, the most basic acid test for the code is that the program can decrypt its own encrypted output given the correct decrypting key and the cipher text.


text:
Q: ¿Como evito volver a la pantalla de Login una vez logueado en Angular 8? Hice una aplicación con un Login, pero una vez me logueo y le doy al botón atrás este vuelve al login  aun teniendo una sesión iniciada, mi pregunta es ¿como puedo evitar esto? ya que soy nuevo en Angular.
Este es mi Guard
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { AuthService } from '../shared/services/auth.service';

@Injectable({
  providedIn: 'root'
})
export class GuardAuthGuard implements CanActivate {

  constructor( private auth: AuthService, private router: Router ) {}

  canActivate(): boolean {
    if (this.auth.authentication()) {
 this.router.navigateByUrl('/login');
    } else {
      return true;
    }
  }

}

A: Lo mejor que podés hacer es implementar un segundo Guard, pero solo para el LoginComponent que, como ya lo tenés en tu Guard, detecte si ya estás logeado.
Si estás logeado: redirigir a la pagina principal. En este caso podría ser un Dashboard o lo que deseas que se muestre al iniciar la sesión.


text:
Q: SumProduct with 2 criterias including wildcard I have SumProduct working but it does not seem to be capturing all the values.
Here is a sample data:

I would like to match WiFi Services*, Day and then sum up the values in Column I.
This is my formula that does not seem to be capturing call the correct minutes.
=SUMPRODUCT((LEFT(Table164[Call Description],13)="WiFi Services")*(Table164[Time Rate]=AA20)*(Table164[Mins]))

Cell AA20 is referring to the Time Rate: Day
Does anyone have an idea why the above formula is not capturing everything or they have a better approach to this?
Thanks

A: Did you implement the wild card in the formula? ("WiFi Services*")

=SUMIFS(I:I,G:G,"WiFi Services*", H:H, "Day")


text:
Q: Constructor DI + Unity 2.0 + issue with resolving dependency Controller:
public class HomeController : Controller
{
    IEmployeeTask _employeeTask;

    public HomeController()
    {
        _employeeTask = new UnityContainer().Resolve<IEmployeeTask>();
    }

    public HomeController(IEmployeeTask employeeTask)
    {
        _employeeTask = employeeTask;
    }

    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult GetAndDisplayEmployee()
    {
        return View();
    }

    [HttpPost]
    public ActionResult GetAndDisplayEmployee(int empid)
    {
        return View(_employeeTask.GetEmployeeModelFromService(empid));
    }
}

Global.asax.cs:
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    var container = new UnityContainer();
    container.RegisterType<IEmployeeModelMap, EmployeeModelMap>();
    container.RegisterType<IEmployeeService, EmployeeService>();
    container.RegisterType<IEmployeeTask, EmployeeTask>();
    container.RegisterType<IEmployee, Employee>();
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

Unity Dependency Resolver:
 public class UnityDependencyResolver : IDependencyResolver
 {
     readonly IUnityContainer _container;
     public UnityDependencyResolver(IUnityContainer container)
     {
         this._container = container;
     }
     public object GetService(Type serviceType)
     {
         try
         {
             return _container.Resolve(serviceType);
         }
         catch
         {
             return null;
         }
     }
     public IEnumerable<object> GetServices(Type serviceType)
     {
         try
         {
             return _container.ResolveAll(serviceType);
         }
         catch
         {
             return new List<object>();
         }
     }
 }

Employee Task class:
 public class EmployeeTask: IEmployeeTask
 {
     IEmployeeService _employeeService;
     IEmployeeModelMap _employeeModelMap;

     public EmployeeTask(IEmployeeService employeeService, IEmployeeModelMap employeeModelMap)
     {
         _employeeService = employeeService;
         _employeeModelMap = employeeModelMap;
     }

     public EmployeeViewModel GetEmployeeModelFromService(int empId)
     {
         return _employeeModelMap.ToModel(_employeeService.GetEmployeeFromEntities(empId));
     }
}

Now, i have used unity 2.0 application block. Tried to resolve the dependency of the controller using unity with out using Custom Controller factory.
     I am stuck with below error.

The current type, DataProviderInfrastructure.IEmployeeTask, is an
  interface and cannot be constructed. Are you missing a type mapping?

A: I don't use Unity, but my guess would be that it attempts to use your parameterless constructor where you try to resolve the dependency. Creating this constructor is very very wrong. First - it defeats the purpose of having dependency injection and second - you create new container inside - which will be empty so it obviously can't resolve any dependencies. Try removing this from your code:
public HomeController()
{
    _employeeTask = new UnityContainer().Resolve<IEmployeeTask>();
}


text:
Q: Find and rename a file in bash or python I am trying to run a script in bash or python that locate an nfo file inside a dir and rename it.
Like the dir is in /home/disk/xxx/P and inside there are files and this file named b.nfo that I want to rename to 1.nfo
I tried Both bash and python with no luck
Bash
cd /home/disk/xxx/P
for f in *;do
rename ".nfo" "1.nfo"
done

Python
dir = '/home/disk/xxx/P'
x = os.listdir(dir)
for f in x:
 if f.endswith('.nfo'):
new = '/home/disk/xxx/P' +'/'+'1.nfo'
os.system('mv str(f) new')

None of these work..  What am i doing wrong?

A: Try this:os.rename(path_to_file, path_to_renamed_file)

A: import glob
for fname in glob.glob("/home/disk/*/P/*.nfo"):
    print "Found :",fname
    # now rename it or whatever ...
    new_name = fname.replace(".nfo",".1.nfo")
    os.rename(fname,new_name)

the same files would match in bash with ls /home/disk/*/P/*.nfo

A: To rename a file in python you can use os.rename(src, dest) http://www.tutorialspoint.com/python/os_rename.htm
As for your own code, it didn't work because os.system('mv str(f) new') actually executed the command "mv str(f) new". if you want to use params you should have done: os.system('mv %s %s' % (f, new)). But anyway don't use os.system, use os.rename(). Its much cleaner and will work on all platforms.

A: If this is just a single file as it appears you are doing...try:
#!/bin/bash
cd /home/disk/xxx/P
findIt=$(find . -type f -name b.nfo)
if [[ ${findIt} != "" ]] ; then
  mv ${findIt} 1.nfo
else
  echo "File was not found"
fi

A: You can use the modules os and glob:
import glob
import os

dir_ = '/home/disk/xxx/P'
for fn in glob.glob(os.path.join(dir_, '*.nfo')):
    os.rename(fn, os.path.join(os.path.split(fn)[0], '1.nfo'))

A: I'm not sure what you want to do. In increasing levels of complexity:
mv /home/disk/xxx/P/b.nfo /home/disk/xxx/P/1.nfo
or
if [ -f /home/disk/xxx/P/b.nfo   ]; then
   mv /home/disk/xxx/P/b.nfo /home/disk/xxx/P/1.nfo
else
   echo "b.nfo not found"
fi

or
for nfofile in /home/disk/xxx/P/*.nfo
do
    newname=$(echo $nfofile | <some sort of name transformation>)
    mv $nfofile $newname
done