Q:

Optimal Yahtzee (Dice roll) decisions: Probability and weighting choices

I'm a senior in computer science, and I have a hobby of taking on little projects that I find interesting. My current one is a Yahtzee optimal play solver. One would enter their current roll, and it would tell you if/what to hold onto and what to reroll (if any). It will then tell you what field to put your score in after the potential 2 re-rolls of varying sizes.
So far, I've come up with the following:

I realize calculating the probabilities for all possible configurations takes a lot of math, like "Probability of yahtzee if you can reroll twice" is about 1/29. But the probability with just one roll is 1/7776. Big difference. So I am going to write a simulation for ~1 billion random plays to see the (nearly accurate) odds of certain outcomes are after three rolls. So we can assume probabilities of outcomes are out of the way.
I plan to create something like this:
Consider a very concrete non-ambiguous example of just numbers. Say your value is 20. If you reroll (in this particular way), you have a 30% chance at 30, a 25% chance at 20, a 35% chance at 5, and a 10% chance at 80. Expected net = E(gain) - E(Loss) = Sum E(val_i - val). So we have E(change/net) = .3*(30 - 20) + .25*(20 - 20) + .35*(5 - 20) + .10*(80 - 20) = 5.75. So odds are if we make the roll, we will get 25.75 instead of our current 20. This is awesome and works great for this nice simple case... but when we speak of yahtzee, it isnt so simple.
For instance, we have four of a kind for, say, 5's. We also have a 5's place on the scoreboard. So if we have a 30% chance at 4 of a kind, we also have a 30% chance at four 5's. The point i'm trying to make is that your percentages wont add up to 100%. You could normalize them, but then you run into the problem of reducing weight on "something you would pick if you got it" which lowers the expected net value. For instance, say you have 1 1 2 2 3. If you rerolled the 3 to a 1, a 1/6 chance, you could either take the 25 point full house or the 3 point 1's. If we normalized, it would have a < 1/6 chance for full house and < 1/6 for 1's, depending on how many other % are in this normalization. So we are weighting the full house less simply because a paralell case exhists, even though you would likely choose the full house and not the 3 1's (I hope i'm making sense and not just rambling...) .

Anyway, i would love if one of your brilliant minds could help me think of an elegant way to do this. That is, given a roll of 5 dice and one of the 31 possible ways to hold back dice and reroll the others, which of the reroll configurations should you do, or should you not reroll (the 32nd choice). This is the "high level' way of saying this.
The lower level version is "Given the 32 choices (31 ways to reroll, 1 way to not reroll), which will give you the optimal score?". I got the 32 from (5 choose 0) ways to reroll no dice + (5 choose 1) ways to reroll 1 dice, etc to (5 choose 5) ways to roll 5 dice.
I'm just looking for some insight on how to weight your decisions appropriately. My hunch is that you have to do a bit of tricky manipulation such that if you have overlapping cases, you take the maximal case? (Ie. Three 1's vs. a full house with 1 1 1 2 2 after rerolling the 3 in 1 1 3 2 2, you would take that chance multiplied by the full house value, and not put any weight to the 3 1's. This of course assumes we need both a FH and 1's. If you didn't need a full house, it wouldnt even be in the equation).
Thanks everyone who takes the time to read this :).
John
[Edit:]
Thanks again for your help. I'm pretty sure I know how to do this now, but I wanted to run it by you to make sure im not misunderstanding anything. I know that you cant fit the entire game tree, but im just writing this in general assuming we had infinite memory. I know i'd actually only be able to use this with some initial non-blank states.
Begin algorithm
We have 13 boxes, each with a certain number of states.
When we make the tree, we start with all states initialized to "nothing", and simply proceed to do all possibilities of the states which gives us all possible end states when completed. Let us look at one such "leaf" node, which is at the end of a completed path through our tree.
In order to backtrack up the tree and give nodes values (scores), we start here. This nodes value is the sum of all scores in all boxes. To give its parent a value though, we set our value(score) to val := (val - stateScore) + (stateScore*probStateScore); This, from the parents point of view, takes away the guarenteed gain from that node state and changes it to the expected value (since we havent gotten that state yet, it is no longer a given but a probability). So if this nodes value is 300, and the gained score from its last choice was 50 with a probability of 10%, you would set your value to 250 + 5 = 255. Now, you parent takes the max of all its children and sets its own value to val := (max(children) - thisNodesStateScore) + thisNodesStateScore*probOfThisStateScore; By the time we get to the top, we have a set of nodes (first tier of the tree) with the optimal expected values should you pick them.
When playing the game, we may roll perhaps a 1 1 2 1 5. We can classify this as a 0 in any state, a 3 of a kind of ones = scoreState(10), 3 ones = scoreState(3), one 5 = scoreState(5), or one 2 = scoreState(2). We observe which of the values of these states is maximal, and choose that state. Continue until the end of the game.
End algorithm
If this is right, my question was how does the 3 rolls come into this? If you roll 1 1 2 15 and you have 2 rolls left, how do you give the optimal setup to hold and reroll based on the optimal values in the tree? Again, we can assume we know all probabilities of rolling a given setup. Thanks again, and I apologize that this question was so long and time consuming.

A:

As I wrote in a comment, if you're really going for optimal play, you need to consider the entire remaining game. The game has a finite but considerable number of possible states: There are $7$ different states for each of the $1$s through $6$s slots, $27$ different states for each of the three-of-a-kind, four-of-a-kind and chance slots, three binary states for full house and the two straights, and a count of yahtzees that you can probably safely limit to something like $0$ to $4$, for a total of $7^6\cdot27^3\cdot3^3\cdot6=375141013254$. That's a bit too much to keep in memory, but after two or three plays the number is reduced considerably and it becomes feasible to calculate the value of the remaining game by dynamic programming. That allows you to focus on a single play, since the later stages of the analysis tell you for every given final result of the current play which slot to use it for.
Assuming that you do know which slot to use which final result for, the problem you describe in the question (if I understand it correctly) isn't a problem. Every final result has a certain value, given by the maximum of all game values that would result from using it in the slots it can be used in, and you just need to optimize the expected value of these final result values; the probabilities of the final results add up to $1$, and the probabilities of getting a result that could be used for a particular slot are just a distraction; what counts isn't what slot a result could be used for but only which slot you actually will use it for in optimal play.
[Edit:]
The numbers of states come about as follows: In the slot for the $1$s, you may have entered anything from $0$ to $5$ $1$s, which makes six states, or you may not have entered anything yet, which makes seven. The slots for three-of-a-kind, four-of-a-kind and chance can contain any of the sums from $5\cdot1=5$ to $5\cdot6=30$, which makes $26$ states, or nothing, which makes $27$. The slots for full house and the two straights can each contain either nothing, zero, or the value of that slot, which makes $3$ states. The yahtzee count can in principle go up to the number of plays in the game, $13$, but I've never seen anyone roll more than $3$ yahtzees in a game, and I think it can be safely limited to $4$ or so; that makes five different states for the counts from $0$ to $4$, and one for nothing, which makes six.


Q:

Why does my JavaScript event execute on any input, rather than input to the proper field in Chrome?

I have an event I want to execute on key down in an input field. It does as much in Firefox. In chrome, however, it executes the event (a redirect) when I give the page any input (click, key down, etc). I can't seem to figure out why. Any ideas?
Here's the javascript:
var yum = document.getElementById("username");
var form = document.querySelector("div.resp-wrapper form[name='register']");
form.setAttribute("autocomplete", "off");
yum.addEventListener("keydown", function handler() {
    window.location.href = "https://giphy.com/gifs/troll-you-mad-face-eVy46EWyclTIA";
    this.removeEventListener("keydown", handler);
});

This is the page I'm working on [Link Deleted]; you can see the problem there while it's live. I'll be removing this link eventually.
Oh I guess I should probably mention that this is an invisible form field (it's a honeypot). It's between the captcha and the last visible form field. You can run a test by clicking where the field would be and pressing any key.
UPDATE: I am able to reproduce on my Windows machine; chrome version 74.0.3729.131 (Official Build) (64-bit). On my android, the behavior is the same as well (touching anywhere on the page redirects me) - version 74.0.3729.136. But was not able to reproduce on my Mac chrome version 71.0.3578.98.

A:

Figured it out; and, of course, it was something stupid. I removed the CSS from the form field and realized that, even though I had cleared my cache and browser history, several times, that didn't prevent Chrome's autofill feature from populating that field EVERY time.
When I removed the CSS I could see the field was always populated whenever I visited the page. Chrome had been filling in my email address (oddly, considering it's not an email field). I cleared my Chrome autofill settings and now the code works as expected. It's unfortunate that the autocomplete="off" attribute doesn't prevent this. I've read that usually this attribute is moot because the browser will override it anyway.


Q:

How to show Device date and time in iphone app?

Always i'm struggling with NSDate in iphone apps. I have developed one iphone app for US based client. The app should show the todays date. I have used the following code in my app. The date is showing correctly for me(Am in India). But, the date is also showing the india date for my client in (US). I want to show the date from the iphone/ipad device.
    NSDate *today1 = [[NSDate alloc] init];

NSString *dates = [NSString stringWithFormat:@"%@",[today1 description]];
dates = [dates substringToIndex:10];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateStyle:NSDateFormatterBehaviorDefault];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:dates];

How to do this? Any suggestions/sample code to solve this? I has spend 6 hours to solve my problem but, i didn't find the answer? Please help me. Thanks to spend your valuable time with me.

A:

Use Locale
See code blow Taken from here
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];

NSString *dateFormat;
NSString *dateComponents = @"yMMMMd";

dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:usLocale];

Updated answer below
I have tested this should work out of the box any where is the world.
NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
[dateFormat setLocale:[NSLocale currentLocale]];
NSString *dateString = [dateFormat stringFromDate:date];
[dateFormat release];
NSLog(@"Date: %@:", dateString);


Q:

How to transfer files to production?

We are a group that started working on a fairly big website with an existing codebase. We have a test and a production server.
Our idea is to have a test repository with a number of devs having push access to; and a blessed repository that only a few can push to. The blessed repo is supposed to be always stable and represent the latest production version.
How can I automate the process of transferring the files into production? Is it bad to have the production files under version control? That way, pushing to the blessed repository would mean deployment. But, what happens when there are merge conflicts? Will the production server break until it is resolved?

A:

To put it simple:
The push process in itself should be fully automatic. Whether you have some custom script, or you simply pull from the "blessed" repo to the production environment. That is up to you. You should just have something automated, because automated processes can be made reliable (as opposed to uploading files by hand and such).
However, the push process should be triggered manually. You push your updates, and once you feel confident, you tag it as a release candidate and pull it to your test environment (that would ideally be as similar to your production environment as possible). Once the RC is tested, the push can be initiated.
As of today, nothing else can give you, what human testers can.
This sounds a little slow, in the sense that the feedback loop is a relatively big. But for proper testing, it is important to take an fixed snapshot, which is then examined for 24-48h (or maybe more, depending on the size of the project). The opposite is a scenario, where you find a lot of bugs right after pushing and you try to patch it up with some quick fixes that introduce new bugs.
You better make a release with known bugs (of acceptable severity), than one with unknown bugs (of unknown severity).


Q:

How to use TitanCleanup in 1.0.0?

I'm working on a school project and we've been experimenting with some bulk loading scripts. However, I need a way to clear our titan database of all vertices, edges, and properties to start over. From what I can tell, TitanCleanup.clear() is the way to do it. But whenever I go through gremlin and close the graph, calling TitanCleanup.clear(graph) just results in a groovysh_evaluate error. We can't find any better documentation of using TitanCleanup other than the titan docs which just say what it does. Any examples or pointers to where to look would be much appreciated.
Edit: This is the whole thing I'm putting into gremlin, including the stack trace
gremlin> g = TitanFactory.open('./conf/titan-hbase.properties')
==>standardtitangraph[hbase:[hadoop-16.csse.rose-hulman.edu]]
gremlin> g.close()
==>null
gremlin> TitanCleanup.clear(g)
No such property: TitanCleanup for class: groovysh_evaluate
Display stack trace? [yN] y
groovy.lang.MissingPropertyException: No such property: TitanCleanup for class: groovysh_evaluate
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:51)
        at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:304)
        at groovysh_evaluate.run(groovysh_evaluate:3)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.codehaus.groovy.tools.shell.Interpreter.evaluate(Interpreter.groovy:69)
        at org.codehaus.groovy.tools.shell.Groovysh.execute(Groovysh.groovy:185)
        at org.codehaus.groovy.tools.shell.Shell.leftShift(Shell.groovy:119)
        at org.codehaus.groovy.tools.shell.ShellRunner.work(ShellRunner.groovy:94)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.super$2$work(InteractiveShellRunner.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:130)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuper0(ScriptBytecodeAdapter.java:150)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.work(InteractiveShellRunner.groovy:123)
        at org.codehaus.groovy.tools.shell.ShellRunner.run(ShellRunner.groovy:58)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.super$2$run(InteractiveShellRunner.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:130)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuper0(ScriptBytecodeAdapter.java:150)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.run(InteractiveShellRunner.groovy:82)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.apache.tinkerpop.gremlin.console.Console.<init>(Console.groovy:144)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.apache.tinkerpop.gremlin.console.Console.main(Console.groovy:303)

A:

You'll need to import the TitanCleanup class before you use it:
gremlin> import com.thinkaurelius.titan.core.util.TitanCleanup

After you close the graph (as you were already doing), you should be able to run TitanCleanup.clear(g) successfully.


Q:

Use ARRAYFORMULA in a custom script function (Google Sheets + GAS)

Is there any way to adjust this function for use with ARRAYFORMULA in spreadsheets?
function SendTelegram(botSecret, chatId, body) {
  var response = UrlFetchApp.fetch("https://api.telegram.org/bot" + botSecret + "/sendMessage?text=" + encodeURIComponent(body) + "&chat_id=" + chatId + "&parse_mode=HTML");
}

Instead of using a formula for each line like this:
=SendTelegram($H$1,$I$1,F2)
=SendTelegram($H$1,$I$1,F3)
=SendTelegram($H$1,$I$1,F4)
=SendTelegram($H$1,$I$1,F5)

By using this way:
=ARRAYFORMULA(SendTelegram($H$1,$I$1,F2:F))

Returns the following message:
Limit Exceeded: URLFetch URL Length. (line 22).

A:

Something like this, you might have to adjust to the particular behavior you want.
function SendTelegram(botSecret, chatId, body) {
  if (body.map) { // is array?
  var response = body.map(function(b) {return SendTelegram(botSecret,chatId,b);});
   } else {
  var response = UrlFetchApp.fetch("https://api.telegram.org/bot" + botSecret + "/sendMessage?text=" + encodeURIComponent(body) + "&chat_id=" + chatId + "&parse_mode=HTML");
  }
}


Q:

Alien Swarm: "Who scores the kill if ... (collection of cases)?"

This is a collection of questions like "Who gets the kill if someone does this and someone else does that?"
Includes sentry, barrels, flamethrower questions, as well as questions about various offhand items.

Do sentry kills count as kills?

Who scores the kill if...

...someone brings a sentry to the mission and someone else assembles it?
...someone brings a sentry to the mission, assembles it and then someone dismantles and assembles it again?
...someone brings a sentry to the mission, starts assembling it, but someone else finishes it?
...the sentry was brought by someone and assembled by someone else, and then rotated by another person?

If an alien dies because of the explosion of a barrel you shot, does it count as a kill?
If you shoot a barrel with weapon, and an alien dies, does that count as weapon kill?
(i.e. for achievements)

If someone sets an alien on fire, and then someone else attacks it with flamethrower again (on Easy difficulty, for example), whom does the kill count to?

Are kills with the following offhand items counted?

Hornet Barrage
MTD6 Smart Bomb
Hand Grenades
Assault Jets
v45 Electric Charged Armor
ML30 Laser Trip Mine
M478 Proximity Incendiary Mines
IAF Tesla Sentry Coil

Partial answers are also good.

A:

1. Sentry kills do not count as kills!
2.1. Yes, barrel-kills are counted
   2. No, they don't count as a weapon kill.
4. Offhand items:
   Hornet Barrage    ✓ Yes
   Smart Bomb        ✓ Yes
   Hand Grenades     ✓ Yes
   Assault Jets      ✓ Yes
   Electric Armor    ✓ Yes
   Laser Trip Mines  ✓ Yes
   Incendiary Mines  ✗ No
   Tesla Sentry Coil ✗ No


Q:

Can you send a file larger that the SendBufferSize throuh a TcpClient?

I am experimenting with the Tcp connections in .NET and I would like to send some data that is larger than the SendBufferSize proporty of the TcpClient object. Is it possible to send the data by simply writing to the network stream or do I need to cut it in pices and send those and at the other end create it again?

A:

From MSDN:

If the network buffer is smaller than the amount of data you provide the Write method, several network send operations will be performed for every call you make to the Write method.

You only need to call Write once, the TcpClient will handle splitting it into multiple network operations.


Q:

iPhone SDK: How do I pass an array of values from a ViewController onto other ViewController?

I tried creating a method like below in SecondViewController:
-(void)setValue:(NSMutableArray*)array
 {
      //NSMutableArray *newArray = [[NSMutableArray alloc] init];
      newArray = [array retain];
 }

and passing the value from FirstViewController using an object of SecondViewController named second:
[second setValue:existingArray];

existingArray is an NSMutableArray.
What could be wrong?

A:

In the code you have set the array in the "second" object of a SecondViewController.
So you need to use that object for displaying the SecondeViewController, other wise how can it won't show the array.
Check the following code.
 //   In the FirstViewController

- (void)buttonClicked:(id)sender{

    SecondViewController *second = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle: nil];
 [second setValue:existingArray];
 [self.navigationController pushViewController:second animated:YES];
 [second release];

}

Here in the code I am assigning the data to the array in the "second" object and I am using that object to display the controller.
Regards,
Satya


Q:

Wrong Reachability status -Boolean value is not set in iOS

I have a Boolean value to check Reachability with following code.
@property (nonatomic,assign) BOOL isOnline;

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];

    Reachability * reach = [Reachability reachabilityWithHostname:@"www.google.com"];

    reach.reachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Reachable");
            self.isOnline = YES;
        });
    };

    reach.unreachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.isOnline = NO;
            NSLog(@"Unable");
        });
    };

    [reach startNotifier];

However when i check it with
if(self.isOnline == YES)
    {
NSLog(@"YES");
}

else{
NSLog(@"NO");
}

It's only showing NO. I am sure Reachability can reach to the internet and i have connection. However Boolean value is not set to YES.
How can i do it?

A:

It seems that you are using the Reachability by Tony Million so 1st thing i would suggest is to use isReachable function in it.
Secondly, there is an issue with this reachability in iOS7 so to resolve this you have to do the following
In the Function -(BOOL)isReachableWithFlags:(SCNetworkReachabilityFlags)flags in Reachability.m you have to commit one line
#if TARGET_OS_IPHONE
    if(flags & kSCNetworkReachabilityFlagsIsWWAN)
    {
       // We're on 3G.
       if(!self.reachableOnWWAN)
          {
          // We don't want to connect when on 3G.
          // Comment this line
           //connectionUP = NO;

         }
    }
