text:
Q: AS3: Finding coordinates of a string array I'm learning AS3 and I'm programming a typewriter effect with a blinking cursor. Now I'm "cheating" moving the blinking cursor. Is there a way to locate coordinates of the string when they are shown on the screen?
var myString:String = "Lore Ipsum";
var myArray:Array = myString.split("");

stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);

function myKeyDown(e:KeyboardEvent):void{
    tf.appendText(myArray.shift());
    BlinkingCursor.x = BlinkingCursor.x + 5;
}

A: if you haven't already, check the api for the TextField object (assuming you're using a textfield and 'tf' stands for it): http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/TextField.html
There should be some methods and properties that can help. At a quick glance TextField. getLineLength() may help as it seems to return the number of characters in a line (which you can multiply by char width if using a monospaced font).
If you're using a single line of text, you can probably just use the TextField.textWidth property.

A: Untested but you can try :
function myKeyDown(e:KeyboardEvent):void{
    tf.appendText(myArray.shift());
    BlinkingCursor.x = (tf.x + tf.width) + 5;
}

and regarding...

Is there a way to locate coordinates of the string when they are shown
  on the screen?

You should already know since you put the textField on screen in first place. Just to confirm :

*

*Did you use tf.x = & tf.y = to set coords before addChild(tf)?

*Does trace("TF current X-pos : " + tf.x); do like what you want?


text:
Q: Function call difference in javascript What is the difference between these two and why would you use one over another?
MYUtils.isIOS = (function(){
    return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
}());

var ios = MYUtils.isIOS;

vs
MYUtils.isIOS = function(){
    return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
};

var ios = MYUtils.isIOS();

A: In this example, there is no strong reason to use one over the other.
The first example runs, and sets the value. The value, from that point on, does not change.
In the second example, every time you call isIOS(), you are running the inner function.  navigator.userAgent is not going to change at some point during your page life, so the result won't change.
However, should you be looking for some value that can change, perhaps checking if a certain HTML checkbox is set, or looking for a value set in localStorage then the second way is better, because you allow for a changing environment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# calling a API endpoint with CSRF token its not working I need to develop a .NET Job that triggers an execution in the HPOO software, by calling API endpoint that requires a CSRF token.
Before I started coding, I tested the scenario in Postman:

*

*calling a normal GET endpoint only with the basic authentication

*getting back a CSRF token

*and then finally calling a POST API, passing the basic authentication together with the CSRF token.

Everything worked as expected when I did these tests in Postman.
When I try to implement the same scenario in code, the program blocks when calling the POST endpoint (passing the token).
Follow my code below:
ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

var uriExecution = new Uri("https://hpoo-api.com.br/oo/rest/v2/executions");
var cookies = new CookieContainer();

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriExecution);
request.Method = "GET";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("Authorization", "Basic " + GetBasicAuthenticaton());
request.CookieContainer = cookies;

var response = request.GetResponse();

var csrf = response.Headers.Get("X-CSRF-TOKEN");

HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(uriExecution);
request2.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request2.Headers.Add("Authorization", "Basic " + GetBasicAuthenticaton());
request2.Headers.Add("X-CSRF-TOKEN", csrf);
request2.CookieContainer = cookies;

var response2 = request2.GetResponse();

At the moment my code calls the method GetResponse() of request2, I get a exception saying I'm forbidden to access (403).
I tried with HttpClient library too, but I got the same error, specifying that I'm forgetting the CSRF token.
Some things that I already tried which have not worked:

*

*Created a new CookieContainer, with all cookies in the first request, and pass to the request2.

*Removed the CSRF header, only cookies.

*Removed the cookies, only passing the header.

*Removed the CSRF header, only passing the CSRF query and cookies.

*Removed basic authentication, only passing the CSRF header and cookies.

Please, someone could help me?
Sorry for my bad english, brazilian here...

A: I found out the problem. Even colleting the cookies from first request and storing in a CookieContainer, the second request wasn't sending the cookies. After some search, I see its possible to send cookies in header, like this:
request.Headers.Add("Cookie", "cookie1=value1; cookie2=value2");

This way works like a charm, I only have to understand why using CookieContainer doesn't work...


text:
Q: MVC3 maproute where first value of URL is querstring for default controller and action I want to make a route something like this:
routes.MapRoute(
            "Default", // Route name
            "{s}", // URL with parameters
            new { controller = "Home", action = "Index", s = UrlParameter.Optional }
        );

Where s is a parameter for the default controller and action.. Is this possible? i would also settle for something like:
routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{s}", // URL with parameters
            new { controller = "Home", action = "Index", s = UrlParameter.Optional }
        );

        routes.MapRoute(
            "qMap", // Route name
            "sc/{s}", // URL with parameters
            new { controller = "Home", action = "Index", s = UrlParameter.Optional }
        );

But neither work.. i suspect because the first element/paramater is always expected to be a controller?

A: If you have only the following route definition (make sure you have removed all other route definitions from your RegisterRoutes method):
routes.MapRoute(
    "Default",
    "{s}",
    new { controller = "Home", action = "Index", s = UrlParameter.Optional }
);

and the following controller:
public class HomeController: Controller
{
    public ActionResult Index(string s)
    {
        ...
    }
}

a request of the form http://foo.com/abc would be routed to the Home controller and the Index action will be invoked and passed s=abc.


text:
Q: Testing a Docker image in Jenkins I've been searching around but I can't seem to find anything on how to do this except using curl (but that is only for integration tests).
I have setup my Jenkins to get codes from GitHub, build the Docker image and push a repo. This I have done. What I can't find is how to test the Docker image before and after build. I have the unit and integration test in the GitHub repo, so it is cloned together with the codes.
My application is a flask app, using Flask and JWT_Flask_Extended.
How can I code the jenkinsfile to run the unit test before build and integration test after build of the Docker image.
I'm using python3. Can someone point me in the right direction?
Thanks.


text:
Q: Java code for calculating GCD and LCM of two numbers is working fine but not being accepted on one of the online platforms below is my code for calculating gcd and lcm of two numbers. When i try with different test cases it works fine. But when i try to submit it on online platform it says wrong
package javapractice;
import java.util.*;
public class chef_gcdlcm {

    public static void main(String[] args) {
        try{
            Scanner input = new Scanner(System.in);
            long t = input.nextInt();
            long l,s,temp;
            while(t-->0){
                long A = input.nextLong();
                long B = input.nextLong();
                temp = 1;
                if(A>B){ l = A;
                 s = B;}
                else{ l = B;
                s = A;
                }
                while(temp!=0){
                    temp = l%s;
                    if(temp!=0){
                        if(temp>s){l = temp;}
                        else{s = temp;}
                    }
                }
                long gcd = (A*B)/s;
                System.out.println(s +" "+gcd);
            }
            input.close();
        }catch(Exception e){
            e.printStackTrace();
        }

    }

}

A: your code doesn't work, here's fixed;
package javapractice;
import java.util.*;
public class chef_gcdlcm {

  public static void main(String[] args) {
    try{
        Scanner input = new Scanner(System.in);
        long t = input.nextInt();
        long l,s,temp;
        while(t-->0){
            long A = input.nextLong();
            long B = input.nextLong();
            temp = 1;
            if(A>B){
               l = A;
               s = B;
            }else{ l = B;
               s = A;
            }
            while (s != 0) {
              temp = l % s;
              if (temp > s) {
                 l = temp;
              } else {
                 l = s;
                 s = temp;
              }
            }
           long gcd = (A * B) / l;
           System.out.println(l + ":" + gcd);
        }
        input.close();
    }catch(Exception e){
        e.printStackTrace();
    }

  }

}

what you missed;

*

*you forgot set large to small (l=s) when temp is smaller than l.

*you don't have to check this: if(temp!=0) the while loop takes care of that.

*you should divide A*B to l, not to s at the end. s should come out 0.

A: It isn't necessary to do the swapping and comparing. If necessary, the values will be corrected after the first iteration.
Consider l = 24 and s = 36
save = s;    save is 36
l %= s;      l is still 24
s = l;       s is now 24
l = save     l is now 36

Modified code
try {
    Scanner input = new Scanner(System.in);
    long t = input.nextInt();
    long l, s, temp;
    while (t-- > 0) {
        l = input.nextLong();
        s = input.nextLong();
        long A = s;
        long B = l;
        // doesn't matter which is larger.  It will be corrected
        // after the first iteration.
        while (s > 0) {
             temp = s;
             l %= s;
             s = l;
             l = temp;
        }
        long lcm =  (A / l) * B; // prevents overflow
        System.out.println(l + " " + lcm);
    }
} catch (Exception e) {
    e.printStackTrace();
}

Note:  It is not necessary, useful, and in general bad practice to close the scanner when it was created with System.in.  This is because that also closes that input stream which will no longer be available for the duration of the program.


text:
Q: Why I cannot reach non-persistent listeners count from my UnityEvent? I need to know how many non-persistent listeners were added to a UnityEvent.
It seems that there is no methods giving me this number in UnityEvent class. I can only get the persistent listeners count (the ones added from editor or with UnityEvent.AddPersistentListener() ).
The only solution I have figured out is to create a child class and override the function with a count of registrations.
Here is a short code showing the problem :
    private UnityEvent myEvent;

    private void MyFunctionToHook()
    {
        // func logic
    }

    private void MyInitialisation()
    {
        myEvent.AddListener(MyFunctionToHook);
        myEvent.AddListener(MyFunctionToHook);
        myEvent.AddListener(MyFunctionToHook);

        // here, I need to know how much hooks were added.
        // ??
    }

1) Do you have any ideas of how I can manage to track this information natively?
2) Am I doing this right ? Is it wrong wanting to know this information ?
It seems weird to not have access to this info, because it could be useful in unit-tests / warnings..etc
Thanks for your time.
Here is the unityEvent documentation : https://docs.unity3d.com/ScriptReference/Events.UnityEvent.html
[EDIT]
the only solution I have found so far is the following :
    public class TrackingUnityEvent<T0> : UnityEvent<T0>
{
    private int nonPersistentListenersCount;

    public int GetNonPersistentEventCount()
    {
        return nonPersistentListenersCount;
    }

    public void AddNonPersistantListener(UnityAction<T0> call)
    {
        AddListener(call);
        nonPersistentListenersCount++;
    }

    public void RemoveNonPersistantListener(UnityAction<T0> call)
    {
        RemoveListener(call);
        nonPersistentListenersCount--;
    }
}

This way is gross because you can't tell if "RemoveListener()" and "AddListener()" are successfull as they are void.

A: Why don't you wrap the event inside another class without inheritance, so that you can count the listener? You can also add more code to the event...
public class MySpecialEvent {
    private UnityEvent event;
    public EventCount { get; private set; }

    public void AddListener(UnityAction call) {
        event.AddListener(call);
        EventCount++;
    }

    public void RemoveListener(UnityAction call) {
        event.RemoveListener(call);
        EventCount--;
    }
}


