text:
Q: Update attribute in callback Rails 3 Following on from this question, I have spent the day trying to add a cumulative running sales total to my sales table. It's a bit tricky (for me) because I want a running total for sales where the isbn_id is the same, and, within that set, records where the channel_id is the same - ranked by invoice_date. This is all so I can calculate royalties on a particular range of units sold.
Here's my non-working callback code, in the Sale model:
before_save :runningtotal

private

def runningtotal
  @sale = Sale.order("invoice_date ASC")
  @lastbal = @sale.find_all_by_isbn_id(@isbn).group_by(&:channel)
  #that sucessfully gets all sales ranked by date ascending, then groups them by channel, just for the current isbn.
  @lastbal.each do |channel, sale|
    sale.each_with_index do |sale, i|
      previous_sale = sale[i-1] unless i==0
      next unless previous_sale
      @total_quantity = previous_sale.quantity + :quantity
      write_attribute(:total_quantity,@total_quantity)
    end
  end
end

Is this roughly how a callback should be written - just in the model? Does it just run magically before_save of a new sale?
My core question is: how can I update the attribute "total_quantity" to be the sum of "quantity" for the current record, and "total_quantity" for the previous record by date, in a before_save callback, within the constraints of the finds for isbn_id and channel_id?
Here's the output of the find:
ruby-1.9.2-p180 :025 > @lastbal = @sale.find_all_by_isbn_id(@isbn).group_by(&:channel)
=> {#<Channel id: 4, isbn_id: nil, channel_name: "Gratis", created_at: "2011-05-26 11:08:22", updated_at: "2011-05-26 11:08:22">=>[#<Sale id: 26, isbn_id: 2, quantity: 10000, value: 40000, currency: "", total_quantity: nil, created_at: "2011-05-26 11:11:30", updated_at: "2011-05-26 11:11:30", customer: "6", retail_price: nil, discount: nil, channel_id: 4, invoice_date: "2011-05-18", rule_id: nil, trenche: nil>], #<Channel id: 1, isbn_id: nil, channel_name: "Home", created_at: "2011-05-16 19:47:27", updated_at: "2011-05-16 19:47:27">=>[#<Sale id: 22, isbn_id: 2, quantity: 1000, value: 5193, currency: "", total_quantity: nil, created_at: "2011-05-25 19:46:03", updated_at: "2011-05-25 19:46:03", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2011-05-11", rule_id: nil, trenche: nil>, #<Sale id: 24, isbn_id: 2, quantity: 1000, value: 4394, currency: "", total_quantity: nil, created_at: "2011-05-26 09:48:16", updated_at: "2011-05-26 09:48:16", customer: "g", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2011-05-10", rule_id: nil, trenche: nil>, #<Sale id: 25, isbn_id: 2, quantity: 1000, value: 4394, currency: "", total_quantity: nil, created_at: "2011-05-26 10:02:38", updated_at: "2011-05-26 10:02:38", customer: "g", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2011-05-05", rule_id: nil, trenche: nil>, #<Sale id: 21, isbn_id: 2, quantity: 1000, value: 5193, currency: "", total_quantity: nil, created_at: "2011-05-25 14:12:45", updated_at: "2011-05-25 14:12:45", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2010-10-15", rule_id: nil, trenche: nil>, #<Sale id: 13, isbn_id: 2, quantity: 50, value: 159, currency: "", total_quantity: nil, created_at: "2011-05-25 12:33:09", updated_at: "2011-05-25 12:33:09", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2010-01-01", rule_id: nil, trenche: nil>, #<Sale id: 14, isbn_id: 2, quantity: 25, value: 129, currency: "", total_quantity: nil, created_at: "2011-05-25 12:33:23", updated_at: "2011-05-25 12:33:23", customer: "", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2010-01-01", rule_id: nil, trenche: nil>, #<Sale id: 12, isbn_id: 2, quantity: 100, value: 415, currency: "", total_quantity: nil, created_at: "2011-05-25 12:32:50", updated_at: "2011-05-25 15:13:21", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2001-10-01", rule_id: nil, trenche: nil>, #<Sale id: 11, isbn_id: 2, quantity: 500, value: 2197, currency: "", total_quantity: nil, created_at: "2011-05-25 12:32:24", updated_at: "2011-05-25 15:11:20", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2000-10-01", rule_id: nil, trenche: nil>], #<Channel id: 2, isbn_id: nil, channel_name: "Export", created_at: "2011-05-16 19:47:35", updated_at: "2011-05-16 19:47:35">=>[#<Sale id: 23, isbn_id: 2, quantity: 2000, value: 5000, currency: "", total_quantity: nil, created_at: "2011-05-26 09:16:15", updated_at: "2011-05-26 09:16:15", customer: "v", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2011-05-02", rule_id: nil, trenche: nil>, #<Sale id: 17, isbn_id: 2, quantity: 242, value: 657, currency: "", total_quantity: nil, created_at: "2011-05-25 12:34:24", updated_at: "2011-05-25 12:34:24", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-10-15", rule_id: nil, trenche: nil>, #<Sale id: 18, isbn_id: 2, quantity: 54, value: 194, currency: "", total_quantity: nil, created_at: "2011-05-25 12:34:44", updated_at: "2011-05-25 12:34:44", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-10-15", rule_id: nil, trenche: nil>, #<Sale id: 15, isbn_id: 2, quantity: 135, value: 377, currency: "", total_quantity: nil, created_at: "2011-05-25 12:33:48", updated_at: "2011-05-25 12:33:48", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-09-15", rule_id: nil, trenche: nil>, #<Sale id: 16, isbn_id: 2, quantity: 433, value: 830, currency: "", total_quantity: nil, created_at: "2011-05-25 12:34:06", updated_at: "2011-05-25 12:34:06", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-09-15", rule_id: nil, trenche: nil>]}

Here's the columns in my Sale model:
#  id             :integer         not null, primary key
#  isbn_id        :integer
#  quantity       :integer
#  value          :integer
#  currency       :string(255)
#  total_quantity :integer
#  created_at     :datetime
#  updated_at     :datetime
#  customer       :string(255)
#  retail_price   :integer
#  discount       :decimal(, )
#  channel_id     :integer
#  invoice_date   :date
#  rule_id        :integer

Thanks so much in advance.
UPDATE: final solution.
Really not sure that this counts as 'giving back to the community' as it's comically verbose, not DRY, full of puts which I used to figure out all the bugs, and badly formatted to boot, but heck, I'm a noob at and the very least I can come back here and laugh at myself in a few years when I know what I'm doing. So, here's my final solution, in Sale.rb. Poor overstuffed model. I will refactor this, one day.
before_save :runningtotal
after_commit :refresh

private
  def runningtotal
    # get the latest sale that matches the new sale's isbn and channel id, then rank by invoice date descending, and get the first record:
    lastsale = Sale.where(:isbn_id => self.isbn_id).where(:channel_id => self.channel_id).order("invoice_date DESC").first
    allsales = Sale.where(:isbn_id => self.isbn_id).where(:channel_id => self.channel_id).order("invoice_date DESC")
    # set the total_quantity field in the new sales record to its quantity + the last sale's total.
        if allsales.maximum(:invoice_date).nil?
          puts "runningtotal thinks the max of invoice date in the allsales relation is nil"
          puts "and runningtotal is setting total_quantity on the new sale to be #{self.quantity + (lastsale.try(:total_quantity) || 0)}"
          self.total_quantity = self.quantity + (lastsale.try(:total_quantity) || 0)
          else
            if self.invoice_date < allsales.maximum(:invoice_date)
            puts "the runningtotal method has been skipped because runningtotal thinks the current invoice date is less than the highest invoice date in the allsales relation"
            else
              puts "this is a normal entry so runningtotal has set the total quantity to be #{self.quantity + (lastsale.try(:total_quantity) || 0) }"
              self.total_quantity = self.quantity + (lastsale.try(:total_quantity) || 0)
            end
        end
  end

  def refresh
     allsales = Sale.where(:isbn_id => self.isbn_id).where(:channel_id => self.channel_id).order("invoice_date ASC")
       #if the runningtotal callback hasn't run, the total quantity will be nil, and nil triggers this after_commit callback
       if total_quantity.nil?
         puts "running refresh callback"
         puts "here's a sample parameter pass: id: #{id} quantity: #{quantity} date: #{invoice_date} "
         puts "allsales class is #{allsales.class}"
         # if the new sale that's being saved has a date that's before any previous sale...
            puts "before the if, refresh thinks that the earliest invoice date is #{allsales.minimum(:invoice_date)} and that invoice date is #{invoice_date}"
            if invoice_date <= allsales.minimum(:invoice_date)
              puts "date earlier than existing sales dates"
              puts "refresh thinks that the earliest invoice date is #{allsales.minimum(:invoice_date)} and that invoice date is #{invoice_date}"
              #... then set its total_quantity to the sale quantity...

                update_attribute(:total_quantity, quantity)
                puts "total_qty updated with qty"
                # ... and update all subsequent records' total_quantity (skipping the before_save callback which would trigger an infinite loop).
                  allsales.each_with_index do |sale, i|
                    previous_sale = allsales[i-1] unless i==0
                    next unless previous_sale
                     puts "getting qty out of arel when date earlier than others: #{previous_sale.quantity}"
                     puts "this is adding #{quantity} to #{previous_sale.quantity } which is #{quantity + previous_sale.total_quantity }"
                 Sale.skip_callback(:save, :before, :runningtotal )
                    sale.update_attribute(:total_quantity, (sale.quantity + previous_sale.total_quantity ))
                 Sale.set_callback(:save, :before, :runningtotal)
                 end
            else
              # if the invoice date is within the min and max range of the previous sales...
                # ... update all previous and subsequent records' total_quantity (skipping the before_save callback which would trigger an infinite loop).
                  allsales.each_with_index do |sale, i|
                    previous_sale = allsales[i-1] unless i==0
                    next unless previous_sale
                    puts "getting qty out of arel within existing date range: #{previous_sale.quantity}"
                    puts "this is adding #{quantity} to #{previous_sale.quantity } which is #{quantity + previous_sale.total_quantity }"
                Sale.skip_callback(:save, :before, :runningtotal )
                    sale.update_attribute(:total_quantity, (sale.quantity + previous_sale.total_quantity ))
                Sale.set_callback(:save, :before, :runningtotal )
                  end
        end
      end
  end

A: Yes, using before_save in the model will run that every time it is saved, whether new or updated.  Thus you need to watch out in calculations the expect the current (new) record to not exist yet. ;)  You might want to use before_save, :on => :create to limit it to the creation action.
However, if I understand your english statement of the problem, your code is rather convoluted.  I don't even see where @isbn is set, that could be dangerous...
Does this need to update the total on other objects this isbn and channel? Usually it's better form to simply calculate that as needed rather than trying to cache the total in every record.
within the callback, self is the current (new?) record, so use it to refer to new values.

  @sale = Sale.order("invoice_date ASC")
  @lastbal = @sale.find_all_by_isbn_id(@isbn).group_by(&:channel)