#endif


Q:

two prepositional phrases

The lighted dial of Dudley's watch, which was dangling over the edge of the sofa on his fat wrist, told Harry he'd be eleven in ten minutes' time.

(Harry Potter and the Sorcerer's Stone)
Are the highlighted two prepositional phrases one element, or is ‘over the edge of the sofa’ a parenthetical phrase?

A:

Over the edge of the sofa on his fat wrist is not two but three preposition phrases, to wit

over the edge
of the sofa
on his fat wrist

3 (boldfaced) prepositions, each with its own object NP, equals 3 preposition phrases.
It is certainly the case that there are frequent compound preposition constructions with words like edge; but they're no different in principle from compound noun constructions like horse doctor, pony ride, and snake bite.

[[on/under/over/from/at] [the edge/side/back/arm]] [of the chair/sofa/table/desk]

It is also true that, while the first two PPs do go together as a single constituent in this way, the third one is independently attached to dangling, as a further locative, pinning down Dudley's watch, the antecedent of the relative clause that contains all these PPs.

A:

Yes, those are two prepositional phrases: one whose head noun is edge and governed by the preposition over, and the other one whose head noun is wrist and governed by preposition on.
There are no parentheses here.
Edit
This should help:
(S (NP (NP The dial)
       (PP of
           (NP (NP (NP Dudley 's)
                   watch)))
               ,
               (SBAR (WHNP which)
               (PP of
                   (NP (NP (NP Dudley 's)
                           watch)
                       ,
                       (SBAR (WHNP which)
                             (S (VP was
                                    (VP dangling
                                        (PP over
                                            (NP (NP the edge)
                                                (PP of
                                                    (NP the sofa))))
                                        (PP on
                                            (NP his fat wrist))))))))

               ,))
   (VP told
       (NP Harry)
       (SBAR [that]
                  (S (NP he)
                     (VP 'd
                         (VP be
                             (NP eleven)
                             (PP in
                                 (NP (NP ten minutes ')
                                     time)))))))

.)

If you have not yet turned to tools that crank out constituency parses — and probably dependency parses, too — then you probably should.


Q:

jersey 2.6 jackson 2.3 and complex keys in maps

i have a simple Object containing an id. I am searching for a way to use it as a key in a hashmap.
Jersey is registered as a servlet in my web.xml
<servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>org.ambientlight.RestConfig</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
</servlet>

jackson is registered here.
public class RestConfig extends ResourceConfig {

    public RestConfig() {
        packages("org.ambientlight.webservice");
        register(JacksonFeatures.class);
    }
}

This is my key object:
@JsonSerialize(using = SwitchableIdSerializer.class)
public class SwitchableId {

    public String id;

    public SwitchType type;

    public SwitchableId(String id, SwitchType type) {
        super();
        this.id = id;
        this.type = type;
    }
}

this is my serializer
public class SwitchableIdSerializer extends JsonSerializer<SwitchableId> {

    @Override
    public void serialize(SwitchableId data, JsonGenerator json, SerializerProvider provider) throws IOException,
    JsonGenerationException {
        json.writeString(data.id + "|" + data.type);
    }
}

if i return the SwitchableId directly everything works like aspeceted. but if i return a structure with a hasmap then the serializer is not used and just  simple SwitchableId.toString() is applied.
There are so many examples out there. for older releases or if jackson is used standalone. But i cannot find any hint how to deal within a jersey servlet. Please help!
i have tried to annotate the containing class:
public class PowerstateHandlerConfiguration extends AbstractActionHandlerConfiguration {

    @JsonSerialize(keyUsing = SwitchableIdSerializer.class)
    public Map<SwitchableId, Boolean> powerStateConfiguration = new HashMap<SwitchableId, Boolean>();
}

but without success. What is missing?

A:

Thank you for your help,
A great annoying thing is. I used that annotation before the map on the server side without success. On my android client instead, a module registration for the spring rest template does not work. And there i use the annotation that you showed me in your answer - and there it works.
Anyway, to answer my question and for everybody who tries to register a module on the object mapper that jersey uses - here is my solution as it works for me now. A Feature is that instead of annotating every map the serializer is always available.
The resource config is the following:
public class RestConfig extends ResourceConfig {

    public RestConfig() {
        packages("org.ambientlight.webservice");

        register(new ContextResolver<ObjectMapper>() {

            @Override
            public ObjectMapper getContext(Class<?> type) {
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.registerModule(new SwitchableIdModule());
                return objectMapper;
            }
        });
    }
}

the serializer was changed to read map keys:
public class SwitchableIdSerializer extends JsonSerializer<SwitchableId> {

    @Override
    public void serialize(SwitchableId data, JsonGenerator json, SerializerProvider provider) throws IOException,
    JsonGenerationException {
        json.writeFieldName(data.id + "|" + data.type);
    }
}

the serializer is registered in a simple module - that was registered in the ResourceConfig:
public class SwitchableIdModule extends SimpleModule {

    private static final long serialVersionUID = 1L;

    public SwitchableIdModule() {
        addKeySerializer(SwitchableId.class, new SwitchableIdSerializer());
        addKeyDeserializer(SwitchableId.class, new SwitchableIdDeserializer());
    }
}


Q:

knockout not all properties are being mapped

I suppose that for the knockout experts this will be a simple question for me it's confusing.
My JSON input:
    {
      "odata.metadata":"http://localhost:49163/odata/$metadata#TwitterMessages","value":[
        {
          "message":{
            "text":"Pellentesque fermentum a diam a suscipit. Donec ultrices tempor sapien, vitae dictum erat pulvinar sagittis. Vivamus a fermentum lectus, et lacinia enim. Morbi pretium adipiscing risus, vitae euismod lacus fermentum eu.","company_fk":3,"image_url":"http://www.baconwrappedmedia.com/wp-content/uploads/2013/01/funny-kids-bacon-wrapped-media-21.jpg","active":true,"author_id":"3242342423","message_id":3,"author_picture":"http://3.bp.blogspot.com/_Gxh8CVH8l8Y/TJBDI4QVfnI/AAAAAAAAAWE/W1H4Z2MAub0/s1600/547206_1271901770610.27res_400_483.jpg","author_name":"Ligula","source":"TWITTER","createddatefriendly":"1 day ago","message":"Ut at erat at mauris euismod tincidunt non id justo?","pubdate":"2014-01-10T13:27:42.917"
          },"hashtag":{
            "hashtag_id":2,"hashtag":"#voetbal","company_fk":3
          },"twitter_id":"0","user_screenname":"Ligula","user_name":"Ligula","message_fk":3,"hashtag_fk":2
        },{
          "message":{
            "text":"Duis sed nunc semper, volutpat urna et, volutpat diam.","company_fk":3,"image_url":"http://www.allfunnystuff.com/wp-content/uploads/2013/04/funny-baby-angry-punch.jpg","active":true,"author_id":"75675675","message_id":4,"author_picture":"http://www.drodd.com/images8/funny-face15.jpeg","author_name":"Curabitur","source":"TWITTER","createddatefriendly":"3 day(s) ago","message":"Suspendisse a sapien id lorem tincidunt imperdiet eget id velit.","pubdate":"2014-01-10T13:30:26.657"
          },"hashtag":{
            "hashtag_id":2,"hashtag":"#voetbal","company_fk":3
          },"twitter_id":"0","user_screenname":"Curabitur","user_name":"Curabitur","message_fk":4,"hashtag_fk":2
        }
      ]
    }

My javascript/Knockout code:
    function CompanyViewModel() {
        var self = this;
        self.name = ko.observable();
    }

    function TweetViewModel(item) {
        var self = this;
        self.user_screenname = ko.observable("");
        self.user_name = ko.observable("");
        self.message = ko.observable("");
        self.hashtag = ko.observable("");
        ko.mapping.fromJS(item, {}, self);
    }

    function ViewModel() {
        var self = this;
        self.Company = ko.observable(new CompanyViewModel());
        self.Tweets = ko.observableArray([new TweetViewModel()]);

        $.getJSON('/Data/company.json', function (data) {
            ko.mapping.fromJS(data, {}, self.Company());
        });

        $.getJSON('/Data/tweets.json', function (allData) {
            var mappedTweets = $.map(allData.value, function (item) {
                return new TweetViewModel(item)
            });
            self.Tweets(mappedTweets);

            console.log(self.Tweets())
        });
    }

    var vm = new ViewModel();

    ko.applyBindings(vm);

My HTML:

Everything is working fine. But here is my question:
Why i DON'T need to "declare" the Message.Text observable to use it for databinding but i DO NEED to declare the user_screenname observable?
If i would remove the line:
        self.user_screenname = ko.observable("");

I get an error: user_screenname is not defined. As i use the mapping construction i would expect that user_screenname property is also automatically mapped to the viewmodel. Or am i doing something wrong?

A:

You need to declare explicitly your user_screenname because one of your message in the returned data does not contain the user_screenname property so the mapping does not create it and your binding will break.
You can prefix your property with $data:
	`

in this case the binding won't break if you don't have an user_screenname property so it will work without explicitly declaring the user_screenname.


Q:

What’s the adjective form of “odaxelagnia”?

All I can think of is “odaxelagniac” like “mania” and “maniac” but I’m not positive.
Edit: What’s the word, if one exists, for someone who suffers from odaxelagnia, a form of paraphilia? Also, is “paraphiliac” a word?

A:

There are a few paraphilias that end with the greek suffix -lagnia. This is actually hard to look up because the dictionaries only consistently list one as far as I can tell, that is algolagnia.

algolagnia n. Sexual gratification derived from inflicting or
  experiencing pain. al′go·lag′nic adj. al′go·lag′nist n. American
  Heritage Dictionary
n (Psychiatry) a perversion in which sexual pleasure is gained
  from the experience or infliction of pain. ˌalgoˈlagnic adj
  ˌalgoˈlagnist n Collins English Dictionary
n. sexual pleasure derived from enduring or inflicting pain, as in
  masochism or sadism. algo•lag′nic, adj. al`go•lag′nist, n.
   Random House Kernerman Webster's College Dictionary

Collins English Dictionary gives "algolagniac" as noun.

algolagniac n another word for algolagnist Collins
  English Dictionary

From Merriam-Webster we get the noun for the person "algolagniac"

algolagnia : a perversion (such as sadism or masochism)
  characterized by pleasure and especially sexual gratification in
  inflicting or suffering pain. algolagniac noun

And further down on the page we also get:

algolagnic adj

In Oxford Living Dictionaries in addition to algolagnia we get:

algolagnic
  adjective & noun

(strange? probably not, see below for -ic endings being both noun and adjective)
and

algolagniac noun
A person who practises algolagnia, a sadomasochist.
Oxford Living Dictionaries

OK, now this gets very weird. My claim is that the word for a person who has one of these paraphilias is mostly the word that ends in -iac. However note that American Heritage Dictionary, Merriam-Webster and Oxford Living Dictionaries list "paraphilic" and "amnesic" as both adjective and noun, and both "paraphiliac" and "amnesiac" as both adjective and noun. How confusing is that? However searches for "amnesic who" and amnesiac who" - and "paraphilic who" and "paraphiliac who" - both show that the -iac ending word is more common for referring to people with the condition.
However a person with narcolepsy or schizophrenia is a "narcoleptic" or "schizophrenic", not "narcoleptiac" or "schizophreniac". We can be sure that a person with a condition of mania, egomania, kleptomania, pyromania has a word ending in -maniac. Paranoiac is listed in dictionaries as both a noun and adjective, with Merriam-Webster also listing "paranoic" as an alternative. I can't make heads or tails out of these rules.
My suggestion, based on what I've seen and due to the fact that these are obscure terms, would be to use:
odaxelagnia as the noun for the condition (for obvious reasons)
odaxelagniac as the noun for the person with the condition (modelled on paraphiliac and amnesiac, and also to disambiguate it from the -ic suffix which is often an adjective)
As for the adjective for the person with the condition, I'm not completely sure. All the dictionaries I've checked do not list "algolagnistic", so I'd be tempted to suggest simply what the dictionaries say, to use "odaxelagnist". However the word "algolagnistic" does come up in searches, and I feel that naturally one might be disposed to use this following the pattern of "masochist"/"masochistic" and all the other words ending in -ist. Also the addition of -ic to -ist to form suffix -istic is a very natural and intuitive use of a common English morpheme:
fascist/fascistic
nationalist/nationalistic
misogynist/misogynistic
hedonist/hedonistic
pacifist/pacifistic
Where the word ending in -ist is a noun denoting a person and the -istic is the adjective.
Based on this, even though the suffix -lagnistic isn't listed in dictionaries, you may want to use this. These are such specific words that the majority of paraphilias don't even appear in dictionaries.

A:

"odaxelagniac" definitely has been used, but it looks more like a noun to me
It seems to me that, even though -ac is etymologically an adjective suffix, odaxelagniac would be more likely to be used as a noun referring to someone with odaxelagnia.
So in fact, I don't think the answer to the question in your title ("What’s is the adjective form of “odaxelagnia”?") is the same as the answer to the question in the body of your post ("What’s the word, if one exists, for someone who suffers from odaxelagnia, a form of paraphilia?"). I think a sentence like "He/she is an odaxelagniac" (with a predicate noun) would be more likely than either "He/she is odaxelagniac" or "He/she is odaxelagnistic" as a way of expressing the idea "He/she suffers from odaxelagnia".
Compare the usage of maniac: I'm pretty sure that people say things like "He's a maniac!" more frequently than they say things like "He's maniac!"
A complication: even if I am right in saying that maniac (along with -iac words in general) is rare as a predicate adjective, it does seem to occur fairly frequently in attributive position before a noun (e.g. "the maniac driver"). It's not clear that the word is actually an adjective in this context, because either nouns or adjectives can be used before nouns in English (compare "the frog prince").
Using Google search, I was able to find various examples of "odaxelagniac" being used as a noun and being used as an attributive word (I'm not sure whether a noun or an adjective) before a noun.
Noun examples:

"I'm an odaxelagniac It means I get sexual arousal from biting"

(Whisper.sh)

You bit like an odaxelagniac's boyfriend!

(in comment posted by venomlash on September 25, 2015 at 4:11 PM on the Stranger article "The Morning News: After Yesterday's Fatal Crash, Renewed Questions about Ride the Ducks and the Aurora Bridge", by Heidi Groover,  Sep 25, 2015 at 9:00 am)

Attributive examples:

"...just like that teenager I yelled at last week wasn't an odaxelagniac creep"

("Paranoia", by MistressMacha, published Aug 3, 2011 on fanfiction.net)

Yeah, you're right. I'm always seeing promicuous girls around here calling themselves odaxelagniac retifists. It's a plauge. */sarcasm*

(Posted June 15, 2008 by Hallucigenia in "Tila Tequila calls Herself an Asexual!?", on The Asexual Visibility & Education Network Forums)

I didn't find any examples of sentences where "odaxelagniac" was used as a predicative adjective (e.g. no examples like "I am odaxelagniac", "He/she is odaxelagniac", "They/we/you are odaxelagniac").
"odaxelagnistic" seems like it would be a "correctly" formed adjective corresponding to odaxelagnia, but I don't think it has been used yet, and I don't know if it would be a good choice to refer to an individual with odaxelagnia
If for whatever reason you want a word related to odaxelagnia that is definitely an adjective and not a noun, I think the most likely formation would be odaxelagnistic, although I can't find any evidence of it being used yet.
The Oxford English Dictionary has an entry for the adjective algolagnistic, which it says is from "algolagnia n. + -istic suffix, after German algolagnistisch (1892)." It is defined as

Of, relating to, or characterized by algolagnia; sadomasochistic.

Although I can't find a dictionary with entries for urolagnistic or coprolagnistic, Google search turns up a few examples of these adjectives.
The example sentences in OED entry for algolagnistic suggest to me that adjectives of this type tend to be used to refer to behaviors or inclinations rather than to individuals:

1895   C. G. Chaddock tr. A. P. F. von Schrenck-Notzing Therapeutic Suggestion ix. 175   Very often we find that algolagnistic inclinations arise at the sight of boys being whipped at school.
1908   E. Paul tr. I. Bloch Sexual Life of our Time xxi. 558   De Sade..collected almost all the facts..regarding algolagnistic phenomena [Ger. algolagnistischen Erscheinungen] in ethnology.
1914   Med. Standard Aug. 301/1   Algolagnistic manifestations are frequently the result of a lack of familiarity with the facts of science, abnormal educational or religious influences, [etc.].

"odaxelagnic" also seems like it would be a "correctly" formed adjective
As Janus Bahs Jacquet mentioned in a comment, it also seems like -ic should work as an adjective suffix in this context. Even though "algolagnic" has no no OED entry, there are a number of hits for it on Google Books, some of which correspond to adjective uses. By analogy, it should be possible to use "odaxelagnic" as an adjective.

A:

You have, odaxetic

(adjective) Referring to a sensation of biting or itching; it is not used in the working medical parlance.

The Free Dictionary


Q:

Simulator fails to open

I always getting this error whenever i runs iOS 6 series simulators.  I tried lot of steps for this problem. i.e., 1. deleting Derived Data, Creating a new project ..
Notification center label http://imageshack.com/a/img836/3808/adat.png
if anyone tell me the solution for this.

A:

you have not provided more details i post answer in guessing from you question
refer below link it more helpful.
IOS simulator failed to install application? in Xcode 5
iOS Simulator failed to install the application
https://discussions.apple.com/message/24468440#24468440


Q:

Visual studio not following moving semantic

I am trying this code in Visual Studio 2015 v4.
using namespace std;

void * operator new(size_t size) {
    cout << "Creating new " << endl;
    void * p = malloc(size);
    return p;
}

class CTest {
private:
    string a;
    string b;
public:
    CTest( const string &&one , const string && two  ) :a(move(one)), b(move(two)) {}
};

int main() {
    CTest("one", "one" );
    return 0;
}

This code outputs "Creating new" 4 times in Visual studio , which means it allocates memory 4 times. However following semantics it should only allocate twice ( creating 2 literals in data segment , creating one and two function argument = 2 allocs , and then moving their resource to a and b member variable )
Compiling this under g++ outputs "Creating new" twice, as it should.
Is there any settings i need to set in order for VS to follow moving semantics? It should be supported by default as far as i know.
Thanks for help.

A:

There are several issues here:
1) std::move does not move, especially if you pass by const &&. See answers here and here.
2) Every std::string implementation I am aware of uses small buffer optimization. Such implementations will never allocate when constructed with short strings (such as "one").
3) The standard library runtime is allowed to call operator new during static initialization, for instance to setup std::cout. The allocations you see are most likely not related to the string constructor or (lack of) move.


Q:

Second form not displaying correctly

I have created two different forms, one for the user to select values and the other for displaying all the total costs.
I did declare an instance of the other class and passed it the two variables that held charges. Within the second class I had a constructor accept the arguments and then assign them to variables within the second form.
When trying to display the results on the second for by using the ".ShowDialog();" method, the form appears blank, nothing on it.
First form:
namespace DormAndMeal
{
    public partial class MainForm : Form
    {
        int ALLENPRICE = 1500;
        int PIKEPRICE = 1600;
        int FARTHINGPRICE = 1800;
        int UNIVERSITYPRICE = 2500;

        int MEAL7 = 600;
        int MEAL14 = 1200;
        int UNLIMITEDMEAL = 1700;

        public MainForm()
        {
            InitializeComponent();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            // close
            this.Close();
        }

        private void btnOkay_Click(object sender, EventArgs e)
        {

            int roomCharge = 0;
            int foodCharge = 0;

            // Checking for the room plan chosen, assigning price to roomCharge
            if (radAllen.Checked)
            {
                roomCharge = ALLENPRICE;
            }
            else if (radPike.Checked)
            {
                roomCharge = PIKEPRICE;
            }
            else if (radFarthing.Checked)
            {
                roomCharge = FARTHINGPRICE;
            }
            else if (radUniversity.Checked)
            {
                roomCharge = UNIVERSITYPRICE;
            }

            // Checking for which meal plan was selected, assign price to foodCharge
            if (radMeal1.Checked)
            {
                foodCharge = MEAL7;
            }
            else if (radMeal2.Checked)
            {
                foodCharge = MEAL14;
            }
            else if (radMeal3.Checked)
            {
                foodCharge = UNLIMITEDMEAL;
            }

            // Instance of Charges form
            Charges myCharges = new Charges(foodCharge, roomCharge);

            // Display the form
            myCharges.ShowDialog();
        }
    }
}

As you can see, the form finds which radio buttons were selected and assigns prices accordingly, then it creates an instance of the second form and shows it.
form 2:
namespace DormAndMeal
{
    public partial class Charges : Form
    {
        int foodTotal;
        int roomTotal;

        public Charges()
        {
            InitializeComponent();
        }

        public Charges(int food, int room)
        {
            this.roomTotal = room;
            this.foodTotal = food;
        }

        private void Charges_Load(object sender, EventArgs e)
        {
            lblFood.Text = foodTotal.ToString("c");
            lblRoom.Text = roomTotal.ToString("c");

            lblTotal.Text = (foodTotal + roomTotal).ToString("c");
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            // close
            this.Close();
        }
    }
}

This form has a constructor to accept the arguments and assign them, then go through and display them to the appropriate variables located on the form.
For some reason the second form shows up blank.

A:

You are not calling the InitializeComponents method, which will create all of the controls from the designer file:
public Charges(int food, int room)
{
  InitializeComponent();
  this.roomTotal = room;
  this.foodTotal = food;
}

or as pointed out in comments, you can call your other constructor:
public Charges()
{
  InitializeComponent();
}

public Charges(int food, int room)
  : this()
{
  this.roomTotal = room;
  this.foodTotal = food;
}


Q:

Converting Objective-C malloc to Swift

I am working on a project that was written in Objective-C and needs to be updated to Swift. We use a C file for transferring data.
Here is the code I was given in Objective-C:
- (NSData *)prepareEndPacket {
    UInt8 *buff_data;
    buff_data = (uint8_t *)malloc(sizeof(uint8_t)*(PACKET_SIZE+5));
    // Call to C File
    PrepareEndPacket(buff_data);
    NSData *data_first = [NSData dataWithBytes:buff_data length:sizeof(uint8_t)*(PACKET_SIZE+5)];
    return data_first;
}

In the C .h file I have this for reference:
#define PACKET_SIZE     ((uint32_t)128)

I can not seem to find a good way of converting this to Swift. Any help would be appreciated.

A:

malloc and free actually work fine in Swift; however, the UnsafeMutablePointer API is more "native". I'd probably use Data's bytesNoCopy for better performance. If you want, you can use Data(bytes:count:), but that will make a copy of the data (and then you need to make sure to deallocate the pointer after making the copy, or you'll leak memory, which is actually a problem in the Objective-C code above since it fails to free the buffer).
So, something like:
func prepareEndPacket() -> Data {
    let count = PACKET_SIZE + 5
    let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: count)

    PrepareEndPacket(buf)

    return Data(bytesNoCopy: buf, count: count, deallocator: .custom { ptr, _ in
        ptr.deallocate()
    })
}

By using bytesNoCopy, the Data object returned is basically a wrapper around the original pointer, which will be freed by the deallocator when the Data object is destroyed.
Alternatively, you can create the Data object from scratch and get a pointer to its contents to pass to PrepareEndPacket():
func prepareEndPacket() -> Data {
    var data = Data(count: PACKET_SIZE + 5)

    data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
        PrepareEndPacket(ptr)
    }

    return data
}

This is slightly less efficient, since the Data(count:) initializer will initialize all the Data's bytes to zero (similar to using calloc instead of malloc), but in many cases, that may not make enough of a difference to matter.


Q:

React / span with onClick event not in tag

Something out of my knowledge is happening in my code. I have a component which renders a span tag with a onClick event:
{props.page.word}

But when I check the code in the browser the span tag doesn't have the onClick:
developer tools screenshot of the code
I know it seems a little abstract but I just can't figure why the onClick isn't there.
Thanks.

A:

You are confusing JSX with html. The span tag you have in your code is not plain html tag it is a javascript object(read more about jsx here). React takes care of binding the events for you, don't worry if you can't see onClick in your html.


Q:

Linear interpolation of two 2D arrays

In a previous question (fastest way to use numpy.interp on a 2-D array) someone asked for the fastest way to implement the following:
np.array([np.interp(X[i], x, Y[i]) for i in range(len(X))])

assume X and Y are matrices with many rows so the for loop is costly. There is a nice solution in this case that avoids the for loop (see linked answer above).

I am faced with a very similar problem, but I am unclear on whether the for loop can be avoided in this case:
np.array([np.interp(x, X[i], Y[i]) for i in range(len(X))])

In other words, I want to use linear interpolation to upsample a large number of signals stored in the rows of two matrices X and Y.
I was hoping to find a function in numpy or scipy (scipy.interpolate.interp1d) that supported this operation via broadcasting semantics but I so far can't seem to find one.
Other points:

If it helps, the rows X[i] and x are pre-sorted in my application. Also, in my case len(x) is quite a bit larger than len(X[i]).
The function scipy.signal.resample almost does what I want, but it doesn't use linear interpolation...

A:

This is a vectorized approach that directly implements linear interpolation. First, for each x value and each i, j compute the weight w expressing how much of the interval (X[i, j],  X[i, j+1]) is to the left of x.

If the entire interval is to the left of x, the weight of that interval is 1.
If none of the subinterval is to the left, the weight is 0
Otherwise, the weight is a number between 0 and 1, expressing the proportion of that interval to the left of x.

Then the value of PL interpolant is computed as Y[i, 0] + sum of differences dY[i, j] multiplied by the corresponding weight. The logic is to follow by how much the interpolant changes from interval to interval. The differences dY = np.diff(Y, axis=1) show how much it changes over the entire interval. Multiplication by the weight prorates that change accordingly.
Setup, with some small data arrays
import numpy as np
X = np.array([[0, 2, 5, 6, 9], [1, 3, 4, 7, 8]])
Y = np.array([[3, 5, 2, 4, 1], [8, 6, 9, 5, 4]])
x = np.linspace(1, 8, 20)

The computation
dX = np.diff(X, axis=1)
dY = np.diff(Y, axis=1)
w = np.clip((x - X[:, :-1, None])/dX[:, :, None], 0, 1)
y = Y[:, [0]] + np.sum(w*dY[:, :, None], axis=1)

Demonstration
This is only to show that the interpolation is correct. Blue points: original data, red ones are computed.
import matplotlib.pyplot as plt
plt.plot(x, y[0], 'ro')
plt.plot(X[0], Y[0], 'bo')
plt.plot(x, y[1], 'rd')
plt.plot(X[1], Y[1], 'bd')
plt.show()


Q:

Can't assign id as variable to jade template

When doing this:
div(id=player)
  ul.timeline
    {{#epochs}}
    li.epoch {{epoch}}
    {{/epochs}}

and render it with hogan
html = ss.tmpl['board'].render({ //ss is for socketstream, it uses hogan.
  epochs: treeStructure,
  player: "player2"
});

I get the following error
! Errror formatting Jade template
/Users/ilyadorman/dev/game/client/templates/board.jade:2
    1| div(id=player)
  > 2|   ul.timeline
    3|     {{#epochs}}
    4|     li.epoch {{epoch}}
    5|     {{/epochs}}

player is not defined

But when I do {{player}} it works fine! What am I missing?

A:

Like it says, player is not defined within the context you are trying to use it in.
You could put single or double quotes around player and then it would be defined-- as a primitive string.
Like div(id='player').
If that's what you want.  If you want the div's id to be dynamically altered with the variable then you should use the double curlies for that to be passed in.
These are different programmatic contexts. You can define variables within a Jade template and perform operations on them, but these are different from the variables passed in, which in Hogan/Mustache are called tags.  In this case, you want the tags.
I've never tried anything like this, but something along the lines of
div(id='{{player}}')
should work.


Q:

Why do I have different versions of Kotlin JARs in the classpath?

I decided to add a couple Kotlin files to an existing Java Android project in AS 3.0.
Once I added Kotlin files, I let the assistant add the appropriate lines to my build.gradle files, in particular:
project build.gradle
buildscript {
    ext.kotlin_version = '1.2.21'
    //...
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

app build.gradle
// top of file
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
//....
dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

Unfortunately all builds now produce this warning:
Warning:Runtime JAR files in the classpath should have the same version. These files were found in the classpath:
/Users/sddsfsd/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk7/1.2.21/88bfff5aa470143a83b0bc5ec00c0be8cabd7cad/kotlin-stdlib-jdk7-1.2.21.jar (version 1.2)
/Applications/Android Studio.app/Contents/gradle/m2repository/org/jetbrains/kotlin/kotlin-stdlib-jre7/1.1.51/kotlin-stdlib-jre7-1.1.51.jar (version 1.1)
/Users/sddsfsd/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.2.21/d64187eb2d9d1521be3421aa8c6774a8625cdde8/kotlin-stdlib-1.2.21.jar (version 1.2)

Why does Android Studio have its own older version of Kotlin in the classpath? How do I remove it?

A:

Why do I have different versions of Kotlin JARs in the classpath?

You have different versions because some of your dependencies depend on Kotlin 1.1 version.

Why does Android Studio have its own older version of Kotlin in the
  classpath? How do I remove it?

Updating your dependencies like I explained here in a related question about renamed stdlib-jre7 and already explained here for conflictive dependencies that have not been renamed.
Kotlin reference - binary compatibility warnings:

Runtime JAR files in the classpath should have the same version.
Some runtime JAR files in the classpath have an incompatible version.
Consider removing them from the classpath.
This means that you have a dependency on libraries of different
  versions, for example the 1.1 standard library and the 1.0 reflection
  library.
To prevent subtle errors at runtime, we recommend you to use the same
  version of all Kotlin libraries. In this case, consider adding an
  explicit dependency.

In your case, the indirect dependency was renamed and you need to update the library that uses it:
Find conflictive dependencies via command, or build tab since AS 3.1
./gradlew -q dependencies app:dependencies --configuration variantDebugCompileClasspath

In the related question, the warning was removed updating Realm version to 4.3.2.
Note: I checked my path and I also have outdated dependencies there but it's ok if you don't use it.


Q:

Where does GCM data to be pushed get stored?

In GCM, there are three main components

GCM server
third party app server
client (mobile)

Which one of them stores the data that is to be pushed?
For example, if a mobile1 has to communicate with a mobile2 and it wants to send a message "HI" and an image, then where does this two pieces of data get stored, on the app server, or on the GCM server?

A:

Found out a solution the flow is like from
app server to ccs to gcm


Q:

See stacktrace after deadlock

My application is being executed in debug mode and then deadlock happens. Is there any way to see the stacktrace before deadlock or at least the last called method?

A:

Click BreakAll (Ctrl + Alt + Break) and open Debug->Windows->Threads
There you can see stacktrace for every thread


Q:

Can Grave Betrayal give me a Mutavault?

Would Grave Betrayal give me a Mutavault? I'm guessing no, but enough rules have changed since Onslaught that I'm not going to guess.

A:

Yes, you get a Black Mutavault with a +1/+1 counter on it. It will not be a Zombie because non-creatures cannot have creature subtypes.

Detailed Explanation
First, you need to know why Grave Betrayal triggers.

603.6c Leaves-the-battlefield abilities trigger when a permanent moves from the battlefield to another zone [...]
603.6d [...] Leaves-the-battlefield abilities will trigger based on [an object's] existence, and the appearance of objects, prior to the event rather than afterward.

Mutavault was a creature prior to death, and so Grave Betrayal will trigger. The trigger doesn't care what Mutavault becomes after death. Second, you need to know how Grave Betrayal can still find the Mutavault in the graveyard even though it is a new object.

603.6 Trigger events that involve objects changing zones are called "zone-change triggers." Many abilities with zone-change triggers attempt to do something to that object after it changes zones. During resolution, these abilities look for the object in the zone that it moved to.

Third, you need to know why lands cannot have creature subtypes.

205.3d An object can't gain a subtype that doesn't correspond to one of that object's types.

Lastly, here is how the events actually unfold:

An opposing Mutavault creature dies.
Grave Betrayal triggers.
Grave Betrayal's trigger resolves. It looks for Mutavault in the graveyard and finds it there.
Mutavault returns to the battlefield under your control. It gains the color Black and a +1/+1 counter. It won't be a Zombie because Zombie is a creature subtype and Mutavault is not a creature at the moment.


Q:

Custom model method to get a relation in Laravel

I try to define a custom Model method in Laravel. I have a n:m relation between Subscription and Notification over SubscriptionNotification.
I already defined the default relations:
public function subscription_notifications() {
    return $this->hasMany('App\SubscriptionNotification');
}

public function notifications() {
    return $this->belongsToMany('App\Notification', 'subscription_notifications');
}

Now I want to define a method, which returns a collection of notifications. I collect the IDs of the notifications I want in an array and write the following method:
public function notifications_due() {
    // Collect $notification_ids
    return $this->belongsToMany('App\Notification', 'subscription_notifications')->whereIn('notifications.id', $notification_ids)->get();
}

But when I want to use the mothod by $subscription->notifications_due, I get the following error:
[LogicException]
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

I'm new to Laravel (I come from Rails). I don't know if this is in Laravel even possible. Maybe someone can help me. Thanks!

A:

Remove the ->get() part in the method notifications_due. get() will return a Collection, but when calling the method as a property (or magic method), Laravel expects the method to return an instance of Relation. Laravel will then execute the query and transform it to a Collection automatically.
Also, you can use your already defined notifications() method:
public function notifications_due() {
    // Collect $notification_ids
    return $this->notifications()->whereIn('id', $notification_ids);
}


Q:

Android Http requests handler

I have a problem with handling http requests with proxy on Android. I have a 3rd-party component which contacts a server and I need it to communicate via proxy. I can't set proxy in system. Handling of proxy for DefaultHttpClient should be fine but there is a problem with 3ed-party component which can't be accessed (don't have a source code) and can't set a proxy.
My questions are:
Is there any way to set proxy only for my application?
Or
Is there any way to create listener to http requests to handle proxy setting when calling for website?
Or
Any other ideas?

A:

Even if there was, if the third party component is not using system libraries, but their own, it would still not pick it up. Contact them and have them add proxy support, or at least make it clear what HTTP library they are using.


Q:

NSTableView sorting decimal column causes exception

I have a NSTableView that I am using to experiment with sorting columns. The string, integer and date columns seem to work fine but the decimal column is causing a crash which I'm scratching my head over.
Here's the data structure:
class LearningStruct : NSObject, Decodable {
    @objc var ID : Int
    @objc var Text : String
    @objc var Description : String
    @objc var CreationDate : Date
    @objc var UpdateDateTime : Date?
    @objc var ValueX: Decimal
    @objc var IsTrue : Bool
}

(Note the use of @objc and NSObject, apparently Swift can't natively handle key value coding required for sorting)
I create some test JSON data:
let learningJSON = "{\"Items\": [{\"ID\": 1, \"Text\": \"Item 1 text\", \"Description\": \"This is item 1 description\", \"CreationDate\": \"02/17/2019\", \"ValueX\": 123.45, \"UpdateDate\": \"02/17/2019\", \"IsTrue\": true}, {\"ID\": 2, \"Text\": \"Item 2 text\", \"Description\": \"This is item 2 description\", \"CreationDate\": \"02/14/2019\", \"ValueX\": 789.01, \"UpdateDate\": \"02/14/2019\", \"IsTrue\": false}]}"
internal var learningItems = [LearningStruct]()

Then I use the decoder to populate the array:
            let decoder = JSONDecoder()
            let dateformatter = DateFormatter()
            dateformatter.dateFormat = "MM/dd/yyyy" // "MM/dd/yyyy'T'HH:mm:ss"
            decoder.dateDecodingStrategy = .formatted(dateformatter)
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            let learningData = try decoder.decode(LearningItems.self, from: learningJSON.data(using: .utf8)!) as LearningItems
            learningItems = learningData.Items

The NSTableColumns have their Identifier set to the property name in the storyboard for easy mapping.
           for prop in properties {
                let colindex = learningTableView.column(withIdentifier: NSUserInterfaceItemIdentifier.init(prop)) // Get the column index number for that property key
                if (colindex >= 0) { // If the column exists
                    let descriptorID = NSSortDescriptor(key: prop, ascending: true)
                    learningTableView.tableColumns[colindex].sortDescriptorPrototype = descriptorID
                }
            }

Here's the sorting logic:
/// Sorting logic
    func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {

        print("--- Sorting logic begin ---")

        // Debug print the sorters
        for col in learningTableView.tableColumns {

            if col.sortDescriptorPrototype != nil {
                let sorter = col.sortDescriptorPrototype!.key!
                let direction = col.sortDescriptorPrototype!.ascending
                print("Column \(col.identifier.rawValue): sort descriptor: \(sorter), is ascending: \(direction)")
            } else {
                print("Column \(col.identifier.rawValue): no sort descriptor")
            }
        }

        print("+++ Sort descriptors list")
        let learningItemsMutable = NSMutableArray(array: learningItems)
        let sorters = tableView.sortDescriptors
        for sortdesc in sorters {
            print("Sort descriptor: \(sortdesc.key!)")
        }
        print("Sorting...")
        learningItemsMutable.sort(using: sorters)
        learningItems = learningItemsMutable as! [LearningStruct]
        tableView.reloadData()
        print("--- Sorting logic end ---")
    }

When I run the code, it sorts everything perfectly when I click on a column until I get to the "ValueX" column. The example below is me clicking on each column in order, ending with "Value X". When I click that, I get an exception that doesn't really help me... can anyone assist?
--- Sorting logic begin ---
Column ID: sort descriptor: ID, is ascending: true
Column Text: sort descriptor: Text, is ascending: true
Column Description: sort descriptor: Description, is ascending: true
Column CreationDate: sort descriptor: CreationDate, is ascending: true
Column ValueX: sort descriptor: ValueX, is ascending: true
Column IsTrue: sort descriptor: IsTrue, is ascending: true
+++ Sort descriptors list
Sort descriptor: ValueX
Sort descriptor: CreationDate
Sort descriptor: Description
Sort descriptor: Text
Sort descriptor: ID
Sorting...
2019-02-22 12:29:27.093825+0000 NSTableView Learning[8571:1649436] [General] -[NSInvocation getArgument:atIndex:]: struct with unknown contents found while getting argument at index -1
2019-02-22 12:29:27.095961+0000 NSTableView Learning[8571:1649436] [General] (
    0   CoreFoundation                      0x00007fff4aecaded __exceptionPreprocess + 256
    1   libobjc.A.dylib                     0x00007fff76f96720 objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff4ae22af3 -[NSInvocation getArgument:atIndex:] + 473
    3   Foundation                          0x00007fff4d251a85 _NSGetValueWithMethod + 174
    4   Foundation                          0x00007fff4d184494 -[NSObject(NSKeyValueCoding) valueForKey:] + 284
    5   Foundation                          0x00007fff4d193d68 _sortedObjectsUsingDescriptors + 389
    6   Foundation                          0x00007fff4d1be3c9 -[NSMutableArray(NSKeyValueSorting) sortUsingDescriptors:] + 497
    7   NSTableView Learning                0x000000010000d3c9 $S20NSTableView_Learning0cB10ControllerC05tableB0_24sortDescriptorsDidChangeySo0aB0C_SaySo16NSSortDescriptorCGtF + 5289
    8   NSTableView Learning                0x000000010000dacf $S20NSTableView_Learning0cB10ControllerC05tableB0_24sortDescriptorsDidChangeySo0aB0C_SaySo16NSSortDescriptorCGtFTo + 111
    9   AppKit                              0x00007fff48b9e388 -[NSTableView _sendDataSourceSortDescriptorsDidChange:] + 82
    10  AppKit                              0x00007fff4862275a -[NSTableView setSortDescriptors:] + 327
    11  AppKit                              0x00007fff48b9e5ca -[NSTableView _changeSortDescriptorsForClickOnColumn:] + 542
    12  AppKit                              0x00007fff48b81d73 -[NSTableHeaderView _trackAndModifySelectionWithEvent:onColumn:stopOnReorderGesture:] + 1000
    13  AppKit                              0x00007fff48b84eeb -[NSTableHeaderView mouseDown:] + 596
    14  AppKit                              0x00007fff4859f1eb -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] + 5668
    15  AppKit                              0x00007fff484d3223 -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] + 2319
    16  AppKit                              0x00007fff484d26c9 -[NSWindow(NSEventRouting) sendEvent:] + 481
    17  AppKit                              0x00007fff4836f954 -[NSApplication(NSEvent) sendEvent:] + 336
    18  AppKit                              0x00007fff4835d19d -[NSApplication run] + 755
    19  AppKit                              0x00007fff4834c8a3 NSApplicationMain + 780
    20  NSTableView Learning                0x000000010001085d main + 13
    21  libdyld.dylib                       0x00007fff78064ed9 start + 1
    22  ???                                 0x0000000000000003 0x0 + 3
)

A:

The used type Decimal, in Objective-C NSDecimal is not in the list of supported key-value-coding types. KVC documentation
typedef struct {
    signed   int _exponent:8;
    unsigned int _length:4;     // length == 0 && isNegative -> NaN
    unsigned int _isNegative:1;
    unsigned int _isCompact:1;
    unsigned int _reserved:18;
    unsigned short _mantissa[NSDecimalMaxSize];
} NSDecimal;

The NSDecimal uses bit fields which are the key issue.
Every attempt to make it work (this should be possible) will be not Codable out of the box.


Q:

Multiprocessing Pool.apply executing n-1 times

Im having an issues with multiprocessing.Pool.apply.
My objective is to have 5 processes, each filling an array with 100 elements (100 for this test), and then merging then arrays into a single one with length 500. Problem is, it ends up with only 400 elements for any reason i cant understand.
I have tried changing the amount of processes created by the pool but that didn't change anything at all besides the execution time.
import torch.multiprocessing as mp
import itertools

pool = mp.Pool(processes=5)
split = int(500/5)
lst =  pool.apply(RampedGraph, (split,[]))    #each foo returns a list of 100 elements
lst = list(itertools.chain.from_iterable(lst)) #merging the lists into one

len(lst)
>>>400

The expect output of len(lst) should be 500.
Can anyone enlighten me on what Im doing wrong?
EDIT Foo method explained:
def RampedGraph(popsize, graph_lst):
    cyclic_size = int(math.ceil(popsize/2))
    acyclic_size = popsize - full_size
    append = graph_lst.append
    for _ in range(cyclic_size):
        t = c.Node().cyclic()
        nn = c.number_of_nodes()
        c = c.calculate(0, False)
        append((t,nn,c))
    for _ in range(acyclic_size):
        t = c.Node().acyclic()
        nn = c.number_of_nodes()
        c = c.calculate(0, False)
        append((t,nn,c))
    return graph_lst

A:

import torch.multiprocessing as mp
# import multiprocessing as mp
import itertools

def RampedGraph(popsize, graph_lst):
    print(mp.current_process().name)
    return list(range(100))

num_workers = 5
pool = mp.Pool(processes=num_workers)
split = int(500/num_workers)
lst =  pool.starmap(RampedGraph, [(split,[])]*num_workers)
lst = list(itertools.chain.from_iterable(lst))
print(len(lst))
# 500

pool.starmap(RampedGraph, [(split,[])]*5) sends 5 tasks to the task pool.
It causes RampedGraph(split, []) to be called 5 times concurrently.
The 5 results returned by RampedGraph are collected into a list, lst.
Note that calling RampedGraph 5 times concurrently does not guarantee that all 5 processors are used. For example, if RampedGraph were to finish very quickly, it is possible that one processor handles more than one task, and perhaps another processor never gets used at all.
However, if RampedGraph takes a non-trivial amount of time, in general you can expect all 5 worker processes to be used.
Note: I ran the above code with import multiprocessing as mp rather than import torch.multiprocessing as mp. But since torch.multiprocessing is supposed to be a drop-in replacement for multiprocessing, that shouldn't make a difference.

Using multiprocessing comes with both costs and benefits.
The benefit, of course, is the ability to use multiple processors concurrently.
The costs include the time required to launch additional processes, and the cost of interprocess communication. multiprocessing uses Queues to transport arguments to the function run by the worker processes, and to transport the returned value back to the main process. To transport the  returned values through the Queues, the objects are serialized into bytes via pickling. If the pickled objects being sent through the Queues are large, this can add a significant overhead cost when using multiprocessing. Notice that all these costs are not incurred by an equivalent sequential version of the same code.
Particularly when the function run by the worker processes finishes quickly, overhead costs can dominate the total run time of the program, making code which uses multiprocessing slower than a sequential version of the same code.
Thus, a key to speed when using multiprocessing is to try to minimize interprocess communication and to make sure the worker processes do a lot of work so the overhead costs become a relatively small part of the total run time.


Q:

Clearing the cache in rails without deleting everything else

I am using redis for the cache store in rails
Doing Rails.cache.clear will indeed clear the cache, but essentially remove everything else in Redis.
Is there a way to expire all the cache keys without completely removing everything else in redis?

A:

if you know the keys already, you can go like this
# delete a single key
Rails.cache.delete(:key)

# delete many keys
Rails.cache.delete_if {|k, v| k =~ 'key' }

actually the Rails.cache keys are just a {} Hash , so you can go with any kind of ruby.hash methods.(hopefully im not wrong)


Q:

Problem with time format

I wrote the following code to get the time
public String getTime() {
    final Calendar cld = Calendar.getInstance();
    String time = cld.get(Calendar.HOUR) + ":" + (cld.get(Calendar.MINUTE));
    try {
        Date date = new SimpleDateFormat("HH:mm").parse(time);
        time = new SimpleDateFormat("HH:mm").format(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return time;
}

This always give me time like
11:59
01:07
But I need in 24 hrs format like:
11:59
13:07
How to change the code.

A:

Use HOUR_OF_DAY instead of HOUR.


Q:

Getting the error NSCFDictionary objectAtIndex while displaying data in Uitableview

I am new to the iOS , When i am implementing to fetch the data from api , i am getting the -[__NSCFDictionary objectAtIndex:]: error.
Code:
Request Dispatching
-(void)JobTakeFive{

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    //NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.json-generator.com/api/json/get/cuCmzXKUOa?indent=2"]]];

     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.json-generator.com/api/json/get/cpvIEMqesy?indent=2"]]];

    NSLog(@"%@",request);

    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (conn)
    {
        responseData = [[NSMutableData alloc] init];

    }else{

    }
}

Response Handling and parsing
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
    postresponce = [[NSMutableData alloc] init];
    [postresponce setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [responseData appendData:data];
    [postresponce appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    NSLog(@"%@ ", [error localizedDescription]);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSError *error=nil;

    NSDictionary *responCE =[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    respArray=[responCE valueForKey:@"yes_questions"];
   respArray1=[responCE valueForKey:@"no_questions"];

    [MBProgressHUD hideHUDForView:self.view animated:YES];

    [take5table reloadData];

}

Troublezone - Showing response in Tableview
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 2;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    switch (section) {
        case 0:
            return respArray.count;
            break;

        case 1:
            return respArray1.count;
            break;

        default:
            return 0;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

 [tableView deselectRowAtIndexPath:indexPath animated:YES];

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    NSLog(@"Section:%ld Row:%ld selected and its data is %@",
          (long)indexPath.section,(long)indexPath.row,cell.textLabel.text);
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

 if (section == 0) return @"First section header title";
    if (section == 1) return @"Second section header title";

    else

    return @"Hello World";
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier1";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    UILabel *Sno = (UILabel *)[cell viewWithTag:96];

    UILabel *QuesLab = (UILabel *)[cell viewWithTag:98];

    if (indexPath.section==0) {

     //   titleUIL.text = [[dicc valueForKey:[headersArray objectAtIndex:indexPath.section]]objectAtIndex:indexPath.row];

        Sno.text=[NSString stringWithFormat:@"%@",[[respArray objectAtIndex:indexPath.row] valueForKey:@"question_id"]];

        QuesLab.text=[[respArray objectAtIndex:indexPath.row]valueForKey:@"question_title"];

    }

    else if (indexPath.section==1){

        Sno.text=[NSString stringWithFormat:@"%@",[[respArray1 objectAtIndex:indexPath.row] valueForKey:@"question_id"]];

        QuesLab.text=[[respArray1 objectAtIndex:indexPath.row]valueForKey:@"question_title"];

    }

    if (indexPath.row %2 ==1)
        cell.backgroundColor = [UIColor colorWithRed:.9 green:.9 blue:.9 alpha:1];
    else
        cell.backgroundColor = [UIColor colorWithRed:.8 green:.8 blue:.8 alpha:1];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  50;
}

Error
-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x7f90d3eaf8a0
2016-11-08 10:44:16.935 Ecs Services[3691:701820] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x7f90d3eaf8a0'

My response is:
Printing description of responCE:
{
    "job_location" = "Crown Promenade ";
    "job_name" = "Test Schedule 2 for Crown Promenade";
    "job_no" = 207;
    "no_questions" =     {
        12 =         {
            "question_answer" = No;
            "question_id" = 13;
            "question_title" = "Is there a risk of falls or falling objects?";
            "question_type" = Full;
        };
        13 =         {
            "question_answer" = No;
            "question_id" = 14;
            "question_title" = "Is there a risk of Plant or Traffic interaction?";
            "question_type" = Full;
        };
        14 =         {
            "question_answer" = No;
            "question_id" = 15;
            "question_title" = " Is there a risk of electrical hazards?";
            "question_type" = Full;
        };
        15 =         {
            "question_answer" = No;
            "question_id" = 16;
            "question_title" = " Is the work in or involve a confined space? ";
            "question_type" = Full;
        };
        16 =         {
            "question_answer" = No;
            "question_id" = 19;
            "question_title" = " Does the job involve hot works?";
            "question_type" = Short;
        };
        17 =         {
            "question_answer" = No;
            "question_id" = 20;
            "question_title" = "Is there a risk of environmental damage? ";
            "question_type" = Full;
        };
        18 =         {
            "question_answer" = No;
            "question_id" = 21;
            "question_title" = " Is there a risk of crush injuries? (in,on or between)";
            "question_type" = Full;
        };
        19 =         {
            "question_answer" = No;
            "question_id" = 22;
            "question_title" = "Is there a risk of water  or sun hazards?";
            "question_type" = Full;
        };
        20 =         {
            "question_answer" = No;
            "question_id" = 23;
            "question_title" = "Are there any access issues or concerns ";
            "question_type" = Full;
        };
        21 =         {
            "question_answer" = No;
            "question_id" = 24;
            "question_title" = " Are there hazards involving unstable ground?";
            "question_type" = Full;
        };
        22 =         {
            "question_answer" = No;
            "question_id" = 25;
            "question_title" = " Do I need to apply isolation ?.................... ";
            "question_type" = Short;
        };
        23 =         {
            "question_answer" = No;
            "question_id" = 26;
            "question_title" = "Could there be any uncontrolled movement? \U2026...\U2026\U2026.\U2026.. ";
            "question_type" = Full;
        };
        24 =         {
            "question_answer" = No;
            "question_id" = 27;
            "question_title" = "Do I need mechanical lifting or a work at height platform? .. ";
            "question_type" = Full;
        };
        25 =         {
            "question_answer" = No;
            "question_id" = 39;
            "question_title" = test;
            "question_type" = Full;
        };
    };
    "yes_questions" =     {
        0 =         {
            "question_answer" = Yes;
            "question_id" = 1;
            "question_title" = " Do I understand the job thoroughly?";
            "question_type" = Full;
        };
        1 =         {
            "question_answer" = Yes;
            "question_id" = 2;
            "question_title" = "Am I authorized, qualified & trained to do the work?";
            "question_type" = Short;
        };
        10 =         {
            "question_answer" = Yes;
            "question_id" = 11;
            "question_title" = "Do I have the appropriate PPE & in good condition?";
            "question_type" = Full;
        };
        11 =         {
            "question_answer" = Yes;
            "question_id" = 12;
            "question_title" = "Can I complete the task on my own ? ";
            "question_type" = Full;
        };
        2 =         {
            "question_answer" = Yes;
            "question_id" = 3;
            "question_title" = "Do I have the correct tools & they\U2019re in good condition?";
            "question_type" = Full;
        };
        26 =         {
            "question_answer" = Yes;
            "question_id" = 40;
            "question_title" = "";
            "question_type" = Full;
        };
        27 =         {
            "question_answer" = Yes;
            "question_id" = 41;
            "question_title" = "equipment in good condition";
            "question_type" = Full;
        };
        3 =         {
            "question_answer" = Yes;
            "question_id" = 4;
            "question_title" = "Have I informed others who may be affected by my work? ";
            "question_type" = Full;
        };
        4 =         {
            "question_answer" = Yes;
            "question_id" = 5;
            "question_title" = "Is there free access to others not involved in the vicinity?";
            "question_type" = Full;
        };
        5 =         {
            "question_answer" = Yes;
            "question_id" = 6;
            "question_title" = " I have read & understand the SWMS applicable to this task? ";
            "question_type" = Full;
        };
        6 =         {
            "question_answer" = Yes;
            "question_id" = 7;
            "question_title" = "Have I obtained all permits & filled out correct paperwork? ";
            "question_type" = Short;
        };
        7 =         {
            "question_answer" = Yes;
            "question_id" = 8;
            "question_title" = "Have I applied lock out tags (where & if required)? ";
            "question_type" = Full;
        };
        8 =         {
            "question_answer" = Yes;
            "question_id" = 9;
            "question_title" = " Have I performed a pre job on-site inspection?";
            "question_type" = Full;
        };
        9 =         {
            "question_answer" = Yes;
            "question_id" = 10;
            "question_title" = " Am I fit for this task? (fatigue, injury, medications)";
            "question_type" = Full;
        };
    };
}

A:

The problem is, your response is returning you dictionaries, not arrays as you are expecting. To fix that, you can use the allValues method of NSDictionary which returns you an array of all values inside a dictionary.
To fix that, make following corrections:
In your response parsing:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSError *error=nil;

    NSDictionary *responCE =[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    respArray=[[responCE valueForKey:@"yes_questions"] allValues]; //Now you have array of dictionaries which were contained in the dictionary with key yes_question
   respArray1=[[responCE valueForKey:@"no_questions"] allValues];//Now you have array of dictionaries which were contained in the dictionary with key no_question

    [MBProgressHUD hideHUDForView:self.view animated:YES];

    [take5table reloadData];

}


Q:

How do I select fields from an existing Rails resource, not from database?

I have an existing model object, I want to "slim it down" to just a few fields. Use cases include receiving an item from one service to be filtered before passing it on to another service, or using fixtures in tests.
The following works on the database query:
User.select([:firstname,:lastname]).first

to get the record with only firstname and lastname. What if I already did u = User.first so I now have u which has all of the fields.
How do I turn u into an object with just the two fields above without making another inefficient DB query?
u.select([:firstname,:lastname])

doesn't work.
To clarify: I want to get to the equivalent of User.select(:firstname,:lastname).first if I already have the output (post-SQL) of User.first. What is my next step?

A:

It doesn't work that way.
The essence of Active Record pattern (at heart of Rails' ActiveRecord) is that each object corresponds to a specific row in the database. Not backwards though: there may be multiple objects that point to the same row. That's causing some trouble here.
You can either have identity comparison...
In RDBMS the only way you can make sure the two objects correspond to the same row is to compare the objects' primary keys. If one of the two objects doesn't have a primary key, you don't hav a way to determine if whether they are one and the same row.

But ActiveRecord does something, right?

Nothing fancy, actually:
def ==(comparison_object)
  super || # If it's one and the same Ruby object, the result is obvious
    comparison_object.instance_of?(self.class) && # otherwise if same class
    !id.nil? && # and there IS non-nil id
    comparison_object.id == id # Then compare their ids
end

So if the object doesn't have an id, it's non-equal to anything but itself.
...or you can do comparison by value
That takes you about as far as comparing field-by-field, no different than comparing hashes of attributes.
This has a downside that the condition would pass even if the object is built from a different row, but contains the same values in given attributes. I woudn't regard that as a problem: in that specific case you know where one of the compared objects originates (a fixture, I suppose), so its data is trusted. So if the given object contains the same data that the trusted object has, the test is reliable enough.
For that you could one object's entire hash of attributes and compare it to a slice of your fixture:
assert_equal a.attributes, b.attributes.slice(:key1, :key2)