text:
Q: are "seekp" & "seekg" interchangeable? Well I just noticed that by changing the position -in microsoft visual studio- through "seekp" I implicitelly also change the read-position, when handling files.
I am wondering however if this is "portable" behaviour? Can I expect the position of reading & writing to be always the same? And consequently: will tellp & tellg always return the same value?

A: For file positions they are the same. In other words there is only one pointer maintained.
From 27.9.1.1p3:

A joint file position is maintained for both the input sequence and
  the output sequence.

So, seekg and seekp are interchangeable for file streams. However, this is not true for other types of streams, as they may hold separate pointers for the put and get positions.

A: Update: So from all the comments and everything, it seems that for fstream, seekp and seekg use the same pointer. But for stringstream and probably other non-file based streams, they are separate.

Original Post:
Doesn't work for me on linux with g++ 4.7.2. They seem to be independent:
#include <sstream>
#include <iostream>

int main(int, char**) {
    std::stringstream s("0123456789");
    std::cout << "put pointer: " << s.tellp() << std::endl;
    std::cout << "get pointer: " << s.tellg() << std::endl;
    std::cout << std::endl;
    s.seekp(2);
    std::cout << "put pointer: " << s.tellp() << std::endl;
    std::cout << "get pointer: " << s.tellg() << std::endl;
    std::cout << std::endl;
    s.seekg(4);
    std::cout << "put pointer: " << s.tellp() << std::endl;
    std::cout << "get pointer: " << s.tellg() << std::endl;
    std::cout << std::endl;
}

Output:
put pointer: 0
get pointer: 0

put pointer: 2
get pointer: 0

put pointer: 2
get pointer: 4

Also the behaviour you describe sounds like it doesn't comply with the quotes here:

Sets the position of the get pointer. The get pointer determines the
  next location to be read in the source associated to the stream.

and here:

Sets the position of the put pointer. The put pointer determines the location in the
  output sequence where the next output operation is going to take
  place.


text:
Q: Change event on TextField inside ListView Template I've a ListView Template, that has a title Label, 2 button Views (more and less) and a TextField with a value, I need to add a change event to this TextField.
<ItemTemplate name="item" id="item" bindId="item">
    <View id="row" bindId="row">
        <Label bindId="title" id="title"/>
        <View id="options" bindId="options">
            <View class="option" bindId="less" id="less"/>
            <TextField bindId="input" id="input"/>
            <View class="option" bindId="more" id="more"/>
        </View>
    </View>
</ItemTemplate>