can be replaced by this, I think:

 @lastbal = Sale.order("invoice_date ASC").where(:isbn_id => self.isbn_id).group_by(&:channel)

I'm assuming that @isbn is actually the new record's isbn.
From there, I'm not sure if you are only intending to update the new record or the old ones... If you want to update the current record, just set the attribute and exit the callback, and it will be saved when the rest is saved:
self.total_quantity = previous_sale.quantity + self.quantity
If you are intending to update the other objects too, then we have to update those objects and save them. I don't see that happening at all here in your code.
Your code goes through several loops, possibly hitting the write_attribute several times... that doesn't make sense.
If you mean you want to find the last record that matches the current isbn and channel to update the new record, here's what I would do:

def runningtotal
  lastsale = Sale.where(:isbn_id => self.isbn_id).
                  where(:channel_id => self.channel_id).
                  order("invoice_date DESC").first
             # that should be the latest sale that matches
             # the current isbn and channel
  self.total_quantity = self.quantity + (lastsale.try(:total_quantity) || 0)
      # watch out for nil if no previous record exists ^
end

`


text:
Q: Getting 64-bit CPUID sample code to compile in VS2008 I'm trying to get some c & ASM sample code I found running in Visual Studio 2008.  I don't think the problem is the difference between VS 2005-2008.  This example is supposed to get the CPUID on 64-bit systems.  (My attempts getting the ASM-only 32-bit examples to compile failed too)
I can copy and paste this code into a new project, but I have not been able to build it.  I've tried a few different VS project templates with no success.  I believe I followed the instructions all the way.  Can someone provide a step-by-step to get this running in Visual Studio 2008 with the project template and project settings?
One thing I've noticed is that although I can make the environment be 64-bit, I can't seem to target x64 for this project - the only options for adding new platforms are mobile platforms.  And I've had to manually define _M_X64 in the command-line options, which I suspect I shouldn't have to do.
Not to be debugged directly, but just for your info - Errors, as far as I got, are as follows:
1> Assembling: .\cpuid64.asm
1>.\cpuid64.asm(4) : error A2013:.MODEL must precede this directive
1>.\cpuid64.asm(5) : error A2034:must be in segment block
1>.\cpuid64.asm(7) : error A2034:must be in segment block : cpuid64
1>.\cpuid64.asm(11) : error A2034:must be in segment block
1>.\cpuid64.asm(12) : error A2008:syntax error : .
1>.\cpuid64.asm(13) : error A2034:must be in segment block
1>.\cpuid64.asm(14) : error A2008:syntax error : .
1>.\cpuid64.asm(15) : error A2008:syntax error : .
1>.\cpuid64.asm(17) : error A2034:must be in segment block
1>.\cpuid64.asm(18) : error A2085:instruction or register not accepted in current CPU mode
1>.\cpuid64.asm(19) : error A2085:instruction or register not accepted in current CPU mode
1>.\cpuid64.asm(20) : error A2085:instruction or register not accepted in current CPU mode
1>.\cpuid64.asm(21) : error A2085:instruction or register not accepted in current CPU mode
1>.\cpuid64.asm(22) : error A2085:instruction or register not accepted in current CPU mode
1>.\cpuid64.asm(23) : error A2085:instruction or register not accepted in current CPU mode
1>.\cpuid64.asm(24) : error A2085:instruction or register not accepted in current CPU mode
1>.\cpuid64.asm(26) : error A2034:must be in segment block
1>.\cpuid64.asm(27) : error A2034:must be in segment block
1>.\cpuid64.asm(29) : error A2034:must be in segment block
1>.\cpuid64.asm(30) : error A2034:must be in segment block
1>.\cpuid64.asm(31) : fatal error A1010:unmatched block nesting : cpuid64

A: Well, if you can't target x64, you have a slight problem because you're not using the x64 toolchain. I strongly suggest you use the VS install wizard to add in the x64 tools. You should be able to go to new platform, call it x64 and base it on win32.
Having said that, I actually recommend using YASM because it allows you to integrate with VS, and YASM is by far a nicer assembler than Microsoft's.
Since I happen to have a project that would benefit from this anyway, I thought I'd do it using yasm:
gcpuid.asm:
; CPUID on x64-Win32
; Ref:

section .code
global gcpuid

; void cpuid(uint32_t* cpuinfo, char* vendorstr);

gcpuid:

    push rbp
    mov  rbp, rsp

    mov  r8, rcx   ; capture the first and second arguments into 1-> r8, 2-> r9
    mov  r9, rdx   ; cause cpuid will obliterate the lower half of those regs

    ; retrive the vendor string in its
    ; three parts
    mov eax, 0
    cpuid
    mov [r9+0], ebx
    mov [r9+4], edx
    mov [r9+8], ecx

    ; retrieve the cpu bit string that tells us
    ; all sorts of juicy things
    mov eax, 1
    cpuid
    mov [r8], eax
    mov eax, 0

    leave
    ret

cpuid-w32.c:
#include <stdio.h>
#include <stdint.h>

void gcpuid(uint32_t* cpuinfo, char* vendorstr);

int main(int argc, char** argv)
{
    char vendor[13] = { 0 };
    uint32_t flags;

    gcpuid(&flags, vendor);
    printf("Flags: %u, Vendor: %s\n", flags, vendor);

    return 0;
}

Following readme.txt in the vs2010 archive supplied on the links download page, it was a doddle to get vs to assemble this, and this solution is much clearer, I think, than intels.
As to what you do with the cpuinfo parameter, well, you can try various masks to find out all sorts of info about the cpu type. I might update if I finish the implementation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Objective C question: method won't return a string This is my first question so please forgive me if it's obvious.  I learned to program in Pascal a few years ago, so my terminology may be off.  I've looked at a bunch of postings, but nothing seems to address my basic problem.
I have a lookup table that I use to convert decimals back into fractions.  I am calling this method...
-(void) convertToFractions:(float *)float2 aString:(NSMutableString *) myString;

...with this..
[self convertToFractions:&float1 aString:outputFraction];

The idea is that float2 is the decimal that I pass to the method, and myString is the fraction returning.
This runs after the lookup:
myString = [NSString stringWithString:[[decimalInchArray objectAtIndex:x]objectAtIndex:1]];
NSLog(@"myString = %@",myString);

The log shows myString is the correct fraction i.e. myString is correctly displaying the fraction I want to return, but outputFraction is null.
I think it's a pointer issue.  I tried *myString, but the compiler throws an error (incompatible types).
Any suggestions are really appreciated.

A: You want to change the output of your convertToFractions method from void to NSString.
It's returning null because the return type of your method, is void, so it returns nothing.
The return type of an Objective-C method is in the parenthesis, at the beginning of the method name.
Here,s an example, but I don't see where you define convertToString so, I'll use pseudocode.
- (NSString *) convertToFractions:(float *)float2{
  NSString *fraction = *some code to lookup fraction from table;*
  return fraction;
}

myString = [self convertToFractions:(float *)float2];

EDIT:
As others have suggested, you should give Objective-C a fresh look. I suggest you read this Objective-C Primer written by Apple.

A: Where do you define your outputFraction? Nowhere in the code above you mention it.
At a guess your conversion method is declared as (void) meaning it will not return anything. If you need it to return the result as a NSString declare it like
-(NSString*) convertToFractions:(float *)float2 aString:(NSMutableString *) myString;

And make sure you return an NSString before reaching the end of the method with
return MyNSStringVariable;

[EDIT]
I can see you are hoping that outputFraction will be returned by your method but that is not the case with Objective-C (not sure about Pascal). You are simply passing outputFraction as a second variable in your method.
So the "right" way of doing it would be to have a method
-(NSString*)convertToFraction:(float*)float2 {
     ...// Do your float to fraction calculation here
     ...// Make sure fraction is formatted as NSString
     return YourFractionVariable;
}

Then you can assign the return value to a variable of your choice, for instance:
NSString *fraction = [self converToFraction:aFloatNumber];
NSLog (@"fraction is %@", fraction);

Cheers,
Rog

A: Why not just return the string?
- (NSString*)convertToFractions:(float)float {
    //Bla bla do everything
    return [myString autorelease]; //Autorelease is for memory-management
}

Btw: You seriously need to read into ObjC. Please don't try to use your old pascal-knowledge on ObjC. It's different, and your knowledge isn't really applicable.
I would recommend buying a book about ObjC or reading some good tutorials for it. (Apple itself has some very good ones)

A: If you don't want to return NSString from your method as others suggested you can pass a pointer to NSString pointer to your function (the same way you pass NSError** to some standard api callsm e.g. in NSFileManager methods). Your code will look something like:
NSString *outputFraction;
[self convertToFractions:&float1 aString:&outputFraction];

-(void) convertToFractions:(float *)float2 aString:(NSMutableString **) myString{
  ...
   if (myString)
      *myString = [NSString stringWithString:[[decimalInchArray objectAtIndex:x]objectAtIndex:1]];
}


text:
Q: Using a delegate twice inside of a unit test I have some unit tests where I'm using the DoesNotThrow feature of Nunit.  Up until recently, I wasn't concerned w/ the actual response coming back.  However, I recently needed to add a check for the count on my result set.  I now have a redundant call in my code.  Can I clean this up and make use of the delegate within my second Assert call?
Assert.DoesNotThrow(() => new GetMyCollection.GetCollection(request));

var response = new GetMyCollection().GetCollection(request);
Assert.Greater(response.MyCount, 0);

A: Just get rid of the first line entirely:
var response = new GetMyCollection().GetCollection(request);
Assert.Greater(response.MyCount, 0);

If new GetMyCollection().GetCollection(request) throws an exception, that will make the test fail anyway.
Assert.DoesNotThrow is relatively pointless, IMO - I would only usually use it to contrast with some Assert.Throws calls.


text:
Q: Rounded corner rectangle coordinate representation Simple rounded corner rectangle code in Matlab can be written as follows.
rectangle('Position',[0,-1.37/2,3.75,1.37],...
      'Curvature',[1],...
     'LineWidth',1,'LineStyle','-')
daspect([1,1,1])

How to get the x and y coordinates arrays of this figure?

A: To get the axes units boundaries, do:
axisUnits = axis(axesHandle) % axesHandle could be gca

axisUnits will be an four elements array, with the following syntax: [xlowlim xhighlim ylowlim yhighlim], it will also contain the zlow and zhigh for 3-D plots.
But I think that is not what you need to know. Checking the matlab documentation for the rectangle properties, we find:

Position four-element vector [x,y,width,height]
Location and size of rectangle. Specifies the location and size of the
  rectangle in the data units of the axes. The point defined by x, y
  specifies one corner of the rectangle, and width and height define the
  size in units along the x- and y-axes respectively.

It is also documented on the rectangle documentation:

rectangle('Position',[x,y,w,h]) draws the rectangle from the point x,y
  and having a width of w and a height of h. Specify values in axes data
  units.

See if this illustrate what you want. You have an x axis that goes from −100 to 100 and y axis that goes from 5 to 15.  Suppose you want to put a rectangle from −30 to −20 in x and 8 to 10 in y.
rectangle('Position',[-30,8,10,2]);

A: As explained by the comments there appears to be no direct way to query the figure created by rectangle and extract x/y coordinates. On the other hand, I can think of two simple strategies to arrive at coordinates that will closely reproduce the curve generated with rectangle:
(1) Save the figure as an image (say .png) and process the image to extract points corresponding to the curve. Some degree of massaging is necessary but this is relatively straightforward if blunt and I expect the code to be somewhat slow at execution compared to getting data from an axes object.
(2) Write your own code to draw a rectangle with curved edges. While recreating precisely what matlab draws may not be so simple, you may be satisfied with your own version.
Whether you choose one of these approaches boils down to (a) what speed of execution you consider acceptable (b) how closely you need to replicate what rectangle draws on screen (c) whether you have image processing routines, say for reading an image file.
Edit
If you have the image processing toolbox you can arrive at a set of points representing the rectangle as follows:
h=rectangle('Position',[0,-1.37/2,3.75,1.37],...
      'Curvature',[1],...
     'LineWidth',1,'LineStyle','-')
daspect([1,1,1])
axis off
saveas(gca,'test.png');
im = imread('test.png');
im = rgb2gray(im);
figure, imshow(im)

Note that you will still need to apply a threshold to pick the relevant points from the image and then transform the coordinate system and rearrange the points in order to display properly as a connected set. You'll probably also want to tinker with resolution of the initial image file or apply image processing functions to get a smooth curve.


text:
Q: What to do when fetching/creating a cache thats empty? Memcached, Rails 3 So right now users have a list of items that changes, but not too often, so I decided to keep it in a cache like so:
  #Fetch the cache
  def self.fetch_cache(user)
    Rails.cache.fetch(user.items, :expires_in => 15.minutes) do
      user.items.order("created_at ASC").all
    end
  end

This works if the user has items. The problem is, if the user doesn't have any items (because they're a new user or something) and the cache will return an error.
How should I be using this to make it work for users with nothing?
Thanks!

A: You're using a really weird cache key there (the first argument to Rails.cache.fetch). You're supposed to be passing a string that identifies the cache entry but you're passing in an association.
Rails is probably helpfully calling to_s on user.items in order to turn it into a string that but that's not a useful cache key as you're going to have to load the user's items in order to compute the cache key to get the users' items from the cache!
Something like "user_#{user.id}_items" would be a far better cache key.


text:
Q: How to pack rectangles of given areas into one large rectangle I am writing an application in Perl, but I don't necessarily need code, just an algorithm I can Implement.
I want to represent space allocation of a database system as a number of rectangles packed into one large rectangle (size to fill the monitor). So I know the total area I have to work with, how many pieces I want to divide it into and how big each of those pieces should be.
What I need is a way to lay the individual rectangles out on the big window, correctly sized so they cover the correct area, and packed to cover the entire big window.
This is somewhat reminiscent of bin packing, but differs because I know the area I want each piece to be but I can choose the dimensions (as long as they give the correct area) to fit into the big window.
I hope this is clear enough and I hope someone has run into this before.
Thanks.


text:
Q: Where in the literature does the anticyclotomic $\mathbf{Z}_p$-extension of an imaginary quadratic field first appear? If $K$ is an imaginary quadratic field, then the $\mathbf{Z}_p$-rank of $K$ is $2$, meaning that the Galois group of the compositum of all the $\mathbf{Z}_p$-extensions of $K$ in an algebraic closure $\overline{K}$ is isomorphic to $\mathbf{Z}_p^2$. It is known that the compositum is generated by two special $\mathbf{Z}_p$-extensions: the cyclotomic and the anticyclotomic $\mathbf{Z}_p$-extensions.
Both are Galois over $\mathbf{Q}$ (I believe they are the only $\mathbf{Z}_p$-extensions of $K$ which are Galois over $\mathbf{Q}$). The cyclotomic extension is abelian over $\mathbf{Q}$ and is equal to the compositum of $K$ and the cyclotomic (the only!) $\mathbf{Z}_p$-extension of $\mathbf{Q}$. The anticyclotomic extension is "generalized dihedral" over $\mathbf{Q}$, which means that the unique non-trivial element of $\mathrm{Gal}(K/\mathbf{Q})$ acts on $\mathrm{Gal}(K_\infty^{anti}/K)$ by inversion.
I learned these facts from various sources, after being told by my advisor what the anticyclotomic $\mathbf{Z}_p$-extension was (she gave me the generalized dihedral definition). My question is: when did $K_\infty^{anti}$ first appear in the Iwasawa theory literature? Does it appear in the work of Iwasawa (I'm not all that familiar with his work)? Maybe the work of Greenberg or Washington? Was the primary motivation for studying it the connection with CM elliptic curves?
My motivation for asking this is because I'd really like to read a comprehensive exposition of its basic properties (although perhaps this doesn't exist). I've picked up bits and pieces from books and papers. For example, I know that $K_\infty^{anti}$ is the unique $\mathbf{Z}_p$-extension contained in the union of the $p$-power conductor ring class fields of $K$, and the behavior of primes in these class fields can be determined by the ideal-theoretic formulation of global class field theory, but I feel like the basics are not quite as straightforward as for cyclotomic $\mathbf{Z}_p$-extensions (which somehow seem more natural to me).

A: First time I heard  about antycyclotomic $\Gamma$-extensions  in 1972 from  Pavel Kurchanov, in connection with his paper
http://www.mathnet.ru/php/archive.phtml?wshow=paper&jrnid=sm&paperid=3020&option_lang=eng
Actually, his goal was to construct elliptic curves of infinite rank over $\Gamma$-extensions. (According to Mazur's conjecture, one cannot do it over the cyclotomic extensions.)


text:
Q: Position DIV 25px from top of page? I have a div that is created as :

it's horizontal position is fine, but I want to drop is 25px (possibly more) from the top of the page.
I've tried adding top:25px; to the style and adding the test class css but it hasn't helped.
div.test{
    color:black;
    text-align:center;
    border-radius:5px;
    -moz-border-radius:5px;
    border:1px solid #FFF;
    background-color:#434987;
}

I do have another div on the page that is using position:absolute; and I can put that where I want... but I can't get that to work with this div when I'm using margin:0 auto to align it centrally horizontally..
Can anyone offer some advice how I do this ?
Thanks

A: You can apply multiple margin CSS rules:
margin: 0 auto; margin-top: 25px

top (left, right and bottom as well) only work on certain positioned elements (absolute, fixed, static). Here is a good video about CSS positioning
Working example: http://jsfiddle.net/ZFpRN/


text:
Q: Char match that is not exact still works I am sorry to post again so soon, but I ran into another error in my Tax program. My program is only supposed to work if someone enters only 's,' 'S,' 'm,' 'M,' 'c,' or 'C' for the marital status. When I entered anything that does not start with one of those letters, it prints Invalid Entry, like it is supposed to, but when I enter something that starts with an upper/lowercase s, m, or c, it proceeds as if I only entered that first letter. How do I make it so that the program only proceeds if you enter the one letter?
Thanks!!
Here is my code:
import java.util.Scanner;

public class TaxPrep
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        char maritalStatus;
        double grossIncome = 0;
        double numberOfExemptions = 0;
        double taxRate = 0;
        double taxableIncome = 0;
        double taxesOwed = 0;
        String anotherCustomer = "y";

        System.out.print("A A R O N ' S  T A X  P R E P A R E R\n\n");

        do{
            System.out.print("Are you (s)ingle, (m)arried, or (c)ohabiting?\n");
            System.out.print("Enter s, m, or c ==> ");
            maritalStatus = sc.next().charAt(0);
            switch (maritalStatus)
            {
                case 's': case 'S':
                    System.out.print("Gross income ==> ");
                    grossIncome = sc.nextDouble();
                    System.out.print("Number of exemptions ==> ");
                    numberOfExemptions = sc.nextInt();
                    taxableIncome = grossIncome - (1000 * numberOfExemptions);
                    taxRate = 20;
                    break;
                case 'm': case 'M':
                    System.out.print("Gross income ==> ");
                    grossIncome = sc.nextDouble();
                    System.out.print("Number of exemptions ==> ");
                    numberOfExemptions = sc.nextInt();
                    taxableIncome = grossIncome - (1000 * numberOfExemptions);
                    taxRate = 25;
                    break;
                case 'c': case 'C': //tax rate for cohabiting depends on taxable income
                    System.out.print("Gross income ==> ");
                    grossIncome = sc.nextDouble();
                    System.out.print("Number of exemptions ==> ");
                    numberOfExemptions = sc.nextInt();
                    taxableIncome = grossIncome - (1000 * numberOfExemptions);
                    if (taxableIncome <= 20_000)
                    {
                        taxRate = 10;
                        break;
                    }
                    else if (taxableIncome <= 50_000)
                    {
                        taxRate = 15;
                        break;
                    }
                    else
                    {
                        taxRate = 30;
                        break;
                    }
                default: //if input for marital status is invalid
                    System.out.print("\nInvalid entry.\n");
                    continue;
            }

            taxesOwed = taxableIncome * (taxRate / 100);

            //taxable income and taxes owed cannot be negative
            if (taxableIncome < 0)
            {
                taxableIncome = 0;
            }
            if (taxesOwed < 0)
            {
                taxesOwed = 0;
            }

            //tax summary
            System.out.print("\nINCOME TAX SUMMARY");
            System.out.print("\ntax rate: " + taxRate + "%");
            System.out.print("\ntaxable income: $" + taxableIncome);
            System.out.print("\ntaxes owed: $" + taxesOwed);

            //would you like to process another customer?
            System.out.print("\n\nProcess another customer? (y/n): ");
            anotherCustomer = sc.next();
            System.out.print("\n");
        } while (anotherCustomer.equalsIgnoreCase("y")); //as long as user enters 'y' or 'Y', the program will continue to calculate the income tax summary
    }
}

A: You are testing only the first character, even if the entered word is longer:
maritalStatus = sc.next().charAt(0);

sc.next() returns a String, and charAt(0) returns just its first character. So if you entered "sFoo", maritalStatus would just be 's' and the "Foo" would be ignored.
You should get the whole entered String (and possibly convert it to upper case for easier comparison in the switch). The variable maritalStatus should be declared as String in this case:
maritalStatus = sc.next().toUpperCase();

switch (maritalStatus) {
case "S":
    //...
}

Switch statement works with Strings, unless you are using Java 6 or older. In that case you would use:
maritalStatus = sc.next().toUpperCase();

if (maritalStatus.equals("S")) {
    //...
} else if...


text:
Q: failed to load chats in real time I have created a basic chat application.
it shows the no. of users when u r logged in and u can chat to any of them .
but the problemm is that newly added chats to receiver is not displaying but its added in mysql and also displaying the messages in the sender's side.
plz help me with this....

<?php
session_start();
?>

           <title>Live Table Data Edit</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

You Are : <?php echo $_SESSION['name']; ?>

              <textarea id="text" name="text"></textarea>
              <input type="submit" id="sub" name="sub" value="Send" />


text:
Q: Update Class Based Off of Neighbor Class ID This probably has an answer somewhere, but I am having difficulty formulating a question.  I have a situation that hopefully someone can answer quickly.

    content 1
    content 2

This is an simplified example of code I am using for a button (widget) for a website.  I need to be able to edit the inner HTML of the second span tag.  The problem is this code is implemented more than once, so I cannot use the class to change the text; I have to use the ID of the first span to make sure I only update the link I want to update.
I would like to do this using jQuery, but I can't seem to find a good place to start.  Essentially, it can be broken down to:
// where a link contains the ID of the span I need
    // update the HTML of the second span like:
    $("span.span-2").html("UPDATED");

Regards.

A: $('#unique_id1').next('span')

?


text:
Q: Display days, hours, minutes in between 2 dates in java I need to display a countdown timer between a specified date in the future and now in the format Days:Hours:Minutes.
So for example the end date is 4th december 1:30 PM 2013 and right now it is 3rd december 12:30 PM 2013, my textView (or any other view) should show "Time remaning 1 day: 1 hours: 0 minutes"
I do not want to use joda-time library as it increases my applications size by about 4.1 MB and I need to use the date/time feature only once in my application.
I am using the calendar API provided by java and I cannot implement this 'timer'/'countdown timer' functionality
Any idea how I should implement this?
Edit: my application will only be used in 1 time zone ie. EST, so I do not have to worry about time zone correction
Edit: What I have tried so far, get the months of the 2 calendar
cal1.get(Calendar.MONTH); //to get the month
cal2.get(Calendar.MONTH);

cal1.get(Calendar.DAY_OF_MONTH);  //to get the day
cal2.get(Calendar.DAY_OF_MONTH);

cal1.get(Calendar.HOUR_OF_DAY);  //to get the hour in 24 hours
cal2.get(Calendar.HOUR_OF_DAY);

cal1.get(Calendar.MINUTE); //to get the minutes
cal2.get(Calendar.MINUTE);

cal1.get(Calendar.SECOND);  //to get seconds
cal2.get(Calendar.SECOND);

now I subtract the months, if it is 0 then I know that the difference is less than 1 month, similarly I subtract days, hours, minutes. However that doesnt give me an accurate result. Example - today 6th July 4 AM 2013, end date 7th July 3 AM 2013, according to my algorithm it will say time left is 1 day and -1 hours and I run a timer to execute this task every second
I need a better algorithm and a better way to display it, I am doing this same task again and again on the UI thread which may cause lag I feel

A: I guess you have two java.util.Date objects to compare. First you wanna have some kind of timer that gets executed every N seconds. Handler.postDelayed() works just fine for that. Every time it executes, you use timeMs = futureDate.getTime() - System.currentTimeMillis(). This gives you the time difference in milli seconds. Then you only need to convert this to the desired format: e.g. seconds = timeMs / 1000 % 60.


text:
Q: Как узнать номер последней строки в текстовом файле? Скажите, пожалуйста.
A: $array = file('file.txt');
echo count($array);
/*-------------------------------------------*/

$str = file_get_contents('file.txt');
echo substr_count($str "\n");

/*-------------------------------------------*/

$h = fopen('r','file.txt');
$count = 0;
while (!feof($h)) {
    fgets($h);
    $count++;
}
echo $count;

/*-------------------------------------------*/

trim(exec("wc -l file.txt"));


text:
Q: Generate AppxManifest from template file with command line for automated builds We're preparing an app to be deployed for the Windows Store, using the desktop bridge.
Using the "Project -> Deploy" option from within the IDE will use an AppxManifest.template.xml to generate the AppxManifest.xml, replacing some variables with the current settings from the project.

[UWP] Generating manifest: .\Bin\AppxManifest.xml

Is there any way to trigger this build step without using the IDE, so one may use it for automated builds?

A: The Desktop Bridge itself has not provide such a tool for you to do such things. But if you check Desktop to UWP Bridge: Manual Conversion documentation, you will see a minimun manifest template file.
Then if use the Desktop App Converter (DAC) to convert your app, you will need to type some parameters. For example, "Publisher", "Version" etc. After you input these parameters, the DAC tools will help you fill these values into manifest file. If you download the DesktopAppConverter.zip from here. You will find that actually there are many PowerShell script files, the DAC integrate these files. When you input the parameters, it will automatically help you call the specific PowerShell script to do some operations. You could see DesktopAppConverter\manifest\ folder, there should be some script files which is used to generate manifest file.
So, for your requirement, you would have to manually do these things, you could make a tool (by using any programming language) to compare your AppxManifest.template.xml with the standard manifest file and fill the specific values. You also could make a PowerShell script, if you're familiar with PowerShell, you can do it.


text:
Q: Render equation to .png file using Python I want to render equations to PNG files and embed them in the HTML documentation of my library. I am already using pylab (matplotlib) in other projects.
I have not found any clues in http://matplotlib.sourceforge.net/users/usetex.html and http://matplotlib.sourceforge.net/users/mathtext.html
When I do
plt.title(r'$\alpha > \beta$')
plt.show()

I get a titled empty figure with axes.
Update:
After doing some research I found, that the easiest way of rendering LaTeX to png is using mathext ( http://code.google.com/p/mathtex/ ).
Suprisingly, I had all requiered libraries to build it from source.
Anyway, thanks to everyone for replies.
Update 2:
I did some testing of mathtex and found it does not support matrices (\begin{pmatrix}) and some other things I need.
So, I'm going to install LaTex (MikTeX).
Update 3:
I installed proTeXt. It's huge, but easy-to-use and fast. IMHO, for now it's the only way of rendering equations.

A: This worked for me:
# https://gist.github.com/tonyseek/95c90638cf43a87e723b

from cStringIO import StringIO

import matplotlib.pyplot as plt

def render_latex(formula, fontsize=12, dpi=300, format_='svg'):
    """Renders LaTeX formula into image.
    """
    fig = plt.figure(figsize=(0.01, 0.01))
    fig.text(0, 0, u'${}$'.format(formula), fontsize=fontsize)
    buffer_ = StringIO()
    fig.savefig(buffer_, dpi=dpi, transparent=True, format=format_, bbox_inches='tight', pad_inches=0.0)
    plt.close(fig)
    return buffer_.getvalue()

if __name__ == '__main__':
    image_bytes = render_latex(
        r'\theta=\theta+C(1+\theta-\beta)\sqrt{1-\theta}succ_mul',
        fontsize=10, dpi=200, format_='png')
    with open('formula.png', 'wb') as image_file:
        image_file.write(image_bytes)

A: *

*(source) If you are using IPython interpreter, it renders all single matplotlib step into a figure window by default.
Thus, plt.title(r'$\alpha > \beta$') in IPython would immediately create a figure even before calling .show(). On the other hand, using terminal/cmd/IDLE won't.

*plt.show() would create a figure window whether you're using IPython or not, you want to change that line to:
plt.savefig('filename.png')

Edit:
Okay, I misunderstood your question. As @Li-aung Yip said, you may want to use Sympy for pure equation image. We can still do some trick in matplotlib to achieve what you want though (you may need to readjust or resize accordingly):
import matplotlib.pyplot as plt

#add text
plt.text(0.01, 0.8, r'$\alpha > \beta$',fontsize=50)

#hide axes
fig = plt.gca()
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.draw() #or savefig

This is done by hiding axes ticks and adding text inside the plot figure.
But...this doesn't really "not drawing" a figure :\ Though you can post-process such as cropping the image with PIL.

A: It sounds like you want to render LaTeX equations to images. See linked question for a variety of ways of doing this with minimal dependencies. (Some even involve matplotlib, I believe.)
Alternately, if you can install LaTeX or rely on LaTeX being installed, you can just use LaTeX itself to render the equation to postscript and thence into an image format.

A: I fiddled with @warvariuc's answer for a long time in Python 3 and came up with the following solution. It is very similar but has a couple of key differences. First, StringIO and cStringIO are not modules in Py3. Secondly, the equivalent class io.StringIO does not work with at least some versions of MatPlotLib. See this thread: http://matplotlib.1069221.n5.nabble.com/savefig-and-StringIO-error-on-Python3-td44241.html. Basically, the image is binary, so you need to use io.BytesIO. The getvalue() method works just as with StringIO. I took the liberty of using savefig to do the file opening, since it can decide whether you passed in a file name or not for itself:
from io import BytesIO
import matplotlib.pyplot as plt

def renderLatex(formula, fontsize=12, dpi=300, format='svg', file=None):
    """Renders LaTeX formula into image or prints to file.
    """
    fig = plt.figure(figsize=(0.01, 0.01))
    fig.text(0, 0, u'${}$'.format(formula), fontsize=fontsize)

    output = BytesIO() if file is None else file
    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', category=MathTextWarning)
        fig.savefig(output, dpi=dpi, transparent=True, format=format,
                    bbox_inches='tight', pad_inches=0.0, frameon=False)

    plt.close(fig)

    if file is None:
        output.seek(0)
        return output

The warning was something that I am pretty sure is related to the figure size. You can remove the enclosing with entirely if you would like. The reason for the seek is to make the "file" readable (best explained here: https://stackoverflow.com/a/8598881/2988730).


text:
Q: Having user input variables to be used in a later equation I am writing a program to calculate the mass of a given molecule. I have defined every element as an integer. I need to be able to type in a chemical formula like NaCl and have it print out the sum of the atomic masses of Na and Cl. So far I have things set up so that I can type in a chemical formula and it turns it into a list of elements, so if I typed in NaCl it would give me ['Na', 'Cl']. Here is the code:
import re
Na = 22.99
Cl = 35.45
input = raw_input()
inputList = (re.findall('[A-Z][^A-Z]*', input))

Firstly I need to know how to tell the computer I am inputting variables that I previously defined, not strings. Then I want to make it assign each item from the list to its own variable. Something like
e1 = Na
e2 = Cl

My main issue is that at the moment my input is treated as a string.

A: I believe what you want is a dictionary, like so:
atomic_wt = {'Na':22.99, 'Cl':35.45}

Later, when you have your inputs, you can access them in a loop:
for element in inputList:
    elem_wt = atomic_wt[element]

A: Use the sum() and map() functions to add up the appropriate values from a dictionary:
>>> elements = {'Na':22.99, 'Cl':35.45}
>>> result = ['Na', 'Cl']
>>> answer = sum(map(elements.get, result))
>>> answer
58.44

A: Using a dictionary, you can easily take string input and handle it:
elements = { 'Na': 22.99,
             'Cl': 35.45
           }  # You can extend this dictionary to include more elements

print elements.get(raw_input('Enter an element symbol:   ', 'invalid'))
"""
use the .get method to return a placeholder value,
representing that the *input* value doesn't exist in the dictionar
"""


text:
Q: How to concat XML tags in XSLT-1.0? I tried to process an XML file with this XSLT-1.0 file.
I would like to concat all of the <pr> tags in the same cell of the table.
Here is my XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<cours>
    <sigle>GEN1051</sigle>
    <titre>Ingénierie et entreprises II</titre>
    <prgs>
        <pr>4108</pr>
        <pr>7643</pr>
        <pr>7833</pr>
    </prgs>
    <credits>3</credits>
</cours>

I tried it with the function xsl:choose and fn:concat, but of course, this didn't work, because that makes three empty cells instead of one cell with my 3 values of <pr> tags.
This is a part of my XSLT:
<xsl:for-each select="prgs/pr">
    <xsl:choose>
        <xsl:when test="pr = 1">

                <xsl:value-of select="."/>

            <xsl:otherwise>

                    <xsl:value-of select='concat(pr, pr)'/>

            </xsl:otherwise>
        </xsl:when>
    </xsl:choose>
</xsl:for-each>

Who knows a better solution to this problem?

A: You can use the following XSLT-1.0 stylesheet:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="prgs">
        <xsl:copy>

                <xsl:for-each select="pr">
                    <xsl:value-of select="." />
                </xsl:for-each>

        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Its output is:
<?xml version="1.0"?>
<cours>
    <sigle>GEN1051</sigle>
    <titre>Ingénierie et entreprises II</titre>
    <prgs>
        410876437833
    </prgs>
    <credits>3</credits>
</cours>

It concatenates the values of all three <pr> elements in one  element.
If you want to separate your <pr> values, just put a
<xsl:if test="position() != last()"><xsl:text> - </xsl:text></xsl:if>

after the <xsl:value-of select="." /> in the xsl:for-each loop.

A: If you want to put all three pr values in the same cell, you can do simply:
In XSLT 1.0:

    <xsl:for-each select="prgs/pr">
        <xsl:value-of select="." />
        <xsl:if test="position() != last()">; </xsl:if>
    </xsl:for-each>

In XSLT 2.0:

    <xsl:value-of select="prgs/pr" separator="; "/>

The output of both will be:
4108; 7643; 7833

This is assuming you are in the context of cours (as your snippet indicates).


text:
Q: Convergence of angle between vectors? This problem comes is from Hoffman's Analysis in Euclidean Space.

True or False. Let $\{X_n\}$ be a sequence in $\mathbb{R}^m$. If $\{X_{n}\}$ converges to a (nonzero) vector $X$, does the angle between the vectors $X_n$ and $X$ converge to $0$?
I am assuming it is true. Here is my attempt at a proof.

Proof. Assume that $\{X_{n}\}$ converges to the vector $X$. We know that
$$\cos\theta=\frac{\langle X,X_n\rangle}{|X||X_n|}$$
for some positive integer $n$.
Since
$$\lim\limits_{n\rightarrow\infty}\frac{\langle X,X_n\rangle}{|X||X_n|} =\frac{|X|^2}{|X|^2}=1$$
then $$\theta=\cos^{-1}(1)=0$$

I can't see a reason why the converse statement wouldn't be necessarily true. In other words, if the angle between ${X_{n}}$ and some vector $X$ approaches zero, wouldn't the sequence $\{X_n\}$ converge to $X$?

EDIT: Another thing that popped into my mind. Do these results hold in general for all vector spaces?

A: Your proof is correct.
The converse is not true because the angles do not speak to the norms. The angles may converge to a limit but the vectors do not have to converge due an oscillation in norms.


text:
Q: Meaning of "Cut my legs out from under me"? I would like to know the exact meaning of this phrase "cut my legs out from under me".
I've been searching for it everywhere, but until now I've only come across the definition of "cut the ground from under somebody's feet". And I know it is not the same. Though, I've heard on some TV shows people saying "cut my legs out from under me".

A: Merriam Webster's definition for have one's legs/feet/knees cut out from under (one) is as follows:

be knocked down by something that hits one's legs very hard

*

*When I learned that I was seriously ill, I felt as if my feet were cut out from under me.

often used figuratively.

*

*When the program lost the grant its financial legs had been cut out from under it.

According to MW's popularity index they list it as " Bottom 10% of words"
I can't say I've heard it before. While searching online I saw an equivalent French term "couper l'herbe sous le pied", and also saw more example sentences.
Two of the example sentences quoted below are of Canadian origin.

*

*Organized crime has emerged as the number one threat to Canada's overall security, yet the government has cut the legs out from under Canada's security committee

*"Having a national formulary as a defining component of a national pharmacare program," said Brian Ferguson, "would cut the legs out from under the provinces to make decisions about how they ration across different parts of their programs."
(sources for this quote)

Perhaps it's an expression that has transitioned from French Canadians to English Canadians?
Thinking about this further, I know an expression "to have your legs kicked out from under you" which would basically hold the same meaning as MW's definition above.

A: My Dad used to use the term in a manner with less outward accusation (not blaming another) of "my legs went out from under me", I think he meant it in the sense of being utterly flabbergasted or staggered by what someone says.


text:
Q: Issues when downloading PDF file from MVC application I have created a function where a user can download a pdf file from my webpage. The file is stored in a databse and is requested from a webapi. The return value of the webapi is a byte[].
My issue here is that when i run the web application on my local iis this function runs without any errors. I get the pdf file and it is downloaded correctly on my machine. But when i deploy the web application to my Test server this code generates either RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION in chrome with some of the files where as other files are downloaded to the machine but when i try to open the pdf file i get: could not load the pdf file.
This happens with both chrome and IE.
This is my code:
[HttpGet]
[DoNotChangeCacheSettings]
public virtual FileResult DownloadTranslationFile(Guid id)
{
    Guid assessmentTemplateId = id;
    File translationFile = Services.GetFileContent(assessmentTemplateId);
    var fileName = HttpUtility.UrlPathEncode(translationFile.FileName);
    this.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    var result = File(translationFile.FileContent.Content, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName);
    return result;
}

I have been trying to fix this issue for 2 days now but i simply cant figure out what the issue is. Hope you guys can help. Thanks.

A: You don't need to use Content-Disposition. .Net will add it for you. From the docs.

The fileDownloadName parameter is used to generate the
  content-disposition header. The result object that is prepared by this
  method is written to the response by the ASP.NET MVC framework when
  the object is executed. The MediaTypeNames class can be used to get
  the MIME type for a specific file name extension.

I tend to use the Stream-overload:
[HttpGet]
[DoNotChangeCacheSettings]
public virtual FileResult DownloadTranslationFile(Guid id)
{
    Guid assessmentTemplateId = id;
    File translationFile = Services.GetFileContent(assessmentTemplateId);
    var fileName = HttpUtility.UrlPathEncode(translationFile.FileName);
    var stream =  = new MemoryStream(translationFile.FileContent.Content);
    return File(stream, "application/pdf", fileName);
}

But you can use the byte[] as well:
[HttpGet]
[DoNotChangeCacheSettings]
public virtual FileResult DownloadTranslationFile(Guid id)
{
    Guid assessmentTemplateId = id;
    File translationFile = Services.GetFileContent(assessmentTemplateId);
    var fileName = HttpUtility.UrlPathEncode(translationFile.FileName);
    return File(translationFile.FileContent.Content, "application/pdf", fileName);
}

EDIT:
If you got an error when opening the PDF you can ensure that the web browser is doing the right thing by manually saving the PDF from code as well. If that file has errors as well you're probably generating an incorrect byte[].
[HttpGet]
[DoNotChangeCacheSettings]
public virtual FileResult DownloadTranslationFile(Guid id)
{
    Guid assessmentTemplateId = id;
    File translationFile = Services.GetFileContent(assessmentTemplateId);
    var fileName = HttpUtility.UrlPathEncode(translationFile.FileName);
    var stream =  = new MemoryStream(translationFile.FileContent.Content);

    // Code for debugging
    var tempDir = "C:\\temp"; // Make sure app pool can write here.
    var path = Path.Combine(tempDir, fileName); // Possibly add extension here.
    using (var fileStream = File.Create(path))
    {
        stream.Seek(0, SeekOrigin.Begin);
        stream.CopyTo(fileStream);
    }
    stream.Seek(0, SeekOrigin.Begin);

    // Return to client.
    return File(stream, "application/pdf", fileName);
}


text:
Q: Timer.periodic does not call the callback in flutter ios I have a duration bar and a countdown timer. the duration bar simply displays a linear bar to begin a session and the countdown timer converts time passed vs total time into a percentage so that it can be displayed in a progress bar
my duration bar looks like this.
class DurationBar extends HookWidget {
  const DurationBar({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Expanded(
      flex: 0,
      child: _SessionTimer(),
    );
  }
}

class _SessionTimer extends HookWidget {
  const _SessionTimer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var binah = Provider.of<BinahModel>(context);
    var storage = GetStorage();
    var processingTime = storage.read<int>(Keys.binahProcessingTime);
    final time = processingTime ?? 120;
    final countdown = useCountdownTimer(time, true);

    useEffect(
      () {
        switch (binah.sessionState) {
          case SessionState.measuring:
            countdown.start();
            break;
          default:
            countdown.stop();
            break;
        }
        return null;
      },
      [binah.sessionState],
    );

    useEffect(
      () {
        countdown.label.value = '0';
        return null;
      },
      [binah.sessionType],
    );

    useEffect(() => countdown.stop(), []);
    var percent =
        ((int.parse(countdown.label.value) / time) * 100).toStringAsFixed(1);
    // return Text('Duration: ${countdown.label.value}');
    return LinearPercentIndicator(
      width: MediaQuery.of(context).size.width,
      lineHeight: 40.0,
      barRadius: const Radius.circular(100),
      percent: int.parse(countdown.label.value) / time,
      backgroundColor: kBaseThemeColor300,
      progressColor: Colors.blueAccent,
      center: Center(
        child: Text(
          '$percent %',
          style: Theme.of(context).textTheme.headline4!.copyWith(
                color: kDarkIconColor,
              ),
        ),
      ),
    );
  }
}

and my countdown timer (with method useCountdownTimer) looks like this

class CountdownTimer {
  CountdownTimer(this.start, this.stop, this.label, this.counting);
  final Function start;
  final Function stop;
  ValueNotifier<String> label;
  final bool counting;
}

String formatTimer(int timeInSeconds) {
  return timeInSeconds.toString();
}

var _isMounted = false;

CountdownTimer useCountdownTimer(int countdownTime, [bool useAsTimer = false]) {
  final label = useState('0');
  final timer = useState<Timer?>(null);
  final counting = useState(false);

  var stopTimer = useCallback(
    () {
      if (timer.value != null) {
        timer.value!.cancel();
        counting.value = false;
      }
    },
    [],
  );

  useEffect(
    () {
      _isMounted = true;
      return () {
        _isMounted = false;
      };
    },
    [],
  );

  var startTimer = useCallback(
    () {
      stopTimer();
      label.value = formatTimer(useAsTimer ? 1 : countdownTime);
      var duration = const Duration(seconds: 1);
      var time = useAsTimer ? 1 : countdownTime;
      counting.value = true;
      timer.value = Timer.periodic(duration, (Timer t) {
        if (!_isMounted) {
          return;
        }
        if (useAsTimer ? time == countdownTime : time == 0) {
          t.cancel();
          counting.value = false;
        } else {
          useAsTimer ? time++ : time--;
          label.value = formatTimer(time);
        }
      });
    },
    [countdownTime],
  );

  return CountdownTimer(startTimer, stopTimer, label, counting.value);
}

Now the weirdest thing is, this works perfectly on Android,
timer.value = Timer.periodic(duration, (Timer t) {
        if (!_isMounted) {
          return;
        }
        if (useAsTimer ? time == countdownTime : time == 0) {
          t.cancel();
          counting.value = false;
        } else {
          useAsTimer ? time++ : time--;
          label.value = formatTimer(time);
        }
      });

This gets called every 1 second.
But the same code does not work on ios. nothing changes. unless i am missing something key towards ios i am not sure.
any assistance or guidance would be greatly appreciated


text:
Q: When finding the s-domain transfer function of an op-amp, is the following possible? I'm trying to find the transfer function of a Sallen key filter in the s-domain and thought that cutting out the op-amp from the circuit by using the ideal op-amp laws was a smart move (see image below). However, when I attempt this I end up with the transfer function seen below.
\$ \dfrac{V_o}{V_i}=\dfrac{s(R_2+C_2)+1}{s^2(R_1R_2C_1C_2 + R_1R_2C_2^2) +s(R_1C_1 +2R_1C_2+R_2C_1 +R_2C_2) + (R_1/R_2 + 1)} \$
This transfer function does not agree with what any sources on the Internet say, and I'm sure that it's because of how I've remade the circuit.
If possible, could someone please explain to me why this would not work (if that's the case) and how would be better to approach this task?

A: If you wish to redraw the circuit without the op-amp, try something like this:

simulate this circuit – Schematic created using CircuitLab
See the difference?

A: Well this is a very basic mistake I've seen my friends commit while solving circuits involving Op-amps.
Here is the equivalent structure of an Op-Amp

Ideally we have Rin=infinite, Rout=0 ohms(whereas in reality Rin=Mega Ohms and Rout=0-10 Ohms)
In Op-amps circuits having negative feedback we use the virtual short approximation i.e.

*

*Vp=Vn

*No Current is entering the Op-Amp

Now coming to your circuit. You committed a mistake by joining Vout directly to Vp in your equivalent model. Why so ? Because the Virtual Short approximation states that Vp=Vn & Zero amount of  Current is entering the Op amp. When you join Vout and Vp you allow the current from C2 to pass through the Op amp, which actually is completely going into the Output terminal of the Op-amp.
As for your final result, Wiki has a good step by step derivation.
Reference for Virtual Short


text:
Q: vandermonde matrix matlab confusion I'm trying to construct a vandermonde matrix using matlab.
My input vector is
t = [ 1 2 3 4 ]'

My output using the vander function is:
ans =

 1     1     1     1
 8     4     2     1
27     9     3     1
64    16     4     1

Now if I'm not mistaken the vandermonde matrix of the vector in question should be:
1 1 1 1
1 2 4 8
1 3 9 27
1 4 16 64

now I just realized that I can achieve my desired result using something like:
>> fliplr(vander(t))

 ans =

 1     1     1     1
 1     2     4     8
 1     3     9    27
 1     4    16    64

Thanks.

A: Wikipedia and Mathworld agree with you. However, MATLAB documentation says that:

A = vander(v) returns the Vandermonde matrix whose columns are powers
  of the vector v, that is, A(i,j) = v(i)^(n-j), where n = length(v).

I have no idea why The Mathworks did it like this. You can use fliplr to achieve desired result.

A: Just flip the matrix (left/right) to get the one you want.


text:
Q: Angular2. How to get access to the all level routeConfig elements form directives I want to create a directives which should be check ACL defined on the routeConfig element by extend routerData
How can I get access to the routerData defined in routerConfig? (must have all levels of menu)
Example:
My ACL direvtives
@Directive({
    selector: '[myAcl]'
})
export class MyAclDirective {

    @Input('routerLink')
    routeParams: any[];

    /**
     *
     */
    constructor(private _elementRef: ElementRef, private router:Router) {
    }

    ngAfterViewInit(){

        //Key name to find in 'routeConfig' acl definition of 'routerData'
        let componentAliasName = this.routeParams;

        //NEED TO GET ACCESS TO ROUTECONFIG DEFINITION
        //
        //Example:
        //  @RouteConfig([
        //      { path:'/user/...',   name: 'UserLink', component: UserComponent, data: {res: 'user', priv: 'show'} } ])
        // AND GET BY 'name' == 'componentAliasName' my extend acl definition "data: {res: 'user', priv: 'show'}"

        console.log("CHECK ACL: " + data.res + " | " + data.priv);

        //ACL service
        let hasAccess = AclService.checkAccess(data.res, data.priv);

        if (!hasAccess) {
            let el : HTMLElement = this._elementRef.nativeElement;
            el.parentNode.removeChild(el);
        }

    }
}

MainComponent
@RouteConfig([
    { path:'/home',       name: 'HomeLink', component: HomeComponent, useAsDefault: true },
    { path:'/user/...',   name: 'UserLink', component: UserComponent, data: {res: 'user', priv: 'show'} }
])

@Component({
    selector: 'main-app',
    template: `