In the change event I want to add a validation to check if the value is a number like this:
$.input.value = parseFloat(($.input.value.toString().replace(/,/g, '.')).replace(/[a-zA-Z ,_$#%&()~ºª´`'+*:;]/g,''));

The less and more buttons are working, its a simple increment/decrement, but I can't add the listener to the input, I've tried this 2 ways:
$.car.addEventListener('itemclick',function(list) {

    var row = $.car.sections[0].getItemAt(list.itemIndex);

    if(list.bindId == 'more') row.input.value++;
    if(list.bindId == 'less') row.input.value--;

    //tried this 1#: row.input.addEventListener('change',function() {});

    $.car.sections[0].updateItemAt(list.itemIndex,row);
});

//tried this 2#: $.input.addEventListener('change',function() {});

Note that I only need to use the listener when the row is clicked, every time that I change the input value or use one of the buttons, I know the index of the ListItem

A: I don't know if it's the best approach, but what I'll try is to create an hidden TextField, when I click the ListItem's TextField, blur the hidden TextField, and on the change event it will update the ListItem's TextField with the same value


text:
Q: Configure Heartbeat with Elasticsearch to parse Json Result I've configured elasticsearch, kibana and heartbeat and I do see results under "heartbeat" coming in.

However whatever processors I add to a monitor I do not see any extra data:
https://www.elastic.co/guide/en/beats/heartbeat/current/add-tags.html
- type: http
  urls: ["http://localhost:8359/api/heartbeat"]
  schedule: '@every 10s'
  processors:
  - add_tags:
    tags: [web123, production123]

I would like to store the actual JSON response which I get when i query my service: http://localhost:8359/api/heartbeat (not just HTTP 200). And would like to show this reponse in Kibana somewhere under "Uptime" section
Sample json response from endpoint:
{
    "StatusCode": 2,
    "Messages": [
        "interface not found: MyTestService"
    ],
    "Type": "MyTestService",
    "IsValid": false
}

A: Solution:
  schedule: '@every 2m'
  check.response:
    status: 200
    json:
      - description: Json Response
        condition:
          equals:
            Status: Ok

Where "Status" is one of my json properties that is being returned.


text:
Q: How to provide Apple Watch Complication Asset for 45mm? When adding assets for the Graphic Circular Complication there is no option to add an asset for the 45mm version, thus the image does not fill the available space.

Result (The image does not fill the space as it is too small):

I have read that I need to use PDF assets for the 40/42mm but my image is a raster image and thus I can't create it as a PDF. I want to scale the image myself and add it as an asset but there is no option to drop it.
What should I do?

A: The issue is that the size of the image in the asset catalog is smaller than it really should be according to the Apple Human Interface Guidelines. Thus this causes the images not to be filled. As there's no option to drop the 45mm version you need to calculate and resize the image yourself.
This article is the solution!
http://www.glimsoft.com/02/18/watchos-complications/?utm_campaign=iOS%2BDev%2BWeekly&utm_medium=web&utm_source=iOS%2BDev%2BWeekly%2BIssue%2B547
ComplicationController+Ext.swift
extension ComplicationController {
    enum ComplicationImageType {
        case graphicCircularImage
    }

    struct ComplicationImageSizeCollection {
        var size38mm: CGFloat = 0
        let size40mm: CGFloat
        let size41mm: CGFloat
        let size44mm: CGFloat
        let size45mm: CGFloat

        // The following sizes are taken directly from HIG: https://developer.apple.com/design/human-interface-guidelines/watchos/overview/complications/
        static let graphicCircularImageSizes = ComplicationImageSizeCollection(size40mm: 42, size41mm: 44.5, size44mm: 47, size45mm: 50)

        func sizeForCurrentWatchModel() -> CGFloat {
            let screenHeight = WKInterfaceDevice.current().screenBounds.size.height
            if screenHeight >= 242 {
                // It's the 45mm version..
                return self.size45mm
            }
            else if screenHeight >= 224 {
                // It's the 44mm version..
                return self.size44mm
            }
            else if screenHeight >= 215 {
                // It's the 41mm version..
                return self.size41mm
            }
            else if screenHeight >= 197 {
                return self.size40mm
            }
            else if screenHeight >= 170 {
                return self.size38mm
            }
            return self.size40mm    // Fallback, just in case.
        }

        static func sizes(for type: ComplicationImageType) -> ComplicationImageSizeCollection {
            switch type {
            case .graphicCircularImage: return Self.graphicCircularImageSizes
            }
        }

        static func getImage(for type: ComplicationImageType) -> UIImage {
            let complicationImageSizes = ComplicationImageSizeCollection.sizes(for: .graphicCircularImage)
            let width = complicationImageSizes.sizeForCurrentWatchModel()
            let size = CGSize(width: width, height: width)

            var filename: String!

            switch type {
            case .graphicCircularImage: filename = "gedenken_graphic_circular_pdf"
            }

            return renderPDFToImage(named: filename, outputSize: size)
        }

        static private func renderPDFToImage(named filename: String, outputSize size: CGSize) -> UIImage {

            // Create a URL for the PDF file
            let resourceName = filename.replacingOccurrences(of: ".pdf", with: "")
            let path = Bundle.main.path(forResource: resourceName, ofType: "pdf")!
            let url = URL(fileURLWithPath: path)

            guard let document = CGPDFDocument(url as CFURL),
                  let page = document.page(at: 1) else {
                fatalError("We couldn't find the document or the page")
            }

            let originalPageRect = page.getBoxRect(.mediaBox)

            // With the multiplier, we bring the pdf from its original size to the desired output size.
            let multiplier = size.width / originalPageRect.width

            UIGraphicsBeginImageContextWithOptions(size, false, 0)
            let context = UIGraphicsGetCurrentContext()!

            // Translate the context
            context.translateBy(x: 0, y: (originalPageRect.size.height * multiplier))

            // Flip the context vertically because the Core Graphics coordinate system starts from the bottom.
            context.scaleBy(x: multiplier * 1.0, y: -1.0 * multiplier)

            // Draw the PDF page
            context.drawPDFPage(page)

            let image = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()

            return image
        }
    }
}

ComplicationController.swift
func createGraphicCircularTemplate() -> CLKComplicationTemplate {
    let template = CLKComplicationTemplateGraphicCircularImage()
    let imageLogoProvider = CLKFullColorImageProvider()

    imageLogoProvider.image = ComplicationImageSizeCollection.getImage(for: .graphicCircularImage)
    template.imageProvider = imageLogoProvider

    return template
}


text:
Q: Why was Ollivander happy about pulling so many wands for Harry?
Harry tried. And tried. He had no idea what Mr Ollivander was waiting for. The pile of tried wands was mounting higher and higher on the spindly chair, but the more wands Mr Ollivander pulled from the shelves, the happier he seemed to become.
"Tricky customer, eh? Not to worry, we'll find the perfect match here
somewhere- I wonder, now – yes, why not – unusual combination - holly
and phoenix feather, eleven inches, nice and supple."

Why was Ollivander happy about pulling the wands?

A: Ollivander seems to be fascinated by things beyond the ordinary in magic. After Harry's wand chooses him, Ollivander says:

"Yes, thirteen-and-a-half inches. Yew. Curious indeed how these things happen. The wand chooses the wizard, remember. . . . I think we must expect great things from you, Mr. Potter. . . . After all, He-Who-Must-Not-Be-Named did great things — terrible, yes, but great."

This is emphasized again when Harry interviews Ollivander in Deathly Hallows:

"The owner of the Elder Wand must always fear attack," said Ollivander, "but the idea of the Dark Lord in possession of the Deathstick is, I must admit . . . formidable."
Harry was suddenly reminded of how he had been unsure, when they first met, of how much he liked Ollivander. Even now, having been tortured and imprisoned by Voldemort, the idea of the Dark wizard in possession of this wand seemed to enthrall him as much as it repulsed him.

Despite the terrible things Voldemort has done, including to Ollivander himself, Ollivander seems fascinated by Voldemort's unique magic and how that would become even more pronounced with the Elder Wand. It's almost as if he wants Voldemort to get the Elder Wand just to see what awesome magical feats would occur.
For such a person, the situation when Harry bought his wand must have been quite exciting. A wizard already suspected of being extraordinary cannot find a single standard wand to choose him. As each additional wand joins the pile it becomes more and more exciting, as it indicates that this is indeed a special case.

A: He enjoys the challenge
Others have mentioned that he likes his job and has a fascination with magical power that can be channeled out with unique, hand-crafted wands.
We don't see him helping others in detail, but I would assert that, though he's passionate about matching each witch and wizard consumer with their apposite wand, respectively, there must also be some elevated savor associated with solving especially difficult match-making trials.
The most complex or complicated pairings free Olivander from an otherwise more tedious and predictable exercise (that's still fun but not ideally so). It also enables him to continue to grow at his vocation, even though he's already a master at it. This demonstrates that there's always still some potential for growth even for someone so skilled, seasoned, and advanced at a trade as he is. He's probably conscious of this.
Harry is "special"? (Speculation)
Aside from being a complex case study, Harry also has prestige, though almost congenitally and incidentally so. Being the one to solve the "which is the ideal wand for Harry Potter?" question could possibly fill him with a kind of joy or pride, while also reaffirming his abilities to himself and enhancing his store's reputation. This part, of course, is just speculation.
Wand-crafting and sales is at the confluence of art and technical skill
Creating his own wands, he wants to perform the pairing process to the best of his abilities, too, in order to affirm that his wands go to the right witch or wizard. There is quite a lot of technical skills that go into composing or fabricating the wands, but then sorting them to the right owners becomes more of an "art" that requires a different kind of skill.
He knows that there's an "art" to this, and is happy to entertain the methodology.
Process of elimination
He may be getting increasingly thrilled because he's factoring out the likely candidates that failed to partner with Harry.
He knows that eventually one of the wands will work, but until then he's in an excited state of animation. Maintaining the momentum and testing as many promising options is likely the best course of action when a pairing proves difficult.
Olivander has a deep reverence for wand-pairing
The services that he provides have profound impacts on the next generation, so it's ideal that he demonstrates a plenitude of respect, pride, and fondness for and of his work.

A: This was addressed (indirectly) by JKR in her writings on Pottermore. In short, Garrick Ollivander is a wand nerd, obsessed with finding the very best match for each of his customers. A tricky customer is therefore, by definition, much more interesting than a mundane customer.

Mr Ollivander, however, was a purist who insisted that the best wands would never be produced merely by encasing the whiskers of a favourite Kneazle (or the stalk of a Dittany plant that once saved a wizard's father from poisoning, or the mane of a kelpie a witch had once met on holiday in Scotland) in the customer's favourite wood. The best wands, he believed, had cores of immensely powerful magical substances, which were expertly enclosed in specially selected and complementary wandwoods, the result to be matched to an owner with whom the wand itself felt the most affinity.
Mr Ollivander by J.K. Rowling

and

The following notes on various wand woods should be regarded very much as a starting point, for this is the study of a lifetime, and I continue to learn with every wand I make and match.
Wand Woods by J.K. Rowling

Additionally, his reputation is on the line here. Harry is a VIP customer and getting his wand just right will be a big feather in his cap, amongst those that know about these things.

While there was initially substantial resistance to this revolutionary way of crafting wands, it swiftly became clear that Ollivander wands were infinitely superior to anything that had come before. His methods of locating wand woods and core substances, marrying them together and matching them to ideal owners are all jealously guarded secrets that were coveted by rival wandmakers.
Mr Ollivander by J.K. Rowling

A: He's a man who prides himself on his work. The more difficult the task is, the more it proves that this is something that requires his expertise. Presumably, someone of lesser skill could not even get that far.

A: It probably just means he loves his job.
There's no particular reason to think that a "tricky customer" who needs to try many wands is any better than any other. But Ollivander seems to be someone who's found his true vocation, and dedicated his life to it. Handling wands just seems to be enjoyable for him. Maybe he's remembering his process of making each individual wand - he seems to know them all personally - or maybe he simply likes the feeling of handling them one after another.
I'd say there isn't too much to be read into this phrase. It's just a throwaway line in the middle of the passage, probably not something with any big significance. It helps to build an impression of Ollivander for the reader, as a cheerful and competent old man who knows what he's doing and loves his job - no more than that.


text:
Q: how get checked all row from all pages in Antd In table component I have pagination with few pages and I need to add event on it to count all properties from all pages. Right now when I clicking on it , it checks rows only on current page. Or may be there is any way to find out that top checkbox was clicked?

A: The other pages aren't rendered so they aren't mounted.
Therefore they don't exist in the real DOM or React's virtual DOM.
The solution would be to still render the other pages.
But to return nulls in all of the components so it is still invisible.
That would however defeat the purpose of pagination.
https://reactjs.org/docs/faq-internals.html

A: You can use onSelectAll of rowSelection
const App = () => {
  const rowSelection = {
    onSelectAll: () => console.log('all Selected')
  };
  return (
    <Table rowSelection={rowSelection} columns={columns} dataSource={data} />
  );
};


text:
Q: Is Comparable Interface a FunctionalInterface? I am using decompiler tools when I look at Comparable it has one abstract method and not have FunctionalInterface annotation
public interface Comparable<T> {
    int compareTo(T var1);
}

same like Comparator, but comparator have FunctionalInterface annotation
    @FunctionalInterface
    public interface Comparator<T> {
    int compare(T var1, T var2);
    ...
}

A: Is it a FunctionalInterface? No. Comparable doesn't have that annotation.
Is it a functional interface? Yes. From the definition in the language spec:

A functional interface is an interface that has just one abstract method (aside from the methods of Object)

Will it be treated as a FunctionalInterface? Yes:

However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

Is it logically a functional interface? No: Comparable doesn't represent a function. It is more like a trait of an object. "This thing can be compared", rather than "this thing does the comparing".
Is there any practical use of it as a functional interface? I would claim there is no obvious use, as evidenced by the fact you will rarely (if ever) see Comparable<Something> being used as the type of a variable, parameter or field; only in extends or implements clauses, and in the bounds of type variables.

A: Literally Comparable is a functional interface as it declares one and only one abstract method.
But annotating it with @FunctionalInterface would mean that it is documented to be used as a functional interface while that is not the case at all.
The JLS points out that :

9.6.4.9. @FunctionalInterface
Because some interfaces are functional incidentally, it is not
  necessary or desirable that all declarations of functional interfaces
  be annotated with @FunctionalInterface.

Of course you could use it in a lambda by relying on a external Foo instance and not this as we generally do in compareTo() implementation :
Foo one = new Foo(...);
Comparable<Foo> comparableForOne = other -> one.getX().compareTo(other.getX()));

Foo anotherFoo = new Foo(...);
int result = comparableForOne.compareTo(anotherFoo);

But that would be undesirable since a misuse of the Comparable interface that is designed to work for any instance of the class and not a specific instance.

A: A comparable is an object that can be compared to something else; compareTo() is supposed to compare the value of this.
It wouldn't make sense to implement that as a lambda.

A: I found the answer in Java Book Chapter 3 [144 page]

Is Comparable a Functional Interface?

We said that Comparator is a functional interface because it has a
  single abstract method. Comparable is also a functional interface
  since it also has a single abstract method. How- ever, using a lambda
  for Comparable would be silly. The point of Comparable is to imple-
  ment it inside the object being compared.

A: To fully answer the question, we should look under the hood of Java to see what lambdas (at lest as of now) are: syntactic sugar for implementing interfaces with exactly one method. Let's explain it with the example of Comparator<T> (which is perfectly fine to be implemented by a lambda) and go over to Comparable<T> (which can be implemented by a lambda, but does not make sense).
Suppose someone has given us a (compiled)
public class Car {
    private final int horsePowers;
    private final int topSpeed;
    private final int numDoors;
    private final String color;
    // Setters omitted for brevity
}

We cannot modify this class, but we want to sort cars by, e.g., color.  The traditional way would be to call Collections.sort(List<T> list, Comparator<? super T> c). Since we, as developers, are often lazy (otherwise, we would not use Copy-Paste-Programming), we often implement this kind of stuff in an anonymous class:
...
List<Car> cars = ...;
Collections.sort(cars, new Comparator<Car> {
    @Override
    public int compare(final Car lhs, final Car rhs) {
        return lhs.getColor.compareTo(rhs.getColor());
    }
});

This is ugly. First, it is long and second, it is awkward to read. But luckily the Java gods have blessed us with lambda expressions, so that we shall write1:
...
List<Car> cars = ...;
Collections.sort(cars, (lhs, rhs) -> lhs.getColor().compareTo(rhs.getColor()));

This looks better, doesn't it? It's short, comprehensive, and pleasant to read (at least, if you have seen it a hundred times). But under the hood, it is still an old, anonymous class. Nothing else. Some limitations do apply though to lambdas. First, the lambda does not have any state (instance variables). Second, all references used from outside the lambda (local variables or attributes of the surrounding method/class) must be final or effectively final (the lambda is not allowed to change the value). This will get important further below.
Now, let's come to Comparable<T>. While a Comparator<T> defines how to compare two T's with each other, Comparable<T> says "this class is comparable with T (typically itself), and here is how to compare it with T". Let us imagine that our Car class from above actually implements Comparable<Car> like so:
public class Car implements Comparable<Car> {
    ...
    public int CompareTo(final Car that) {
        int diff = this.getHorsePowers() - that.getHorsePowers();
        if (diff == 0) {
            diff = this.getTopSpeed() - that.getTopSpeed();
        }
        if (diff == 0) {
            diff = this.getNumDoors() - that.getNumDoors();
        }
        if (diff == 0) {
            diff = this.getColor().compareTo(that.getColor());
        }
        return diff;
    }
}

In essence it compares Cars first by their horsePower. If they are equal, it compares them by their topSpeed. If they are equal again, it compares them by the number of doors and so on.
Now let's recap: Lambdas are syntactic sugar for implementing interfaces with exactly one method and Comparable<T> describes how a class wants to be compared to T. Now recall what I have said above about Lambdas and states: Lambdas do not have any state. Thus, comparing them with anything is in most situations pointless (no state - nothing to compare; I say "most of the time" since there might be corner cases where such a thing might be feasible). So there is very little reason to actually implement Comparable<T> with a lambda.
In conclusion, we can say that while it is possible to implement Comparable<T> with a lambda, it is seldom useful.

1I know that the comparison lambda would normally writte as Comparator.comparing(Car::getColor), but this is besides the point I am trying to make.


text:
Q: Displaying thumbnail preview of a document I have an xslt list view webpart where I am displaying all the documents in a list. I want to implement on functionality where if user hover on a document link then I should display a small popup with top 50 characters from the document. Is it possible in SharePoint 2010. If yes, then how can I go for it?
It's like reading a document and fetching first 50 characters from there and displaying them in a popup. I can use jQuery for the same.
Thanks in advance.

A: There is a codeplex project titled Thumbnail Extender for SharePoint - the url is http://thumbextsp.codeplex.com/wikipage?title=Home%20English.
It uses Office Web Apps to achieve the thumbnail preview. It doesn't support all document types but it works and is free.
Source


text:
Q: HTTP Live Streaming with AVPlayer in iOS 4.0? Is it possible to use HTTP Live Streaming with AVPlayer on iOS 4.0? This was clearly a documented feature of 4.0. However, if I run Apple's SitchedStreamPlayer sample code on my 3GS running iOS 4.0.1, clicking "Load Movie" does not play the stream, but gives an error:

2011-06-21 13:14:49.428 StitchedStreamPlayer[680:307] The asset's tracks were not loaded due to an error:
  Cannot Open

MPMediaPlayer is able to play the same stream on the same device. However, I need a working solution with AVPlayer.
Does anyone know how to get Apple's StichedStreamPlayer code to work on 4.0? The Runtime Requirements say it should work on "iOS 4.0 or later".
Thanks!

A: This is a bug in 4.0, but I found a workaround. Here is the correct way to load video with AVPlayer:
    AVPlayer *player = [AVPlayer playerWithURL:[NSURL URLWithString:@"http://qtdevseed.apple.com/addemo/ad.m3u8"]];
// now use KVO to decide when it's ready to play
// works in both 4.3 and 4.0.1

The code from StitchedStreamPlayer works in 4.3 but not 4.0.1:
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:@"http://qtdevseed.apple.com/addemo/ad.m3u8"] options:nil];
    NSArray *tracksKeys = [NSArray arrayWithObjects:kTracksKey, kDurationKey, kPlayableKey, nil];
    [asset loadValuesAsynchronouslyForKeys:tracksKeys completionHandler:
     ^{
         NSError *error = nil;
         AVKeyValueStatus status = [asset statusOfValueForKey:[tracksKeys objectAtIndex:0] error:&error];
         NSLog(@"status=%@,error=%@",(status==AVKeyValueStatusLoaded?@"Loaded":status==AVKeyValueStatusFailed?@"Failed":@"?!"),error);
     }];

// output in 4.3: status=Loaded,error=(null)
// output in 4.0.1:  status=Failed,error=Error Domain=AVFoundationErrorDomain Code=-11828 "Cannot Open" UserInfo=0x15f2a0 {NSLocalizedFailureReason=This media format is not supported., NSUnderlyingError=0x1599e0 "The operation couldn't be completed. (OSStatus error -12847.)", NSLocalizedDescription=Cannot Open}

For more info see the old version of StitchedStreamPlayer.


text:
Q: My Macbook Pro will not detect my samsung galaxy s6 I'm trying to connect my samsung galaxy s6 to my macbook pro to run my apps from android studio; however, when I connect my phone to my mac via the usb cable that came with the phone, i get a notification on my phone that it is charging but my macbook and android studio do not detect it.
I have usb debugging on.
Kies and filetransfer don't work.
I cant see the directory in finder even though I have show external disks and hard disks checked.
My phone and mac are both running the latest versions of android and OSX.

A: Turns out that the cord provided by samsung is with mac computers due to OEM compatibility issues. Using a different cord with correct OEM data transfer compatibility will fix the issue.

A: I solve it by using android file transfer. Download it from android official website https://www.android.com/filetransfer/
Install it on Macbook Pro and connect your phone with cable and ROCK!

A: Try PdaNet, it can help you find your device's driver version and match with your device.

A: I'm also having this issue. I've got an s6 edge and a new macbook retina pro; so it's definitely not an issue of "old mac" to new samsung.
Edit: Fixed it by chatting with samsung.
From your phone dial *#0808# then check the MTP option to enabled. Hit reboot.
Also make sure to install smart switch on your computer, available at http://www.samsung.com/ca/support/smartswitch/
When the smartswitch window appears, hit the drop down menu, and then click the blue folder icon. That should do it.

A: I tried with another USB cable and it worked. Its the problem with defult USB cable coming along with mobile.

A: I was facing the issue with Samsung Note-8. My macbook pro was not detecting my phone. So, i just tried with another cable and it worked. there is no need to download samsun


text:
Q: A SciFi / Paranormal tv series from 10+ years ago I remember watching a SciFi/Paranormal thriller kind of tv-series with a man that had a special gift. I remember some vague details, like glowing spiders as one of the problems he needed to solve in an episode.
Some more general memories: the main character always needed some kind of antidote or injections from some sinister person. Also, the intro sequence contained lots of biology closeups, like cells mutating or similar, with lots of glowing yellow highlights (but I don't know how much I got influenced by House's intro).
Sorry to be so vague - it's from when I was a child and I really don't remember much, except that I was somehow strangely attracted to it.
It very probably is aired before the year 2000.

A: I don't remember the opening, but this sounds like the SciFi series The Invisible Man.  He had a gland implanted in him that let him become invisible, but he couldn't use it for but so long at a time.  He had a tattoo, I think it was a snake, with lines drawn between sections so it was, essentially, a meter to let him know how much time he had left to use his invisibility.
He had to get regular injections to help him and if he went over the line from staying invisible too long, he had to get medical attention immediately.
His brother made him invisible and a secret department in the government took over.  Their official attachment to one section or another changed from time to time, depending on funding.  While the person who gave him the injections wasn't sinister (and there was some romantic/sexual tension with him and the woman doctor who monitored him), the guy running the department was not exactly someone you'd trust.
I'm not sure if this is it, since some of what you say matches, but other stuff doesn't.

A: I was going to say this is the Invisible Man which matches the injections except you've already turned that one down. So I'll go with the similar in some ways show of Jake 2.0. In this show the main character gets nanobots into his blood much like in The Invisible man by a lab accident/ holdup. He is then used by the NSA as an agent and sent on missions. The nanobots give him various abilities such as control over electronics, super strength, super eyesight etc. I don't remember a specific episode with spiders that glowed but I believe the nanobots looked like spiders. It also has a biology closeup in the intro. Here's a link to the intro clip on youtube Jake 2.0

A: Some elements of this remind me of the late-90's/early-00's show Strange World.  The main character in that show had to get a treatment from a shadowy organization for his aplastic anemia, which came from a shadowy woman who also used his dependence on the treatment to get him to work against his superiors.  You can see the opening here, it contains many biological references/elements.
However, I can't recall or find any details on one of the cases of the week having glowing spiders.  Nor do I think he had any supernatural powers.

A: I believe this is the show you are refering to. I also loved the show when it was airing. I am not sure of the original name but it seems to be I-Man. A gland of an animal was implanted and he needed injections to maintain his madness. The "snake" tatoo was also a monitor that each section changed from green to red and he needed to have the injection before he lost total control of himself.
http://youtu.be/T0FNLcsfMMk


text:
Q: F# JSON Typeprovider crashes on missing data How can I handle missing data in a JSON file? With lists of data you can simply use a map function. But what about an object
Say I have sample data:
{
    "Person":{
    "FirstName":"John",
    "LastName":"Doe",
    "Age": 42,
    "Address": {
        "Street": "SomeStreet",
        "City" : "Some City"
        }
    }
}

And my actual data comes in like:
{
    "Person":{
    "FirstName":"John",
    "Age": 42
    }
}

I can't figure out how to make the address optional:
type personJson = JsonProvider<"Data/personSample.json">
let personData = testJson.Load("Data/personData.json")

let address = personData.Person.Addres // gives an exception

Also trying to convert it to an optional fails
    let p = personData.Person.Address |> Option.ofObj
System.Exception: Operation could not be completed due to earlier error
 The type 'JsonProvider<...>.Address' does not have 'null' as a proper value at 2,35
I can't imagine I should change the code for each file with some missing data.
So what should I do to solve this?

A: You can use SampleIsList = true when setting up your type provider to offer multiple variations on how your objects are shaped.
open FSharp.Data

type personJson = JsonProvider<"Data/personsSample.json", SampleIsList = true>

let personData = personJson.Load("Data/personData.json")

The contents of personsSample.json could look like this, which includes both your original json and a variation of that json without an address:
[
    {
        "Person":{
            "FirstName":"John",
            "LastName":"Doe",
            "Age": 42,
            "Address": {
                "Street": "SomeStreet",
                "City" : "Some City"
                }
        }
    },
    {
        "Person":{
            "FirstName":"John",
            "LastName":"Doe",
            "Age": 42
        }
    }
]

Now when you load a single personData example, referencing the address field will handle a null value correctly instead of crashing.


text:
Q: How to know the data type of a field in trigger? How can i know the data type of a field inside a trigger. I am able to get the field name and it's value inside a trigger after insert as follows:
DECLARE @AfterInserted XML

     SELECT @AfterInserted = (
        SELECT *
        FROM INSERTED
        WHERE User_Key = User_Key
        FOR XML RAW, ROOT
    );

    CREATE TABLE #XML(
    FieldName   nvarchar(250),
    Value       nvarchar(250));

    Insert Into #XML(FieldName, Value)
      select T.N.value('local-name(.)', 'nvarchar(100)'),
             T.N.value('.', 'nvarchar(250)')
      from @AfterInserted.nodes('/root/row/@*') as T(N)

I also need data type of the field too. something like T.N.value('Data-type')?
Thanks

A: Not exactly sure if this will work for your purpose, but:
SELECT SQL_VARIANT_PROPERTY(your_column, 'BaseType')
FROM your_table

Will return a column's field type as NVARCHAR.
You can also use Precision, Scale, MaxLength, Collation and TotalBytes as the 2nd parameter for SQL_VARIANT_PROPERTY.

A: There is no need to use XML to get meta-data related to the table that the Trigger is on.  You can query the system catalog to get the info directly.
The Trigger is an object with an object_id, so the @@PROCID system variable will have the object_id of the Trigger itself, within the context of the Trigger.
Using the value of @@PROCID, you can look in sys.objects at the row for that specific object_id and the parent_object_id field will be the object_id of the Table that the Trigger is on.
Using the value of parent_object_id, you can query sys.tables / sys.objects to get table-level info, or query sys.columns to get column-level info.
The example below illustrates the above info:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET NOCOUNT ON
GO

-- DROP TABLE dbo.TriggerTest
IF (OBJECT_ID('dbo.TriggerTest') IS NULL)
BEGIN
    PRINT 'Creating TriggerTest...'
    CREATE TABLE dbo.TriggerTest (Col1 INT, Col2 VARCHAR(30), Col3 DATETIME)
END

--
IF (OBJECT_ID('dbo.TR_TriggerTest_IU') IS NOT NULL)
BEGIN
    PRINT 'Dropping TR_TriggerTest_IU...'
    DROP TRIGGER dbo.TR_TriggerTest_IU
END
GO

PRINT 'Creating TR_TriggerTest_IU...'
GO
CREATE TRIGGER dbo.TR_TriggerTest_IU
    ON dbo.TriggerTest
    AFTER INSERT, UPDATE
AS
BEGIN
    SET NOCOUNT ON

    -- get Table info
    SELECT  *
    FROM    sys.tables st
    WHERE   st.[object_id] = (  -- get parent_object_id of this Trigger
                                -- which will be the table that the
                                -- Trigger is on
                                SELECT  so.parent_object_id
                                FROM    sys.objects so
                                WHERE   so.[object_id] = @@PROCID
                            )

    -- get Column info
    SELECT  *
    FROM    sys.columns sc
    -- Custom types will repeat values of system_type_id and produce a
    -- cartesian product, so filter using "is_user_defined = 0"
    INNER JOIN  sys.types st
        ON  st.system_type_id = sc.system_type_id
        AND st.is_user_defined = 0
    WHERE   sc.[object_id] = (  -- get parent_object_id of this Trigger
                                -- which will be the table that the
                                -- Trigger is on
                                SELECT  so.parent_object_id
                                FROM    sys.objects so
                                WHERE   so.[object_id] = @@PROCID
                            )
END
GO

INSERT INTO dbo.TriggerTest (Col1, Col2, Col3) VALUES (1, 'a', GETDATE())


text:
Q: What is the scope of a C++ class added to a QList I wrote a small piece of code to prove to myself some bad practice was indeed bad practice. However I'm not seeing the result I expected.
I have a QList storing objects rather than pointers to those objects.
Here is the class:
class test{
  public:
  test(int value){val=value; printf("created test %d\n",val);}
  ~test(){ printf("deleting test %d\n", val); val=0;}
  void print(){printf("test %d!\n", val);}
  int val;
};

and I have a list of these with test functions as follows:
class myclass {
...
QList<test> _test_list;
void do_test_init();
void do_test();
...
};

void myclass::do_test_init()
{
  for(int i=0; i < 10; i++)
    _test_list.append(test(i+100));
}

void myclass::do_test()
{
  for(int i=0; i < 10; i++)
    _test_list[i].print();
}

The output I see is:
created test 100
deleting test 100
created test 101
deleting test 101
created test 102
deleting test 102
created test 103
deleting test 103
created test 104
deleting test 104
created test 105
deleting test 105
created test 106
deleting test 106
created test 107
deleting test 107
created test 108
deleting test 108
created test 109
deleting test 109
test 100!
test 101!
test 102!
test 103!
test 104!
test 105!
test 106!
test 107!
test 108!
test 109!

I'm assuming this is because the append function is taking a copy of the object I passed in. Does this mean that it's safe to use QList this way? My preference is to store pointers rather than objects, is this misguided?

A: The answer to this question is that it's perfectly "safe" in the sense that the object is copied when it is appended to the list. Providing a copy constructor shows this clearly.
The copied objects are deleted when the list is cleared.


text:
Q: DataTable after row delete on next-previos page it shows again I have strange issue with DataTables. I am using this stuff to delete row and all is working (row is deleted from DB, alerts showing properly), and it removes row from display BUT when I click previous page and come back to the page where row was displayed originally (by page I mean DataTable page number or I increase number of rows per page) - it is showing again...(as it was not actually removed)
Only after hard-refresh it is removed.  Why is this happening and how to really remove it without actually refreshing the browser?
Here is the code I am using to delete row:
function DeletePublisher(element, publisherid) {
jConfirm('Are you sure you want to delete this publisher?', 'Delete publisher', function (r) {
    if (r) $.post('includes/publishers/delete-publisher.php?publisherid=' + publisherid,

    function (data) {
        if ($.trim(data) == 'error') {
            $.jGrowl('This publisher was already deleted', {
                header: 'ERROR'
            });
            $(element)
                .parents('tr')
                .remove();
        } else {
            $(element)
                .parents('tr')
                .remove();
            oTable.fnDeleteRow(element);
            $('tr')
                .removeClass();
            // Now add class names again
            $('tr:odd')
                .addClass('odd');
            $('tr:even')
                .addClass('even');

            $.jGrowl('Publisher deleted');
        }
    });
});

And this is TR element:

<a href="/includes/publishers/edit-publisher.php?editpublisher=<?php echo $publisher_id; ?>" data-fancybox-type="iframe" class="iframe sweet-tooltip" data-text-tooltip="Edit" data-style-tooltip="tooltip-mini-slick">Edit

<a href="#" class="sweet-tooltip" data-text-tooltip="Delete" data-style-tooltip="tooltip-mini-slick" onclick="DeletePublisher(this,'<?php echo $publisher_id; ?>')">Delete

So not sure if element is passing correct ID of row at the first place ?

A: Instead of removing the element from the DOM with $(element).parents('tr').remove();, you may want to try fnDeleteRow to remove the row from the Datatable as well. You can pass a parameter to the method that will tell Datatables to redraw the table which wouldn't force you to do a post back to refresh the data.
Here's the link to fnDeleteRow in the Datatables API.
UPDATE:
Try something like this:
function DeletePublisher(element, publisherid) {
jConfirm('Are you sure you want to delete this publisher?', 'Delete publisher', function (r) {
    if (r) $.post('includes/publishers/delete-publisher.php?publisherid=' + publisherid,

    function (data) {
        var nTr = $(element).closest('tr');

        oTable.fnDeleteRow(nTr, null, true);

        if ($.trim(data) == 'error') {
            $.jGrowl('This publisher was already deleted', {
                header: 'ERROR'
            });
        } else {
            $.jGrowl('Publisher deleted');
        }
    });
});


text:
Q: Include .sh file in .pl file and access variable of .pl file in .sh In .pl script.
..
//variables
my $var;
system("sh main.sh");
..

In .sh script.
// can I used here, some variables of declare in .pl file.

How to used the .pl file variables in .sh file. and obvious.. have used the .sh file
Thanx!

A: The child (sh) will receive the contents of %ENV as its environment.
$ perl -e'local $ENV{VAR} = "VAL"; system("sh", "-c", q{printf "%s\n" "$VAR"})'
VAL

You could also pass the values as arguments.
$ perl -e'my $var = "VAL"; system("sh", "-c", q{printf "%s\n" "$1"}, "-", $var)'
VAL


text:
Q: Signing Data with OpenSSL and Python3 - signed data cannot be validated I'm trying to replicate the following steps to sign some data using OpenSSL in a python3 script.  When I do the work from the command line, everything works.  When I put it into a script, the signed data is not recognized/validated.
How do I get the signed data into a recognized format?  Below I've tried to remove the 'b' (for bytes) and the single quotes to force something through, but no luck.
These steps work fine when doing from the command line:
Command Line:

*

*Create the data file
echo -n "This is my data." > data.txt

*Sign the data file
openssl dgst -sha256 -sign key.pem -keyform PEM -out signature data.txt

*Encode the data file
openssl enc -base64 -in signature > sig_base64
*Output:
nTxLMxUTOf5suMOqy9vCHserJ3jzaKPRxGABR1zz3sZsuQHvBD8r9z82wzmvkS7u
ygW4fi6NH9P5znJFaTw3omnZjOL+xWrxvwmK0Lg25a/MNC5xpuY8i12rIsLLZHbu
B4q0G7dj4m3oJNxyhoZjrKPr3V0KssdxuNBlMYdjd3tuhj5MI1cqpRetAcw2nJps
ovC14sPAzTaKHUmMoN+H5t2rVgoeaHhTknhEAlW5FqXMcm/cR/rRru9EoAEe7cmV
rTRiJpCBiKrpHBNPmQJOmF+zrS3tID4XGFV/yUgcU0chlLMoJyv1AdfHdQYzfeGP
EYFuk7NYnjz5kVLoasTS7Q==

My script
#!/usr/local/bin/python3
import cryptography
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding

key_file = open("key.pem", "rb")

private_key = serialization.load_pem_private_key(key_file.read(), password = None, backend=default_backend())

data = "This is my data."
dataBytes = bytes(data, encoding='ascii')

signData = private_key.sign(dataBytes,padding.PSS(mgf=padding.MGF1(hashes.SHA256()),salt_length=padding.PSS.MAX_LENGTH),hashes.SHA256())

encodedData = base64.b64encode(signData)

print("-----BEGIN DATA REQUEST-----")
print(data)
print("-----END DATA REQUEST-----")
print("\n")
print("Example 1")
print("-----BEGIN SIGNATURE-----")
print(encodedData)
print("-----END SIGNATURE-----")
print("\n")
print("Example 2")
print("-----BEGIN SIGNATURE-----")
print (encodedData.decode('ascii'))
print("-----END SIGNATURE-----")
print("\n")
print("Example 3")
print("-----BEGIN SIGNATURE-----")
print(str(encodedData).replace("b'","").replace("'",""))
print("-----END SIGNATURE-----")

My Script Output
-----BEGIN DATA REQUEST-----
This is my data.
-----END DATA REQUEST-----

Example 1
-----BEGIN SIGNATURE-----
b'sooabk4NIJwPtTdQvqIpiHxGpc10log56IdSaE9gnwPToYhlIOZBUo5W1Peyfz6lnQojYcG+MGLGtYQNIsHsYJnT6p5cBN3QHf/FIU4SaELTLpmLhEtW3n5a19vbEXi/LBXaUfrCNf1A7TaNh+uM+iMIeNDsgF4GWfJwb+O1jlw1NdUk4hces7CHBYGvk9/sGwntyHYkkOnJpPhy6ZQ2bhVnYS/R2d9Wilptjl7OlDkAb4VB2TXjPPtSzWxMQ+Ch4HF8BdnOGzUo+Yb9lKsP8LnyROMEtEBBaTmh/6xVKwaRi1xqorJS+qWRtivqIN4RPsKz+jlcqg6fCZxi6NW2Qw=='
-----END SIGNATURE-----

Example 2
-----BEGIN SIGNATURE-----
sooabk4NIJwPtTdQvqIpiHxGpc10log56IdSaE9gnwPToYhlIOZBUo5W1Peyfz6lnQojYcG+MGLGtYQNIsHsYJnT6p5cBN3QHf/FIU4SaELTLpmLhEtW3n5a19vbEXi/LBXaUfrCNf1A7TaNh+uM+iMIeNDsgF4GWfJwb+O1jlw1NdUk4hces7CHBYGvk9/sGwntyHYkkOnJpPhy6ZQ2bhVnYS/R2d9Wilptjl7OlDkAb4VB2TXjPPtSzWxMQ+Ch4HF8BdnOGzUo+Yb9lKsP8LnyROMEtEBBaTmh/6xVKwaRi1xqorJS+qWRtivqIN4RPsKz+jlcqg6fCZxi6NW2Qw==
-----END SIGNATURE-----

Example 3
-----BEGIN SIGNATURE-----
sooabk4NIJwPtTdQvqIpiHxGpc10log56IdSaE9gnwPToYhlIOZBUo5W1Peyfz6lnQojYcG+MGLGtYQNIsHsYJnT6p5cBN3QHf/FIU4SaELTLpmLhEtW3n5a19vbEXi/LBXaUfrCNf1A7TaNh+uM+iMIeNDsgF4GWfJwb+O1jlw1NdUk4hces7CHBYGvk9/sGwntyHYkkOnJpPhy6ZQ2bhVnYS/R2d9Wilptjl7OlDkAb4VB2TXjPPtSzWxMQ+Ch4HF8BdnOGzUo+Yb9lKsP8LnyROMEtEBBaTmh/6xVKwaRi1xqorJS+qWRtivqIN4RPsKz+jlcqg6fCZxi6NW2Qw==
-----END SIGNATURE-----

The only difference I can see from the command line output vs. example 2 and 3 on the output from my script is the formatting of the signed data from the command line is different from what my script is producing (cli is a block, while my code produces a single line).
I'm stuck.  Can't figure out what is wrong.  Any thoughts?

A: I tried this again using the OpenSSL library and everything works correctly with Example 3 output (I didn't try the others):
Script
#!/usr/local/bin/python3
import OpenSSL
from OpenSSL import crypto
import base64

key_file = open("key.pem", "rb")
key = key_file.read()
key_file.close()

pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)

data = "This is my data."
dataBytes = bytes(data, encoding='ascii')

signData = OpenSSL.crypto.sign(pkey, dataBytes, "sha256")

encodedData = base64.b64encode(signData)

print("-----BEGIN DATA REQUEST-----")
print(data)
print("-----END DATA REQUEST-----")
print("\n")
print("Example 1")
print("-----BEGIN SIGNATURE-----")
print(encodedData)
print("-----END SIGNATURE-----")
print("\n")
print("Example 2")
print("-----BEGIN SIGNATURE-----")
print (encodedData.decode('ascii'))
print("-----END SIGNATURE-----")
print("\n")
print("Example 3")
print("-----BEGIN SIGNATURE-----")
print(str(encodedData).replace("b'","").replace("'",""))
print("-----END SIGNATURE-----")

Output
-----BEGIN DATA REQUEST-----
This is my data.
-----END DATA REQUEST-----

Example 1
-----BEGIN SIGNATURE-----
b'AOPHhQAQ7QnST30rdaFEMVFJqTDAq886MAe1tigxWrjKwUZYIObeabH3UuYVd7s2N4fT9Z/9fOKSyPiDkB61WcfYIdIJBkCkKX+xHTqBnpZjyFevkdx+P8MjomXI1/hP66Jnk2VK7H/KcW+dxG1/F60d3kRvuLeG6M/1bwVJ3zYC2J6c9216GCwBrCg/WG6rJLweuOQL63pccWYMaxESTM9Br6KpK3fw/12soei19+2btFmEx50mUNeXPDKVwePYVT3il3ArrT96NdSteogMd+qnweZvRomMJu+v8SWZeumMU/+ytEHXQzwlgiED+hLCnzG2RYo+s4khbEdu7o57sQ=='
-----END SIGNATURE-----

Example 2
-----BEGIN SIGNATURE-----
AOPHhQAQ7QnST30rdaFEMVFJqTDAq886MAe1tigxWrjKwUZYIObeabH3UuYVd7s2N4fT9Z/9fOKSyPiDkB61WcfYIdIJBkCkKX+xHTqBnpZjyFevkdx+P8MjomXI1/hP66Jnk2VK7H/KcW+dxG1/F60d3kRvuLeG6M/1bwVJ3zYC2J6c9216GCwBrCg/WG6rJLweuOQL63pccWYMaxESTM9Br6KpK3fw/12soei19+2btFmEx50mUNeXPDKVwePYVT3il3ArrT96NdSteogMd+qnweZvRomMJu+v8SWZeumMU/+ytEHXQzwlgiED+hLCnzG2RYo+s4khbEdu7o57sQ==
-----END SIGNATURE-----

Example 3
-----BEGIN SIGNATURE-----
AOPHhQAQ7QnST30rdaFEMVFJqTDAq886MAe1tigxWrjKwUZYIObeabH3UuYVd7s2N4fT9Z/9fOKSyPiDkB61WcfYIdIJBkCkKX+xHTqBnpZjyFevkdx+P8MjomXI1/hP66Jnk2VK7H/KcW+dxG1/F60d3kRvuLeG6M/1bwVJ3zYC2J6c9216GCwBrCg/WG6rJLweuOQL63pccWYMaxESTM9Br6KpK3fw/12soei19+2btFmEx50mUNeXPDKVwePYVT3il3ArrT96NdSteogMd+qnweZvRomMJu+v8SWZeumMU/+ytEHXQzwlgiED+hLCnzG2RYo+s4khbEdu7o57sQ==
-----END SIGNATURE-----


text:
Q: I'm getting a Run-time error '429' in Microsoft Excel 365 VBA. How do I fix it? I've uninstalled and reinstalled my Office 365. The error still occurs.
The code I'm running is:
Dim objWord As Object
Dim MyCounty As String
Dim MyDeed As String
Dim mySelection As Object

Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Add Template:="D:\Documents\Custom Office Templates\file_template.dotm"

I've looked at this link https://learn.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/activex-component-can-t-create-object-or-return-reference-to-this-object-error-4 but it's not really helping. The uninstall/reinstall should have taken care of the registry problems, the DLL objects, and anything else mentioned in the article.
What am I missing?

A: Check that you have the Microsoft Excel Object Library and the Microsoft Office Object Library ticked in Tools > References and that they have been registered.
If they are ticked, you may need to run Detect and Repair from the Excel Help menu to make sure that the Office installation hasn't corrupted in any way.


text:
Q: How to get the phone language with libgdx? I'm tyring to set a default language for my game and I would like it to be the phone's language, the question is: how can I get the phone's language?

A: In my last game I used the default locale of the JVM:
java.util.Locale.getDefault().toString();

to get the device language. That seemed to work fine for Android as well.


text:
Q: Testing the accessibility of the file To avoid exceptions like
(1) Process cannot access the file because it was used by another process
I used the following method to test the accessibility of the file before any further processing.
private bool CheckIfFileBeingUsed(string FilePath)
    {
        FileStream Fs = null;
        try
        {
            Fs = File.Open(FilePath, FileMode.Open, FileAccess.Read, FileShare.None);
            Fs.Close();
        }
        catch (Exception)
        {
            return true; //Error File is being used
        }
        return false; //File is not being used.
    }

Could anyone advise me there's any Windows API or other solutions for such testing of file accessibility instead of the above File.Open Method ?

A: It seems like you're duplicating effort here. Since trying to open the file for processing will throw the same exception you're catching here, why not just proceed with an attempt at processing the file, and handle the exception if it comes up?
Assuming that's not possible for some reason, testing like this still isn't totally reliable, since you now have a race condition. Even if this test passes, there's no guarantee that the file will be in the same state when you go to run your other code on the file. That's why it's easier to just attempt to do what you want, and handle any exceptions at that point.

A: What is the purpose of this check in the first place? You are trying to avoid exception by making it occur earlier and catching it, but why not catch it with your current design? Also, this approach is subject to race condition because file might become non accessible just after your check, so the only correct way to do it is to just do any processing you need and catch exceptions thrown.

A: Your method seem valid to me. Don't forget to close the stream in case of an exception though:
    finally
    {
        if (Fs!= null)
            Fs.Close();
    }

Keep in mind that there is no 100% guarantee that this will prevent the 'file in use' exception. There is a always a very brief (ms) period between your check and actually opening the file, in which the file could become in use by another process.

A: As far as you handle the file exists check explicitly, this method is fine. Your method returns true even if File Doesn't Exist
I don't think C# provides any API for this.


text:
Q: Silverlight 5 Double-click in a ListBox I have seen lots of examples of using the new Silverlight 5 double-click feature. However, none of them have shown how to capture double-click in a ListBox.
Anyone have any examples/tips on how to set this up?
I am using MVVM.
Thanks!

A: You might be able to do this by creating a custom trigger that keeps a tally of the number of mouse clicks. Once args.ClickCount == 2 via the the parameter MouseButtonEventArgs args being true, you can invoke the logic you need:
public class DoubleClickTrigger : TriggerBase<FrameworkElement>

Within the <DataTemplate> for the ListBox you could use the custom event trigger created above. See the following post for more in-depth information:
Double Click trigger for Silverlight


text:
Q: How to disable compiler's options "-MT DOE.o -MD -MP -MF .deps/DOE.Tpo" automately generated by autoconf & automake When I invoke a make command, the command reads (on the screen):

ccppc -I. -I../../h -Wall -fno-builtin -fno-for-scope -mstrict-align
  -mcpu=604 -DCPU=PPC604 -mlongcall  -MT DOE.o -MD -MP -MF .deps/DOE.Tpo -c -o DOE.o DOE.c

I understand where -I. -I../../h -Wall -fno-builtin -fno-for-scope -mstrict-align  -mcpu=604 -DCPU=PPC604 -mlongcall comes from, because I defined them.

AM_CFLAGS=-Wall -fno-builtin -fno-for-scope -mstrict-align  -mcpu=604
  -DCPU=PPC604 -mlongcall AM_CPPFLAGS = -I../../h

However, I don't know where -MT DOE.o -MD -MP -MF .deps/DOE. comes from. I want to disable it.
I digged into the Makefile,and find the line related to -MT DOE.o -MD -MP -MF .deps/DOE..
.c.o:
    $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po

I just want to remove -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo, for I get errors because of it.

A: the -M flags are added by autoconf to enable dependency tracking.
you can disable them, by specifying by running:
 ./configure --disable-dependency-tracking

in general autoconf should figure this out by itself. did you specify the compiler (ccppc seems fairly non-standard to me) when running configure or did you only change to it when running make?


text:
Q: F# Equivalent of Destructor I am translating a C# class that wraps an unmanaged library to F#. I have run into the seemingly simple problem of rewriting the destructor that follows.
class Wrapper {

    // P/Invoke ellided

    private SomeType x;

    public Wrapper() {
        x = new SomeType();
        Begin();
    }

    public ~Wrapper() {
        End();
    }

The simplified F# code I have at this point is as follows:
type Wrapper() =
  [<Literal>]
  static let wrappedDll = "Library.dll"

  [<DllImport(wrappedDll , EntryPoint = "Begin")>]
  static extern void Begin()

  [<DllImport(wrappedDll , EntryPoint = "End")>]
  static extern void End()

  let x = new SomeType()

  do
    Begin()

How can I modify this F# code to have the same behaviour? My search for F# destructor turned up no results in the books I have or on the web.
Thank you.

A: Have you tried looking for F# finalizer?
override x.Finalize() = ...

A: namespace FSharp.Library

type MyClass() as self =

    let mutable disposed = false;

    // TODO define your variables including disposable objects

    do // TODO perform initialization code
        ()

    // internal method to cleanup resources
    let cleanup(disposing:bool) =
        if not disposed then
            disposed <- true

            if disposing then
                // TODO dispose of managed resources
                ()

            // TODO cleanup unmanaged resources
            ()

    // implementation of IDisposable
    interface IDisposable with
        member self.Dispose() =
            cleanup(true)
            GC.SuppressFinalize(self)

    // override of finalizer
    override self.Finalize() =
        cleanup(false)

F# Class Library Template
http://blogs.msdn.com/b/mcsuksoldev/archive/2011/06/05/f-class-library-template.aspx

A: I think it must be defined the same as C# compiler does
override c.Finalize() =
    try
        // do finalization
    finally
        base.Finalize()

Because exception in your finalization code can corrupt something.
Otherwise I misunderstand why C# does that.


text:
Q: Localize control using code I need some examples to understand how localize controls like MessageDialog. I'm able to localize xaml controls using x:Uid and Resources.resw file but I don't understand how to do it using C#

A: Use a ResourceLoader:
 ResourceLoader resourceLoader = ResourceLoader.GetForViewIndependentUse("Resources");

and for getting the strings:
string localizedstring =  resourceLoader.GetString("string1");

Hope it helps!


text:
Q: Ajax call to Node.js server not working in qlikview extension I have setup a Node.js server to render a simple d3 circle.
app.get('/circles',function(req, res) {
    res.render('circles');
});

The view engine is jade. Here is the jade template. I refer my java script libraries which are present in the public folder.
doctype html
html
  head
    title Enterprise dashboard
    h1 Welcome to Visualization
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(src='/javascripts/jquery-1.8.2.min.js')
    script(src='/javascripts/d3.min.js')
    script(src='/javascripts/d3circles.js')
  body(id='idofbody')
    div(id='circle')
    div(id='circle1')

When I access this from a browser, everything works fine. The d3 visualization works rendering the single circle.
I am trying to make ajax call to the '/circles' from a qlikview extension. But the page returned shows only the static part like h1 tag. The SVG that was made with the script in d3 call circles is not rendered.
The fire bug output shows this. As you can notice, the first GET is the call I made from qlikview extension. The second call is unexpected. When rendering the page, it makes a GET call to the script library  with a wrong url-url of the Origin. The url refers the origin and hence becomes unsuccesful I beleive.
note:I can't post the full output from firebug(with all GET calls) as screenshot due to lesser points in my side.
GET   http://25.25.80.63:8765/circles                        200 OK
    3.49s   QvAjax.js (line 23)
GET   http://25.25.80.63/javascripts/jquery-1.8.2.min.js    404 Not Found       151ms   QvAjax.js (line 23)
But the problem occurs only within qlikview. When I do the same ajax call, from a page in a different node server, the script and css libraries are referred with the correct url - the url of the HOST.
Please suggest how to render D3 components into qlikview from the node server.


text:
Q: React-native detect click on WebView Is there solution to detect click anywhere on reacts-native WebView? Tried to put it inside TouchableOpacity but I'm getting errors. Is there some work around it, to detect click?

A: This will be a great feature if react native team can add it in the future. Currently this is still an open issue https://github.com/facebook/react-native/issues/586
Somebody provide a suggestion at there you can give it a try. But it is better wait for facebook team to provide a more elegant solution.

A: Any events taking place inside a webview is sandboxed from the rest of the application. This is by design of this native component, not a limitation of React Native.
What you will need to do is to manually bubble up the event that you are interested in from the webview to your app yourself.
You can currently do so by using react-native-webview-bridge. You set a global listener to the DOM event that you are interested in. Once you catch it, you send it to your application via the bridge.


text:
Q: Find the number of points of distance n away from origin as function of n I came across a seemingly simple problem the other day and I thought I'd share it with anyone interested.
Say you have a point in 3 dimensions.
The number of points that are of distance $0$ away is $1$ (itself).
$1 \rightarrow 6$ (up/down/left/right/in/out).
$\sqrt{2} \rightarrow 12$ (across all 2D diagonals).
$\sqrt{3} \rightarrow 8$ (across all 3D diagonals).
$\sqrt{4}=2 \rightarrow 6 $
...
$\sqrt{7} \rightarrow 0$
etc...
Does anyone know how to create an expression or recurrence relation to find the number of points distance $\sqrt{n}$ away for any given $n$?

A: Consider this naïve C implementation of counting the cubic lattice points as a function of squared distance, the sequence $s(n)$ for $n = 0 .. max$, where the largest distance considered is $\sqrt{max-1}$:
#include <stdlib.h>
#include <math.h>

void histogram_3d(unsigned long sqr[], unsigned long max)
{
    const unsigned long n = 1UL + (unsigned long)ceil(sqrt((double)max));
    unsigned long       z, y;

    for (z = 0UL; z <= n; z++) {
        for (y = 0UL; y <= n; y++) {
            const unsigned long zzyy = z*z + y*y;
            if (zzyy < max) {
                const unsigned long c = 2UL * (y == 0UL ? 1UL : 2UL) * (z == 0UL ? 1UL : 2UL);
                unsigned long       i = zzyy + 1UL;
                unsigned long       d = 3UL;
                sqr[zzyy] += c / 2UL;
                while (i < max) {
                    sqr[i] += c;
                    i += d;
                    d += 2UL;
                }
            }
        }
    }
}

The innermost loop is over the squares of $x$. It applies the fact that the difference between consecutive squares ($1,4,9,16,25,\dots$) increments by 2 every step -- the differences are (starting at 1) $3,5,7,9,\dots$.
Given $max \ge 10$, the ten first elements in sqr array are incremented by 1,6,12,8,6,24,24,0,12,30. On a HP laptop with a Core i5-4200U CPU (x86-64, unsigned long is 64-bit), this calculates the first million terms of the sequence in about three seconds; the first ten million terms in about 180 seconds (three minutes). Using 32-bit unsigned int type instead, on the same machine and compiler, calculating the first million terms takes about two seconds, and first ten million terms about 160 seconds.
It is also possible to modify the above to consider only some window $n = min..max$. That would allow better cache usage (if the histogram for the entire window fits in cache), but I have not tested in practice whether this yields significant speedups or not for very large $n$.
Simply put, the naïve method may yield quite acceptable performance in practice, even though the algorithm technically has $O(n^3)$ time complexity.

The OEIS A005875 page mentions that the generating function for this sequence is
$$\left(\sum_{i=0} x^{i\cdot i}\right)^3 = 1 + 6x + 12x^2 + 8x^3 + 6x^4 + 24x^5 + 24x^6 + 0x^7 + 12x^8 + 30x^9 + O(x^{10})$$
In other words, expanding the above sum, the coefficients of the increasing powers of $x$ yield the (nonzero) terms in the sequence.
The hard part here is the fact that the sum is cubed. (The powers of $x$ in the sum are $0, 1, 4, 9, 16, 25, 36, \dots$, so they are not a problem.) Using a triple loop over this sequence (instead of the lattice coordinates within the $\sqrt{max}$-radius ball as in the example code above) might yield a constant factor speedup, but optimized code would be much more complex. This, too, would have $O(n^3)$ time complexity.

The OEIS page also mentions that the sequence is an Euler transform of period 4 sequence $[6, -9, 6, -3, \dots]$. This means that
$$s(n) = \sum_{k=0}^n -1^k \binom{n}{k} a_k = \sum_{k=0}^n -1^k \frac{n!}{k!(n-k)!} a_k$$
where $a_0 = a_{4i} = 6$, $\;a_1 = a_{4i+1} = -9$, $\; a_2 = a_{4i+2} = 6$, $\; a_3 = a_{4i+3} = -3$, $\;0 \le i \in \mathbb{Z}$.
The negations occur in pairs, so actually
$$s(n) = \sum_{k=0}^n \binom{n}{k} b_k$$
where $b_i = \lvert a_i \rvert$.
(In C, $b_i = \lvert a_k\rvert$ can be evaluated using 3*( ((i+1)&2) | ((i+2)&3)) ), which may be faster than a lookup on some architectures; a lookup may have unwanted cache effects. Another option is (13974 >> ((i&3)<<2)) & 15, which uses only bit shifts and two binary and operations, essentially packing the sequence into a 16-bit hexadecimal number, 13974 = 0x3696.)
This is a very promising approach in general, as its time complexity looks to be $O(n^2)$, if we disregard the complexity of computing the binomial coefficients. It may very well be possible to calculate the coefficients using Pascal's triangle, although extra memory may be needed to store the binomial coefficients for each innermost loop.
Essentially, this approach is mathematically fully defined, but the efficiency of the approach depends on the implementation details -- and as such, is really a programming question, not a mathematical one.


text:
Q: Sorting a two dimensional array on the basis of one row data I am not sure if the title rightly suggests what I am trying to ask. Let's say  I have a two dimensional int array as below:
int[][] x={{1,7,6},{2,4,8}};

Now I want to sort the first row in ascending order and the data in the 2nd row must be in the same column after the sorting, i.e., after sorting, the array should be like this:
x={{1,6,7},{2,8,4}}

What is the right way to do it?

A: This can be done by implementing your own sort routine but a better approach would be to refactor.
Try encapsulating the data as an array of pairs of numbers, each pair wrapped in its own object. You can then sort on the first value and access either value.
class Pair<T extends Comparable<T>> implements Comparable<Pair<T>> {
  final T a;
  final T b;

  public Pair ( T a, T b ) {
    this.a = a;
    this.b = b;
  }

  @Override
  public int compareTo(Pair<T> o) {
    // Comparison on 'a' only.
    return a.compareTo(o.a);
  }

  @Override
  public String toString () {
    return "{" + a + "," + b + "}";
  }
}

public static void main(String args[]) {
  Pair[] pairs = {
    new Pair(1,2),
    new Pair(7,4),
    new Pair(6,8),
  };
  System.out.println("Before: "+Arrays.toString(pairs));
  Arrays.sort(pairs);
  System.out.println("After: "+Arrays.toString(pairs));
}

prints
Before: [{1,2}, {7,4}, {6,8}]
After: [{1,2}, {6,8}, {7,4}]

A: It can be done by implementing your own sorting algorithm and move values in second row.
You might have an array of Obejcts. Each object will hold to values. Then implement your custom comparator and use sort function.
I have one more idea: reorder you array (if you can do so). Then keep pairs in one int[] table. And the outer table is a conatiner for int tables:
int [][] a = {{2,5},{1,4},{3,6}};
Arrays.sort(a, new Comparator<int[]>() {
        @Override
        public int compare(int[] p_o1, int[] p_o2) {
            return Integer.valueOf(p_o1[0]).compareTo(p_o2[0]);
        }
});

A: The easy way would be to create a Pair object that holds the pairs, and sort the collection of Pairs with a custom comparator that only compares the first item of a Pair.
You can always transform your Pairs back to a 2D array if required.
That's probably not the most efficient way but should be good enough for most use cases.

A: In case all of the first row's elements are unique and non-null, you can, before sorting, populate a map where first-row elements point to their second-row counterparts. After sorting the first row, you can then use the map to look up the first (sorted) row's corresponding elements of the second row.

A: You are basically doing a Map, why don't you use an Map implementation to assist you?
TreeMap implements SortedMap, so an easy solution would be placing all your mapped values inside it:
SortedMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
map.put(1, 2);
map.put(7, 4);
map.put(6, 8);

// You can iterate over map now, it'll be already sorted
for(Map.Entry<Integer, Integer> entry: map.entrySet())
{
    System.out.println(entry.getKey()+" : "+entry.getValue());
}

// This is not really necessary
Integer[][] x = {map.keySet().toArray(new Integer[0]), map.values().toArray(new Integer[0])};

// If you have Apache Commons you can:
int[][] y = {ArrayUtils.toPrimitive(map.keySet().toArray(new Integer[0])), ArrayUtils.toPrimitive(map.values().toArray(new Integer[0]))};

A: I copy pasted qSort from  http://www.algolist.net/Algorithms/Sorting/Quicksort and with a little modification
    public static void main(String[] args) throws Exception {
        int[][] x = { { 1, 7, 6 }, { 2, 4, 8 } };
        qsort(x[0], x[1], 0, x[0].length - 1);
        System.out.println(Arrays.deepToString(x));
    }

    static void qsort(int[] x0, int[] x1, int left, int right) {
        int index = partition(x0, x1, left, right);
        if (left < index - 1)
            qsort(x0, x1, left, index - 1);
        if (index < right)
            qsort(x0, x1, index, right);
    }

    static int partition(int[] x0, int[] x1, int left, int right) {
        int i = left, j = right;
        int tmp;
        int pivot = x0[(left + right) / 2];
        while (i <= j) {
            while (x0[i] < pivot)
                i++;
            while (x0[j] > pivot)
                j--;
            if (i <= j) {
                tmp = x0[i];
                x0[i] = x0[j];
                x0[j] = tmp;

                // swap x1 too
                tmp = x1[i];
                x1[i] = x1[j];
                x1[j] = tmp;

                i++;
                j--;
            }
        }
        return i;
    }
}

this program prints
[[1, 6, 7], [2, 8, 4]]

This may seem long, but usually for algorithms efficiency is critical, and this solution seems to be the fastest


text:
Q: Set rvm default interpreter in user's .rvmrc? I'm curious if it's possible to set my default Ruby interpreter within my $HOME/.rvmrc file (i.e. the equivalent of a rvm --default use 1.9.2).
I tried setting rvm_ruby_interpreter and rvm_ruby_version, but no luck.

A: Just cleaning out my unanswered questions... I ended up basically taking Phrogz's suggestion and adding this to my .zprofile:
RVM_DEFAULT=ruby-1.9.3-p194@home
if [ -x ~/.rvm/bin/rvm-prompt ] && [ "$(~/.rvm/bin/rvm-prompt)" != $RVM_DEFAULT ] ; then
  rvm use $RVM_DEFAULT
fi

Looking back it's kind of a weird question, probably due to the fact that I was new to rvm and relatively new to Ruby (but familiar with Unix and dotfiles).

A: You can't in the $HOME/.rvmrc or /etc/rvmrc file, but you can in project .rvmrc files by typing in rvm <interpreter>. So if you want 1.9.2 for one project, but ree for a different, type in rvm 1.9.2 in the first project's .rvmrc file, and rvm ree in the other project's .rvmrc file. You can also automatically activate gemsets this way.
Source: https://rvm.beginrescueend.com/workflow/rvmrc/

A: If you have projects using .rvmrc (or .ruby-version / .ruby-gemset), and want to be sure your home directory sets those envars to something else (no matter how many times you cd here and there), try this in ~/.bashrc:
PROMPT_COMMAND='[[ $PWD = $HOME ]] && (rvm use default; rvm gemset use global) > /dev/null'

Substituting your favorite flavors for default and global, of course.


text:
Q: LINQ on BindingList I have a BindingList I return from datacontext using Entity framework. I would like to use LINQ to get a subset of the data. How can I do that without converting to ObservableCollection or List because I don't want to lose the functionality exposed by BindingList?
BindingList<People> ppl = context.Peoples.Local.ToBindingList();

I'd Like to user .Where(p=>p.Name.Contains("ab"))
Any suggestions

A: The BindingList<T> class has a constructor that accepts a List<T>:
BindingList<People> ppl = new BindingList<People>(context.Peoples.Local.Where(p => p.Name.Contains("ab")).ToList());


text:
Q: Setting visibility and activity of a component in a callback I have a WPF program with a callback that executes after an async method.
The callback looks like this:
public void ProcessCompleteCallback()
{
    MessageBox.Show("Process completed.");
    GenerateOutputButton.IsEnabled = true;
    LoadingGifImage.Visibility = Visibility.Hidden;
    CommandManager.InvalidateRequerySuggested();
}

The first line get executed, but there's no change in the GUI regarding the second and third lines.
I tried to force a Requery by invoking the CommandManager, but it does not help.
Any idea why it isn't working?

A: Try this:
public void ProcessCompleteCallback()
{
    MessageBox.Show("Process completed.");
    Application.Current.Dispatcher.Invoke(() =>
    {
        GenerateOutputButton.IsEnabled = true;
        LoadingGifImage.Visibility = Visibility.Hidden;
        CommandManager.InvalidateRequerySuggested();
    });
}


text:
Q: integer value from object in another activity is not being received properly from another class. Not Answered Yet In my java android application im working on I have ran into a problem. In my activity I have an object that has a int value called addSpend. I have another java class that has a string array. I retrieved the object's value addSpend from the activity into this class and I wanted to put it in the String array but when i ran the app the string just returned the integer as 0 why is that?
Here is my code from the activity:
  Ship testin = new Ship();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.hangar);

    testin.setAddSpend(5);

Here is my code from the other class
    HangarActivity hAObject= new HangarActivity();
   int test = hAObject.testin.getAddSpend();

    String[] shipDesc = {"10 Planets Every 5 Secs \n 100$",
            "50 Planets Every 5 Secs \n" + test,
            "100 Planets Every 5 Secs \n 1500$",
            "500 Planets Every 4 Secs \n 3000$",
            "1000 Planets Every 4 Secs \n 7500$",
            "5000 Planets Every 4 Secs \n 15000$",
            "10000 Planets Every 3 Secs \n 50000$",
            "30000 Planets Every 3 Secs \n 100000$",
            "60000 Planets Every 3 Secs \n  500000$",
            "100000 Planets Every 1 Secs \n 1000000$"};

TextView2.setText(shipDesc[1]);

When you answer can you also explain how to fix the problem as well as tell
me what the problem is thanks.
Edit:
The answers I have recieved are about Intents and getting data from activities. I have one activity and the other a normal class so get Intents wont work. Can someone help me answer this question.

A: You are not supposed to instantiate activities with new. This way the Activity is not managed by Android and so the Lifecycle-Methods (onCreate) are not invoked.
Launch activities with Intent like this: Android Developer Guide

A: if you want to value between actives ,you have to use bundle, check example for this
http://congeritc.blogspot.com.tr/2012/04/android-passing-values-between-views.html


text:
Q: Foundation 4 responsive grid layout for large screens I've used compass to create new sass project with zurb foundation 4 framework. My screen.scss file looks following:
// Reset and normalization settings
@import "normalize";

// Global Foundation Settings
@import "settings";

// Comment out this import if you are customizing you imports below
@import "foundation";

Default settings contains following line:
$row-width: 62.5em;

It means that our grid row has to be 1000px (62.5em) for screens that are at least 768px.
What is the proper way to add one more media condition, which will increase $row-width variable up to 75em (1200px) for screens that are at least 1280px?

A: Create breakpoints for .row in app.scss, like this:
.row{
    @media #{$medium} {
        max-width: 75em;
    }
}

Foundation has variables for screen sizes that are used for media queries in _visibility.scss, for example $medium translates to "only screen and (min-width:80em)".
I haven't tried it myself yet, but should work.
Also, look at this answer, i just modified it a bit:
https://stackoverflow.com/a/14247136/961064
You can find other variables for different screen sizes in _visibility.scss: https://github.com/zurb/foundation/blob/master/scss/foundation/components/_visibility.scss


text:
Q: Find the count of occurrences of a substring within a string in php I have a string say
$result = \nHey there!Listen\n\n===\n\nLife is one\n\n===\n\nBut cs is 1.6ok\n\n===\n\nI hope you got what i wanna say\n\nSpeech finished\n\n===\n

Now I want to

*

*Find the no of occurences of \n in the above string. I have used the below function but it outputs nothing :
substr_count($result,"\n");

*I want to email $result as the Email-body , but \n characters are appearining as it is.
Anyway out there, that I can get rid of these \n characters and they are actually replaced by a new line in email subject ?

A: $result = str_replace("\n", chr(13), $result );
I replaced all the \n characters by chr(13) that is interpreted as enter .
So it worked out for me  :)


text:
Q: Get list items by checking priority of another list using linq I need to implement something,
I have an item list with different priorities and I need to select the items based on these priorities. For that, I have another list of priorities. If priority "one" does not match it should check the second priority and so on. This can be checked with a simple foreach loop and check with .Any() function. But I'm wondering this can be done with a single LINQ query.
enum Brand
{
   Nike,
   Adidas,
   Levis
}
class Info
{
   public Brand Brand { get; set; }
   public int Status{ get; set; }
   public int Group{ get; set; }
}