Home

User

Profile

SubProfile

        <router-outlet></router-outlet>
    `,
    directives: [ MY_ACL_DIRECTIVES, ROUTER_DIRECTIVES ],
})
export class MainComponent {

}

UserComponent
@RouteConfig([
    { path: '/profile/...', name: 'ProfileLink', component: ProfileComponent, data: {res: 'profile', priv: 'show'} }
])
@Component({
    selector: 'user-id',
    template: `<h1>User</h1>`,
    directives: [ROUTER_DIRECTIVES, MY_ACL_DIRECTIVES]
})
export class UserComponent {
}

ProfileComponent
@RouteConfig([
    { path: '/subprofile', name: 'SubProfileLink', component: SubProfileComponent, data: {res: 'profile', priv: 'details'} }
])
@Component({
    selector: 'profile-id',
    template: `<h1>Profile</h1>`,
    directives: [ROUTER_DIRECTIVES, MY_ACL_DIRECTIVES]
})
export class ProfileComponent {
}

SubProfileComponent
@Component({
    selector: 'subprofile-id',
    template: `<h1>Sub Profile</h1>`,
    directives: [ROUTER_DIRECTIVES, MY_ACL_DIRECTIVES]
})
export class SubProfileComponent {
}

Related link

A: You should be able to use the CanActivate decorator. It would look something like this:
@Component({...})
@CanActivate((next, prev) => (hasAccess))
export class UserComponent {
    // your component code
}

You can read more here: https://angular.io/docs/ts/latest/api/router/CanActivate-decorator.html


text:
Q: How to create custom document _id in logstash? This is sample logstash output filter.
output
{
    elasticsearch
    {
            hosts => ["localhost"]
            sniffing => true
            manage_template => false
            index => "mqtt-index-%{+YYYY.MM.dd}"
            document_id => "%{parsedMessage.device_id}"
            document_type => "iot_data"
    }
}

This code changes existing _id as %{parsedMessage.device_id} as it is. How  to change _id by another field?

A: Removed the target option from filter.
filter
{
        json
        {
                source => "message"
        }
}
And use following output for creating custom document id.
output
{
    elasticsearch
    {
            hosts => ["localhost:9200"]
            sniffing => true
            manage_template => false
            index => "mqtt-index-%{+YYYY.MM.dd}"
            document_id => "%{device_id}"
            document_type => "iot_data"
    }
}

A: The notation is not correct you need to do it this way
        document_id => "%{[parsedMessage][device_id]}"


text:
Q: Fetch rows from database table android I'm trying to return the array of rows where the username matches the username in the database table. The JSON result just gives me the last row.
example table:
james 14 u@aol.com

mah 12 j@aol.com

james 23 ra@yahoo.com

result gives me:
23 ra@yahoo.com

but i want both james rows not just the last one.
so both 14 u@aol.com and 23 ra@yahoo.com
 thanks
My php code:
<?php
    $username = $_POST["username"];

    $con = new mysqli("xx", "xx", "xx", "xx");

    // selects everything
    $statement = mysqli_prepare($con, "SELECT * FROM `user` WHERE username = ?");
    mysqli_stmt_bind_param($statement, "s", $username);

    mysqli_stmt_execute($statement);
    // Store the result to use
    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $id, $username, $age, $email);

    // Get results returned and put in array
    $user = array();
    while (mysqli_stmt_fetch($statement)) {
        $user[age] = $age;
        $user[email] = $email;
    }

    // Send array back to phone
    print (json_encode($user));

    mysqli_stmt_close($statement);
    mysqli_close($con);

?>

A: Your array should be empty not like [age][email] it should be empty so that array create index.

A: You overwrite the array so try something like this
while (mysqli_stmt_fetch($statement)) {
        $user[] = array( 'age'=>$age, 'email'=>$email);
    }

A: user[] should be a 2 dimensional array.
In your case last element will be there in the array.
while (mysqli_stmt_fetch($statement)) {
        $user[] = array('age'=>$age,'email' =>$email);
    }

Hope this helps.


text:
Q: std.algorithm.remove() duplicating array items? I have an array that I need to remove items from, by index. It for some reason duplicates other items in the array to take the removed item's place. Here is an example of the issue.
import std.stdio: writeln;
import std.algorithm: remove;

void main() {
    string[string] assocArray = [
        "firstvalue": "Number 1",
        "secondvalue": "Number 2",
        "thirdvalue": "Number 3",
        "fourthvalue": "Number 4",
        "fifthvalue": "Number 5",
        "sixthvalue": "Number 6",
    ];

    string[] assocArrayKeys = assocArray.keys(); // I know these aren't in the same order as the literal.

    writeln(assocArrayKeys);
    // ["thirdvalue", "fourthvalue", "fifthvalue", "sixthvalue", "firstvalue", "secondvalue"]

    assocArrayKeys.remove(0);
    assocArrayKeys.remove(5);

    writeln(assocArrayKeys);
    // ["fourthvalue", "fifthvalue", "sixthvalue", "firstvalue", "secondvalue", "secondvalue"]
    // It did remove them, but there are now two "secondvalue"s.
}

Any help would be appreciated.

A: This was somewhat of a silly question. Someone pointed out that in the documentation, it says that it has to be reassigned to itself.

Note that remove does not change the length of the original range directly; instead, it returns the shortened range. If its return value is not assigned to the original range, the original range will retain its original length, though its contents will have changed.

Source: https://dlang.org/library/std/algorithm/mutation/remove.html
The solution is as follows:
assocArraykeys = assocArrayKeys.remove(0);
assocArrayKeys = assocArrayKeys.remove(5);

This seems a little silly and unintuitive to me though because it is in std.algorithm.mutation. Keyword: mutation.


text:
Q: curl LinkedIn API I obtained the oauth token and oauth token secret for the LinkedIn API via Python. I'd like to make some REST calls via curl now and I tried the following ;
curl -v "http://api.linkedin.com/v1/people/~" -d "oauth_token=xxxxxxxxxx" -d "oauth_token_secret=xxxxxxxxxxxxx"

I've used the LinkedIn API in Python but wanted to use in curl. Am I missing something here ?
Any suggestions in this regard will be highly appreciated.
Thank you for your help.

A: You need to sign the requests using OAuth - usually the best way to do this is to use a library (like you mentioned, the python library works well).  You can scoop the HTTP traffic to see what additional headers are being sent.  The developer portal at http://developer.linkedin.com has an overview of the OAuth stuff, but it'd be pretty tough to get a working implementation for Curl because each signature you generate will be different (based on timestamp).


text:
Q: How can I fold YAML items in VIM? I have a YAML formatted text file, and would like to define custom folding for VIM, but I'm not sure how to go about it (despite reading the VIM documentation for folding).  The file consists of YAML "documents", like so:
---
title: My Title
attr1: value1
attr2: value2
---
title: Next Item
attr1: value3
---
title: One More Item
...

I would like the resulting folded text to look something like this:
+---- 2 lines: My Title ----
+---- ? lines: Next Item ---

Any suggestions are appreciated!  Thanks!

A: Do
%s/---\(.*\)\(\_.\{-}title: \)\(.*\)/---\1 #{{{1 \3\2\3/g
set foldmethod=marker

or
%s/\(---\_.\{-}title: \)\(.*\)/#{{{1 \2\r\1\2/g
set foldmethod=marker

That will add comment with title to the beginning of every YAML document and leave document still valid. foldmarker option must be left untouched.
Result:
1.
--- #{{{1 My Title
title: My Title
attr1: value1
attr2: value2
--- #{{{1 Next Item
title: Next Item
attr1: value3
--- #{{{1 One More Item
title: One More Item
...

Folded:
+--  4 строк: --- My Title-----------------------------
+--  3 строк: --- Next Item----------------------------
+--  3 строк: --- One More Item------------------------

2.
#{{{1 My Title
---
title: My Title
attr1: value1
attr2: value2
#{{{1 Next Item
---
title: Next Item
attr1: value3
#{{{1 One More Item
---
title: One More Item
...

Folded:
+--  5 строк: My Title--------------------------------
+--  4 строк: Next Item-------------------------------
+--  4 строк: One More Item---------------------------

A:
If you want to use a foldmethod other than "manual" all the time, add this line to your ~/.vimrc:
  set foldmethod=foldoption

I would recommend using foldmethod=indent.  This will fold based on any indent.  Then if you change your input to include the indents where you want folds to happen.  For instance if you change your input to
---
title: My Title
    other attrs: other values
---
title: Next Item
---
title: One More Item
...

It will fold as you described

A: Check out pedro's yaml-vim-plugin for improved folding that matches your exact request.
Read more about the plugin on
pedro's blog or find it directly on github as pedrohdz/vim-yaml-folds

The default Vim folding rules for YAML files were always a bit of an eye strain for me. The folding commands do not behave as one would expect them to as well. More about all this in the Explanation section below.
This got me to throw together a quick and simple Vim plugin to handle YAML folding more cleanly, vim-yaml-folds. Here is what YAML folding looks like with vim-yaml-folds installed:
A fold contains the beginning of a YAML section with everything underneath it included.
If you know what I'm talking about and do not care for an explanation, feel free to skip the Explanation and install vim-yaml-folds if you would like.


text:
Q: Relationship based on time I am trying to create a relationship between two data frames that are related, but there is no key that creates a relationship. Here is the layout of my problem:
The first data frame that I am using is information about when people entered an amusement park. In this amusement park, people can stay at the park for multiple days. So the structure of this data frame is

id
name
date

0
John Smith
07-01-2020 10:13:24

1
John Smith
07-22-2020 09:47:04

4
Jane Doe
07-22-2020 09:47:04

2
Jane Doe
06-13-2020 13:27:53

3
Thomas Wallace
07-08-2020 11:15:28

So people may visit the park once, or multiple times (assume that name is a unique identifier for people). For the other data frame, the data is what rides they went on during their time at the park. So the structure of this data frame is

name
ride
date

John Smith
Insanity
07-01-2020 13:53:07

John Smith
Bumper Cars
07-01-2020 16:37:29

John Smith
Tilt-A-Whirl
07-02-2020 08:21:18

John Smith
Insanity
07-22-2020 11:44:32

Jane Doe
Bumper Cars
06-13-2020 14:14:41

Jane Doe
Teacups
06-13-2020 17:31:56

Thomas Wallace
Insanity
07-08-2020 13:20:23

With these two data frames, I want to get the id of the visit associated with the rides that they went on during that visit. So the desired output in this example would be

id
name
ride
date

0
John Smith
Insanity
07-01-2020 13:53:07

0
John Smith
Bumper Cars
07-01-2020 16:37:29

0
John Smith
Tilt-A-Whirl
07-02-2020 08:21:18

1
John Smith
Insanity
07-22-2020 11:44:32

2
Jane Doe
Bumper Cars
06-13-2020 14:14:41

2
Jane Doe
Teacups
06-13-2020 17:31:56

3
Thomas Wallace
Insanity
07-08-2020 13:20:23

The way how I had thought about approaching this problem is by iterating over the visits and then adding the id to the ride if the name matched, the ride occurred during/after the visit, and the time delta is the smallest difference (using a large initial time delta and then updating the smallest different to that difference). If those conditions are not met, then just keep the same value. With this process in mind, here is my thought process in code:
rides['min_diff'] = pd.to_timedelta(365, unit='day')
rides['id'] = -1
for index, row in visits.iterrows():
    rides['id'], rides['min_diff'] = np.where((rides['name'] == row['name']) & (
                                               rides['date'] >= visits['date']) & (
                                               (rides['date'] - row['date']) < rides['min_diff']),
                                               (row['id'], rides['date'] - row['date']),
                                               (rides['id'], rides['min_diff'))

This unfortunately does not execute because of the shapes not matching (as well as trying to assign values across multiple columns, which I am not sure how to do), but this is the general idea. I am not sure how this could be accomplished exactly, so if anyone has a solution, I would appreciate it.

A: Try with apply() and asof():
df1 = df1.set_index("date").sort_index() #asof requires a sorted index
df2["id"] = df2.apply(lambda x: df1[df1["Name"]==x["Name"]]["id"].asof(x["date"]), axis=1)

>>> df2
             Name          ride                date  id
0      John Smith      Insanity 2020-07-01 13:53:07   0
1      John Smith   Bumper Cars 2020-07-01 16:37:29   0
2      John Smith  Tilt-A-Whirl 2020-07-02 08:21:18   0
3      John Smith      Insanity 2020-07-22 11:44:32   1
4        Jane Doe   Bumper Cars 2020-06-13 14:14:41   2
5        Jane Doe       Teacups 2020-06-13 17:31:56   2
6  Thomas Wallace      Insanity 2020-07-08 13:20:23   3

A: I think this does what you need. The ids aren't in the order you specified but they do represent visit ids with the logic you requested.
merged = pd.merge(df1, df2, how="right", left_on=['date', 'name'], right_on=['name', 'ride'])[['name_y', 'ride', 'date_y']]
merged['ymd'] = pd.to_datetime(merged.date_y).apply(lambda x: x.strftime('%Y-%m-%d'))
merged['id'] = merged.groupby(['name_y', 'ymd']).ngroup()
merged.drop('ymd', axis=1, inplace=True)
merged.columns = ['name', 'ride', 'date', 'id']
merged.sort_values(by='id', inplace=True)
print(merged)

OUT:
             name           ride                 date  id
4        Jane Doe   Bumper Cars   06-13-2020 14:14:41   0
5        Jane Doe       Teacups   06-13-2020 17:31:56   0
0      John Smith      Insanity   07-01-2020 13:53:07   1
1      John Smith   Bumper Cars   07-01-2020 16:37:29   1
2      John Smith  Tilt-A-Whirl   07-02-2020 08:21:18   2
3      John Smith      Insanity   07-22-2020 11:44:32   3
6  Thomas Wallace       Insanity  07-08-2020 13:20:23   4


text:
Q: Moti avoid speeding up and down for loop Trying to make a spinner with Moti but having some issue with the speeding down (just want it to spin for ever (I do like that it starts out slow, but not needed).

import { Feather } from '@expo/vector-icons'
import { MotiText } from 'moti'
import React from 'react'
import type { TextStyle } from 'react-native'

import { Colors } from '~/constants/Theme'

type Props = {
  color?: TextStyle['color']
  size?: number
}

export function LoadingSpinner({ color = Colors['white'], size = 15 }: Props) {
  return (
    <MotiText
      from={{
        rotate: '0deg',
      }}
      animate={{
        rotate: '360deg',
      }}
      transition={{
        loop: true,
        repeatReverse: false,
        type: 'timing',
        duration: 5000,
      }}
    >
      <Feather
        name="loader"
        size={size}
        style={{
          paddingBottom: 5,
          color,
        }}
      />
    </MotiText>
  )
}

I'm guessing that it's type: 'timing', that's the issue, but it seems like I can only do timing and spring

A: Have you tried adding easing: Easing.linear to transition, where Easing is imported from react-native-reanimated?


text:
Q: Angularjs watch not working with array inside of object I have an object {Client:[],Employee:[],Product:[],Project:[],PayPeriod:[]} in which each array gets pushed and spliced by components through a two way binding. The main controller connects all 5 of the arrays and gives them to another component. In said component I need to watch that binding but no matter what I do it does not work. This is what I have now.
$scope.$watch('ctrl.parameters', ctrl.Update(), true);

ctrl.Update(); is a function and works.
ctrl.parameters does get updated but does not trigger $watch.
It's a bit of a complicated so if you need anything explained butter I can.
ctrl.Update = function () {
        $.post("/TrackIt/Query.php?Type=getViaParams&EntityType="+ctrl.entity,{Params:ctrl.parameters},function(Data,Status){
            if(Status=="success"){
                if (Data.Success) {
                    ctrl.List = Data.Result.Entities;
                } else {
                    AlertService.Alert(Data.Errors[0],false,null);
                    SessionService.Session(function () {
                        ctrl.Update();
                    });
                }
                $scope.$apply();
            }else{
                AlertService.Alert("Something is up with the select options",false,null);
            }
        },'json');
    };

Edit 1 :
Par = {Client:[],Employee:[],Product:[],Project:[],PayPeriod:[]}
5 Components with two way binding = Par.X (these are what edit the parameters)
1 Component with two way binding = Par (I need to watch the binding inside here)
Edit 2 :

        <entity-select entity="'Client'" ng-model="Values.Client" multi="true" ng-array="Parameters.Client"></entity-select>
        <entity-select entity="'Employee'" ng-model="Values.Employee" multi="true" ng-array="Parameters.Employee"></entity-select>
        <entity-select entity="'Product'" ng-model="Values.Product" multi="true" ng-array="Parameters.Product"></entity-select>
        <entity-select entity="'Project'" ng-model="Values.Project" multi="true" ng-array="Parameters.Project"></entity-select>
        <entity-select entity="'PayPeriod'" ng-model="Values.PayPeriod" multi="true" ng-array="Parameters.PayPeriod"></entity-select>

    <parameter-table entity="'Entry'" parameters="Parameters"></parameter-table>

TrackIT.component('entitySelect', {
templateUrl: "/Content/Templates/Select.html",
controller: function SelectController($scope, $http, AlertService, SessionService) {
    var ctrl = this;
    ctrl.Options = [];
    ctrl.Display = [];

    ctrl.Add = function () {
        var Display = {'Label':ctrl.Label(ctrl.ngModel),'Value':ctrl.ngModel};
        ctrl.ngArray.push(ctrl.ngModel);
        ctrl.Display.push(Display);
    };

    ctrl.Remove = function (Key) {
        ctrl.ngArray.splice(Key, 1);
        ctrl.Display.splice(Key, 1);
    };

    ctrl.$onInit = function() {
        $.post("/TrackIt/Query.php?Type=getSelectList&EntityType="+ctrl.entity,null,function(Data,Status){
            if(Status=="success"){
                if (Data.Success) {
                    ctrl.Options = Data.Result.Entities;
                    if(ctrl.ngModel==undefined){
                        if(ctrl.none){
                            ctrl.ngModel = "NULL"
                        }else{
                            ctrl.ngModel = angular.copy(ctrl.Options[0].Attributes.ID.Value.toString());
                        }
                    }
                } else {
                    AlertService.Alert(Data.Errors[0],false,null);
                }
                $scope.$apply();
            }else{
                AlertService.Alert("Something is up with the select options",false,null);
            }
        },'json');
    };

    ctrl.Label = function(Value) {
        for (var prop in ctrl.Options) {
            if(!ctrl.Options.hasOwnProperty(prop)) continue;
            if(ctrl.Options[prop].Attributes.ID.Value.toString()==Value.toString()){
                return ctrl.Options[prop].DisplayName;
            }
        }
    };

},
bindings: {
    entity:"<",
    multi:"<",
    none:"<",
    ngModel:"=",
    ngArray:"="
}
});

TrackIT.component('parameterTable', {
templateUrl: "/Content/Templates/BasicTable.html",
controller: function ParameterTableController($scope, $http, AlertService, SessionService, DisplayService) {
    var ctrl = this;
    ctrl.List = {};

    ctrl.Update = function () {
        $.post("/TrackIt/Query.php?Type=getViaParams&EntityType="+ctrl.entity,{Params:ctrl.parameters},function(Data,Status){
            if(Status=="success"){
                if (Data.Success) {
                    ctrl.List = Data.Result.Entities;
                } else {
                    AlertService.Alert(Data.Errors[0],false,null);
                    SessionService.Session(function () {
                        ctrl.Update();
                    });
                }
                $scope.$apply();
            }else{
                AlertService.Alert("Something is up with the select options",false,null);
            }
        },'json');
    };

    $scope.$watch('ctrl.parameters', ctrl.Update.bind(ctrl), true);

    ctrl.$onInit = function() {
        DisplayService.DisplayTrigger(function () {
            ctrl.Update();
        });
        ctrl.Update();
    }
},
bindings: {
    entity: "<",
    parameters: "="
}
});

A: There are two problems here.
Problem 1: ctrl is not a property on the scope
After seeing the full controller code, I can see that ctrl is just an alias for this, the instance of the controller which will be published on the scope as $ctrl by default. But you can avoid having to worry about what it is called by instead passing a function instead of a string to $scope.$watch():
// ES5
$scope.$watch(function () { return ctrl.parameters; }, ctrl.Update, true);
// ES6/Typescript/Babel
$scope.$watch(() => ctrl.parameters, ctrl.Update, true);

It's all functions to Angular
You may not be aware that as far as Angular is concerned, it is always calling a function for each watch to get the value to compare. When you pass a string to $scope.$watch(), Angular uses $parse to create a function from that expression. This is how Angular turns strings into executable code in bindings, expressions, and so on.
The function that gets created takes in a single parameter, which is the "context" to evaluate the expression on. You can think of this as which scope to use.
When you pass a function to $scope.$watch() as the first parameter, you effectively save Angular having to create a function for you from the string.
Problem 2: the way you specify the watch listener function
Your ctrl.Update() function is just a function that you want run whenever ctrl.parameters changes.
What you have said in your code of $scope.$watch('ctrl.parameters', ctrl.Update(), true); is:

Do a deep watch (watch changes to any property) on ctrl.parameters, and when it changes, call the result of calling ctrl.Update(), which will be a jQuery promise, not a function.

Instead, you want to pass the ctrl.Update function itself as the second parameter to $scope.$watch(), so it gets called when a change is detected. To do that, just pass ctrl.Update instead of ctrl.Update():
$scope.$watch('ctrl.parameters', ctrl.Update, true);

A Note of Caution
Using ctrl.Update in this particular case will work, because there is no use of this inside that function. For others looking at this answer, note that when you pass a function in this way, the this binding (the "context") is not maintained as ctrl as you might expect. To get around this, use ctrl.Update.bind(ctrl), or just wrap it in a function so it gets called with the correct context: $scope.$watch('ctrl.parameters', function () { ctrl.Update() }, true);.
Use deep/value watches sparingly
You should be very sparing in your use of deep watches in an Angular app (also known as value watches). The reason is that it is a very expensive operation for big objects, as Angular has to do a deep comparison of the object on every digest cycle - traversing through every single property on the entire object, and then, if there is a change, making a deep clone of the object, which again requires traversing every single property to make a completely separate copy to compare against next time.
You can think of a deep watch on an object with n properties as being the equivalent of n shallow/reference watches.
I have a feeling that may be a scarily large number in your situation.

A: I think the problem is that your watch statement is incorrect. The second parameter to $watch must be a function. The following should work:
$scope.$watch('ctrl.parameters', ctrl.Update.bind(ctrl), true);

Note the use of bind to ensure the this parameter is set appropriately.