var list = new Info[]
{
  new Info{Brand = Brand.Nike, Status = 0, Group = "C"},
  new Info{Brand = Brand.Adidas, Status = 0, Group = "D"},
  new Info{Brand = Brand.Nike, Status = 4, Group = "A"},
  new Info{Brand = Brand.Levis, Status = 0, Group = "B"},
  new Info{Brand = Brand.Adidas, Status = 5, Group = "B"}
};
List<string> groupPririties = new List<string>() { "B", "D", "A", "E" };

According to this item list and priority list, I should get Levis and Addidas only. But if those two are not on the list it should return Adidas item and so on. If I dont have any priority matching items in my list, it should return null.
Can I acheive this with linq query only?

A:
But I'm wondering this can be done with a single LINQ query

var priorityItems = list
    .GroupBy(x => x.Group)
    .Where(grp => groupPririties.Contains(grp.Key))
    .OrderBy(grp => groupPririties.IndexOf(grp.Key))
    .FirstOrDefault();


text:
Q: Changing background of search bar in toolbar to be white? I implemented a search bar in my toolbar and it currently looks like this:

But I want to change the background to white with a shadow so that it looks more like this (taken from Material Design guidelines):

How can I do this?
Here is my implementation of the SearchView:
menu_main.xml:
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:title="Search"
        android:icon="@drawable/ic_search_white_24dp"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="collapseActionView|ifRoom" />

</menu>

MainActivity.java:
public abstract class MainActivity extends AppCompatActivity {

    protected Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);

        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        final MenuItem searchItem = menu.findItem(R.id.action_search);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchActivity.class)));
        searchView.setQueryHint("Search");

        MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                setMenuItemVisibility(menu, searchItem, false);
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                supportInvalidateOptionsMenu();
                return true;
            }
        });

        return true;
    }

    private void setMenuItemVisibility(Menu menu, MenuItem searchItem, boolean isVisible) {
        for (int i = 0; i < menu.size(); i++) {
            MenuItem item = menu.getItem(i);
            Log.d(TAG, item.toString());
            if (item != searchItem) {
                item.setVisible(isVisible);
            }
        }
    }
}

How can I style the SearchView to change the background color?


text:
Q: How do you declare instance variables in objective c? I am getting this error and many others due to a problem with the way I am using the 'numerator' and 'denominator' variables: "Inconsistent instance variable specification"
I am new to Objective C, so I am unsure how to resolve this otherwise simple issue.
#import <Foundation/Foundation.h>

@interface Fraction: NSObject

-(void)   print;
-(void)   setNumerator: (int) n;
-(void)   setDenominator: (int) d;

@end

@implementation Fraction
{
   int  numerator;
   int  denominator;
}
-(void) print
{
   NSLog (@"%i/%i", numerator, denominator);
}

-(void) setNumerator: (int) n
{
   numerator = n;
}

-(void) setDenominator: (int) d
{
   denominator = d;
}

@end

int main (int argc, char * argv[])
{
   @autoreleasepool {
      Fraction  *myFraction;

      myFraction = [Fraction alloc];
      myFraction = [myFraction init];

      [myFraction setNumerator: 1];
      [myFraction setDenominator: 3];

      NSLog (@"The value of myFraction is:");
      [myFraction print];
   }
   return 0;
}