text:
Q: C - argv stores random values instead of given ones The program should take three command line arguments of which the first is an arithmetical operand and the second and third numbers on which the operand should be applied
This program will print random values.
#include <stdio.h>

int main (int argc, int *argv[])
{
  switch ( (char) * argv[1] )
  {
    case '+' : printf("%d", *argv[2] + *argv[3] );
  }

  return 0;
}

Also, how am I supposed to get as command line arguments different data types? Is using the type cast correct?

A: #include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
  if ( argc > 3 )
  {
    switch ( *argv[1] )
    {
       case '+' :
          printf("answer: %d\n", atoi(argv[2]) + atoi(argv[3])  );
          break;
       default :
          printf("ERROR: operand %c invalid\n",*argv[1]);
    }
  }
  else
  {
     printf("ERROR: you must enter operator, plus two operands. e.g.:\n");
     printf("%s + 3 2\n",argv[0]);
     return 1;
  }
}

A: #include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[]) {
  if(argc != 4) {
    printf("Error message");
    printf("USAGE: ./a.out <operand> <number1> <number2>");
    return 0;
  }
  switch(*argv[1]) {
    case '+':
      printf("%d", (atoi(argv[2])+atoi(argv[3])));
      break;
    default:
      printf("Enter valid operand");
  }
}

A: As others have mentioned, the arguments are read as an array of strings into argv. Thus you must use char *argv[]. Conversion from string to int is performed by atoi. Simply casting a character to an integer will give you the ASCII representation of that character.
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
    switch ( *argv[1] )
    {
        case '+':
            printf("%d\n", atoi(argv[2]) + atoi(argv[3]) );
            break;
    }

    return 0;
}

To get floating point arithmetic, replace %d with %f and atoi by atof.
Of course you should also add sanity checks. In the very minimum, you should check argc to prevent reading from uninitialized space. See comments.


text:
Q: REST API wrapper - class design for 'lite' object responses I am writing a class library to serve as a managed .NET wrapper over a REST API. I'm very new to OOP, and this task is an ideal opportunity for me to learn some OOP concepts in a real-life situation that makes sense to me.
Some of the key resources/objects that the API returns are returned with different levels of detail depending on whether the request is for a single instance, a list, or part of a "search all resources" response. This is obviously a good design for the REST API itself, so that full objects aren't returned (thus increasing the size of the response and therefore the time taken to respond) unless they're needed.
So, to be clear:

*

*.../car/1234.json returns the full Car object for 1234, all its properties like colour, make, model, year, engine_size, etc. Let's call this full.

*.../cars.json returns a list of Car objects, but only with a subset of the properties returned by .../car/1234.json. Let's call this lite.

*...search.json returns, among other things, a list of car objects, but with minimal properties (only ID, make and model). Let's call this lite-lite.

I want to know what the pros and cons of each of the following possible designs are, and whether there is a better design that I haven't covered:

*

*Create a Car class that models the lite-lite properties, and then have each of the more detailed responses inherit and extend this class.

*Create separate CarFull, CarLite and CarLiteLite classes corresponding to each of the responses.

*Create a single Car class that contains (nullable?) properties for the full response, and create constructors for each of the responses which populate it to the extent possible (and maybe include a property that returns the response type from which the instance was created).

I expect among other things there will be use cases for consumers of the wrapper where they will want to iterate through lists of Cars, regardless of which response type they were created from, such that the three response types can contribute to the same list.
Happy to be pointed to good resources on this sort of thing, and/or even told the name of the concept I'm describing so I can better target my research.

A: In C#, you can add attributes to the properties of an object:

*

*http://msdn.microsoft.com/en-us/library/z0w1kczw(v=vs.80).aspx

*http://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx
It would be easy enough to create an attribute that defines the level of detail a property represents - lite or full - and add the attribute to each of the properties of the car object.  Once you've decorated all of the properties with attributes, write a serialiser class that can be fed an object and a level of detail as its arguments.  It will:

*

*Use reflection to find a list of all properties relevant to the current detail level;

*Spit out a list of those properties and their current values.

This gives you:

*

*A single class instead of multiple classes;

*The ability to have a fully-populated object and produce a lite representation without having to create an intermediate abridged copy;

*A class that can be extended with new properties and have them automatically be added to the REST API.

A: Based on your description, I would use option three. Option two is probably the worst of the bunch since you would be maximizing duplication and minimizing reuse.
Option one is the inheritance model. I don't feel like it's a good fit for the situation. The resulting class hierarchy will introduce complexity but you won't be gaining much in the trade-off. Inheritance can be very useful when you have a number of different objects which all share a common superclass. In this case you really only have one type of object (a car), you just have varying levels of completeness.
With your single car class from option three, there are some good tricks you can use like lazy loading of properties. Basically if your class has been filled with the least amount of data possible then in the getter of the other properties you can trigger a call out to the more detailed API and fill in the rest of the information. Be careful to model this type of behavior around actual usage patterns the object may see, but it can greatly help with ease of use for other programmers who consume your object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Formatting an external hard drive to exFAT? I have a 1T Western Digital external hard drive. I'm using it mainly to store movies.
When I try to format to NTFS, I get an error message that says 'Windows was unable to complete format'.
However, it will format to exFAT without any problems.
Is there a any real reason why I should not just go with the exFAT system?
ETA: I'm running Vista.

A: exFAT does require at the very least an up to date version of Windows XP, so it's slightly less interoperable than NTFS. Also, if you're going to use with a Mac, that will require Snow Leopard and Linux has yet to have usable support.
For a good list of advantages and disadvantages, check the Wikipedia article here:
http://en.wikipedia.org/wiki/ExFAT


text:
Q: How to write Regexp for checking parts of url? Can someone help me to write RegExp for checking URL which look like this
"https://{some_unknown_part}

{this_part_I_know/e.g./domen1.com_or_domen2.org}"?

Thank you.

A: Your question is very unclear. As of your comment, I understand it like that (seems to be the case, so here the same as in the comments above also as an answer):
The beginning of the string needs to be https:// followed by some text and then domain.com? If so, you can use
https:\/\/(?:.*?\.)?domain\.com.*

Here is a live example.


text:
Q: Limit in which terms involve n Limit n goes to infinity $\frac{1}{n}+\frac{1}{n+1}+......+\frac{1}{n+2n}$.
Well the answer came out log[3].. but i dont know how.?
I am trying for MCA.
please don't tell complete answer just a hint would be useful

A: Hint:
Note that
$$\sum_{i = 0}^{2n} \frac{1}{n + i} = \sum_{i = 0}^{2n} \frac 1 n \cdot \frac 1 {1 + i/n} = \sum_{i =0}^{2n} \frac 1 n f\left(\frac i n\right)$$
for $f(x) = \frac 1 {1 + x}$. Do you recognize a Riemann sum?

A: Draw a picture of $y=1/x$. Use the picture to note that
$$\int_k^{k+1} \frac{dx}{x} \lt \frac{1}{k}\lt \int_{k-1}^k \frac{dx}{x}.$$
Thus
$$\int_n^{3n}\frac{dx}{x}\lt \sum_n^{3n}\frac{1}{k}\lt \int_{n-1}^{3n-1} \frac{dx}{x}.$$
Evaluate the integrals, and Squeeze.


text:
Q: cocos2d sprites disable touches i haves game with cocos2d i have many sprites
i'm using touch to sprite with this
CGRectContainsPoint([[gameImages objectAtIndex:i] boundingBox], location)
CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL: location];

but when i touched the sprite must be deleted
i have
[self removeChild:[gameImages objectAtIndex:bacvacIndexner[0]] cleanup:YES];

but the touch works because i use the object coordinates and i cant delete object when i removin that from child
what can i do?why i can get the touch event for sprite . are anything without coordinate method?

A: Use a callback so a higher class remove the object. Inside your to-be-removed class:
[self.touchDelegate performSelector:@selector(removeMe:) withObject:self afterDelay:0.0f];


text:
Q: Topology on union of circumferences Let $$X = \bigcup^{\infty} C_{n}$$ be the subset of $\mathbb{R}^2$ union of the circumferences $ C_n $ having ray 1/n and center (1/n,0), n>0, endowed with the topology induced by that of $\mathbb{R}^2$.
I know the open sets are exactly the intersections of X with the open sets in $\mathbb{R}^2$, and that the circumferences are closed and not open.
1)I now have to prove that X is separable and metrizable, but I cannot see how. The only countable set that seems promising to me and could be dense is {(1/n,0), (0,0)}; if this is the case, I think I recognise it is not closed, so its closure must be bigger, but I fail to notice why it must be all of X.
I also have no idea why it is metrizable.
2) I would also need some hint on how to proceed to show it's (locally) path-connected.
Thanks in advance!

A: $X$ is a subspace of $\mathbb{R}^2$. Subspace of metrizable is metrizable, and subspace of second-countable is second-countable. Being metrizable (and second-countable), it is also separable. So that part is accounted for.
Now, if $p \in X$ is not $(0,0)$, you can get arbitrarily small neighbourhoods $V$ of $p$ in the induced topology consisting of only a segment of the circle that $p$ belongs to. If $p$ is $(0,0)$, you can get arbitrarily small neighbourhoods which are similar to "star convex" domains. So it follows that it is locally path-connected.

A: Any circle has a countable dense subset. (say it is centered at $(0,0)$ and take intersections of it with rays $y=rx,$ where $r$ is rational.) Then your space has a countable union of countable sets dense in it.
For local path connectedness one way is to take two points in the union and "go along" each circle to $(0,0)$ and then connect the two paths.
EDIT The last paragraph doesn't work for local path connected, since the two arcs meeting at $(0,0)$ might go outside a neighborhood of the point $P.$ However if $P=(0,0)$ and $Q$ is near $P$ one can just go along the circle through $Q$ in the direction toward $P.$ And if $P \neq (0,0)$ then it is at some definite distance $d>0$ from $(0,0)$ and then all but finitely many of the circles will be inside the disc of radius $d$ centered at $(0,0).$ Then if one takes a small enough neighporhood of $P$ it will contain points only from the circle through $P$ and close to it, and such points connect to $P$ along the circle through $P.$


text:
Q: Telerik RadRating missing star when zoomed out I am having issue with RadRating control , It renders fine if the browser is zoomed to 100 %. But in chrome if the browser is zoomed 90 % or below 1 out of 5 stars will go missing.
I can see that the 5th start is there in source code but pushed to a new line and goes hidden, I checked Demo page of RadRating control  (http://demos.telerik.com/aspnet-ajax/rating/examples/gridrating/defaultcs.aspx) and this issue is there as well.
It will be very rare someone zooming their browser to 90 % but it will be better to make sure even when that happens control will be  rendered fine.
Steps to reproduce the issue:

*

*Take the demo page in chrome

*Set zoom to 90%

*Reload the page

I tried setting CSS zoom on both control and the whole body but it is not helping. Setting a CSS zoom  of 50 % on control will show all 5 stars  but then the stars will be too small. It will be great if someone can suggest me a workaround to fix this.
Thanks,
Rahul

A: I manage to hack the code by setting width of RadRating div from 104px to 112px using jQuery on page load. Still it will be great to know a nice and neat way to fix this.
UPDATE:
Also I was suggested a much neater solution using CSS in Telerik forum.

    .RadRating
    {
        width: 112px !important;
    }

My Post in Telerik Forum


text:
Q: What belongs into a DLQ / Invalid Message Queue? Is there a good best practice about what kind of messages an application is allowed to reject?
My understanding is that all messages which can't be handled should be rejected to the dead letter queue - no matter if the problem is a syntax error or a semantic error in the message or if the application is temporarily not able to handle the message (for instance because the db just went down).
Of course - if the app already knows upfront that it will not be able to handle a message (DB down), it should stop accepting messages.
So what's the common understanding / best practice?

A: My response is with respect to WebSphere MQ:
A Dead Letter Queue (DLQ for short) is a place where messages that could not be delivered to their destination are put. Messages can be put on the DLQ by queue managers, message channel agents (MCAs), and applications. All messages on the DLQ must be prefixed with a dead-letter header structure, MQDLH. The MQDLH header is automatically fixed when queue manager or MCAs put messages whereas applications must prefix the MQDLH explicitly.
As far applications are concerned, if they are unable to handle the message, say for example the message format is not understood, they can put the message to a BACKOUT queue instead of a DLQ. A BACKOUT queue is just like any normal queue where messages rejected by applications can be put. The advantage of BACKOUT queue is that you can specify a BACKOUT queue on a per queue basis and the messages put there need not have MQDLH header prefixed.
An application can be written to read the messages from BACKOUT and route them back to the target queue as it is. However the messages in a DLQ require additional processing to remove the MQDLH before they are put onto a target queue.


text:
Q: Sorting a linked list issue My code for sorting a linked list is below:
def sort_list(head)
    return head if head.nil? || head.next.nil?
    mid_node = find_mid(head)
    second_half = mid_node.next
    mid_node.next = nil
    left_half = sort_list(head)
    right_half = sort_list(second_half)

    merge(left_half, right_half)

end

def merge(left_head, right_head)

    left = left_head
    right = right_head
    dummy_head = dummy = ListNode.new(-1)

    until left.nil? || right.nil?
        if left.val > right.val
            dummy.next = right
            right = right.next
        else
            dummy.next = left
            left = left.next
        end
        dummy = dummy.next
    end

    #here there may be one list left over.
    dummy.next = left unless left.nil?
    dummy.next = right unless right.nil?

    dummy_head.next
end

def find_mid(head)
    return nil if head.nil?

    slow_ptr = fast_ptr = head
    until fast_ptr.nil? || fast_ptr.next.nil?
        fast_ptr = fast_ptr.next.next
        slow_ptr = slow_ptr.next
    end

    slow_ptr
end

This is giving me a stack too deep error, and I'm not sure why. Seems like I'm terminating both functions appropriately. The sort_list logic looks fine to me, and I tested the find_mid function. Merge also looks fine to me...so what's off here?

A: The problem is with your find_mid function. If you test it with a linked list of just two nodes, you would see it returns the last one instead of the first one.
Example:
list = ListNode.new(4, ListNode.new(3))
res = find_mid(list)
puts res.val # It would print 3

So, the list won't shrink any more and the code would repeat the recursion with a linked list of size 2 forever, or in reality, until the stack too deep error.
The solution then is to change the function as follows:
def find_mid(head)
    return nil if head.nil?

    slow_ptr = head
    fast_ptr = head.next
    until fast_ptr.nil? || fast_ptr.next.nil?
        fast_ptr = fast_ptr.next.next
        slow_ptr = slow_ptr.next
    end

    slow_ptr
end


text:
Q: SSRS report refreshes through I have 'never refresh' set for all parameters I have 2 date/time parameters, to and from. From was set to =DateAdd(DateInterval.Year, -1, Today()). And the other, to, was set to just =Today().
When I view the report, the default values are populated correctly and the report is generated correctly on first load. However, when I change the from date field, the report refreshes. If I change just the to field, it does not refresh.
Reading other suggestions on other sites, someme people mentioned creating a new dataset with something like Select GetDate() as Date and then using that as the default value of my parameter, but that didn't work. Another was creating an internal parameter and setting it's default value to =Today() and then using that value as my parameter's default - again, didn't work.
Anything else I might try?

A: More searching gave me my answer:

@Piquet - Your solution appears to be correct...at least in my case which seems similar to most of the other posts. I was using default values for date parameters that were expressions - "=Today()" and "=DateAdd("yyyy",-5,Today())". And no matter what I tried when changing the value of the report's first parameter would cause a page refresh that generated a blank/report.
I testing changing all parameters default to No Default where they were using expressions and viola no blank page refresh. To get back the default date values I'm now using a dataset like this:
Select CONVERT(date,(DateAdd("yyyy",-5,GETDATE()))) AS default_start, CONVERT(date,GETDATE()) AS default_end
  The blank page refresh is gone when changing the value of the parameters and the default date values are working fine.
Thanks for the post as it seemed an elusive problem. David

From this MSDN thread.
There's also a lot of information in that thread about how if you have two parameters, the second one is assumed to be dependant on the first if they both have expressions:

For example, if you have a report with Param1 and Param2, RS will assume Param2 depends on Param1 if:

*

*Param2 is populated from a query that uses certain types of
  expressions for query text, query parameters, calculated fields,
  filters, etc.

*Param2 is populated from one or more expressions.


text:
Q: Limit of an improper integral with trickery Find the limit,
$$\lim_{x\to0^+}\int_x^1\frac{f(t)}{t^3}\,\mathrm{d}t$$
Where $\:f:[0,1]\:$ is continuous.
Since $$f\in\mathcal{C}^0([0,1])\implies f\in\mathcal{R}([x,1])\text{ s.t. }\forall \epsilon>0 : \bigcup_{0<x<1}[x,1-\epsilon]\subset[0,1]$$
Also, for  $t\mapsto t^{-3}>0$ on $[x,1]$ and $t^{-3}$ is locally integrable.
Thus, by the first mean value theorem for integrals,
$$I_t=\int_x^1\frac{f(t)}{t^3}\,\text{d}t=f(\gamma)\int_x^1t^{-3}\,\text{d}t,\:\:\gamma\in[x,1]\\\implies I_t=\frac{f(\gamma)}{2}\left({1}/{x^2}-1\right)\\\implies \lim_{x\to0^+}I_t=\infty$$
But the answer should be $\left.f(0)\middle/2\right.$ and the teacher used $x^2\cdot\int_x^1\frac{f(t)}{t^3}\,\text{d}t$ to calculate the limit but like I don't get it I mean this isn't the integral we're looking for. How can we just add $x^2$ and then go about finding the limit?

A: Using L'Hospital's Rule (LHR) we have
$$\begin{align}
\lim_{x\to 0^+}x^2\int_x^1 \frac{f(t)}{t^3}\,dt&=\lim_{x\to 0^+}\left(\frac{\int_x^1 \frac{f(t)}{t^3}\,dt}{\frac1{x^2}}\right)\\\\
&\overbrace{=}_{LHR}\lim_{x\to 0^+}\left(\frac{-\frac{f(x)}{x^3}}{-\frac2{x^3}}\right)\\\\
&=\frac12f(0)
\end{align}$$
as was to be shown!


text:
Q: Unchecked Radio Button aspnet mvc I have a radio button that can started unchecked, but even when the condition is false, it's writting the checked attribute in html and the browser show checked
@Html.RadioButton("radio", "1", new { @checked = (condition) })
@Html.RadioButton("radio", "2", new { @checked = (condition) })

A: I think the proper use will be this
@Html.RadioButton("radio", "1",  (condition))

According to RadioButton
, radio button constructor defined as
RadioButton(string name,Object value, bool isChecked)

which will produce
<!-- isChecked is true. -->
<input type="radio" name="name" value="value" checked="checked" />
<!-- isChecked is false. -->
<input type="radio" name="name" value="value" />

I think you are trying to use new htmlattribute which is not needed.

A: The overload you are using for @Html.RadioButton takes HTML attributes. When you specify checked = (condition) you are specifying the attribute checked with a value.
With HTML inputs it's not a case of setting the checked value to true or false. The very presence of the checked attribute means the control is checked. So just checked, or checked = "", and even checked = "false" will all result in a checked control.
See also this related question: What's the proper value for a checked attribute of an HTML checkbox?
In your case you would be better off with the overload HtmlHelper.RadioButton Method (String, Object, Boolean) which lets you specify a boolean value for whether of not the control is checked.

A: Just check your condition on the controller and supply boolean via ViewBag
@Html.RadioButton("TestButton", "Value", (Boolean)ViewBag.DefaultValue)


text:
Q: cancan rails code understanding I am unable to debug some of cancancan code and looking for some help.
can :update, Message do |m|
  false
end

But strangely cancancan always return true and i am unable to debug the issue.Here is a small piece of relevant cancancan code
   rule.rb
    def matches_conditions?(action, subject, extra_args)
         if
           ...
          elsif @block && !subject_class?(subject)
            @block.call(subject, *extra_args)
          end
        end

I can see that the @block.call is made and it return false but this piece of code in the ability.rb does not make sense to me
match = subject.map do |subject|
        relevant_rules_for_match(action, subject).detect do |rule|
          rule.matches_conditions?(action, subject, extra_args)
        end
      end.compact.first

      match ? match.base_behavior : false

The base_behaviour is never set after initialization, and set to true at initialization, how would base_behaviour of a rule would ever return false.
The helper function is called
ability = Ability.new(user)
ability.can? :update ,@message

A: Got it there was a overriding ability


text:
Q: How can I retrieve all data and label the one that are the newest as the new data? I have a table named Standards that includes ID, StandardsFamiliy, Standards,Date and Link.
I want to show all data, but I want the newest date in same StandardsFamily and Standards labeled as the newest one.
For example if I have
StandardFamily,  Standards, Date
A                   a        2018
A                   a        2017
B                   b        2016
C                   c        2010
C                   c        2011
C                   c        2011
C                   c2       2018

I want to retrieve this:
StandardFamily,  Standards, Date,  Status
A                   a        2018   New
A                   a        2017   Old
B                   b        2016   New
C                   c        2010   Old
C                   c        2011   Old
C                   c        2012   New
C                   c2       2018   New

I know how to retrieve only the newest one with following query:
select *
from Standards
where (StandardFamily,Standards,Date)
IN (select StandardFamily,Standards,Max(Date) from Standards group by StandardFamily,Standards)

I think I might to follow something like
select
case when (...) then "New" else "Old" end
from Table

Any help would be appreciated! :)

A: You can get these results by LEFT JOINing to a list of MAX(Date) grouped by StandardFamily and Standard, and then checking for NULL values in the other table (only the entries with the newest Date will have non-NULL values):
SELECT *,
    CASE WHEN s1.StandardFamily IS NULL THEN "Old" ELSE "New" END AS Status
FROM Standards s
LEFT JOIN (SELECT StandardFamily, Standards, MAX(Date) AS Date
           FROM Standards
           GROUP BY StandardFamily, Standards) s1 ON s1.StandardFamily = s.StandardFamily AND s1.Standards = s.Standards AND s1.Date = s.Date

Output:
StandardFamily  Standards   Date    Status
A               a           2018    New
A               a           2017    Old
B               b           2016    New
C               c           2010    Old
C               c           2011    Old
C               c           2012    New
C               c2          2018    New

Demo on dbfiddle

A: In MySQL 8+, you would simply use row_number():
select s.*,
       (case when row_number() over (partition by StandardFamily, Standards order by date desc) = 1
             then 'New' else 'Old'
        end) as status
from standards s;

In earlier versions, I think I would use a correlated subquery:
select s.*,
       (case when date = (select max(s2.date)
                          from standards s2
                          where s2.StandardFamily = s.StandardFamily and
                                s2.Standards = s.Standards
                          )
              then 'New' else 'Old'
        end) as status
from standards s;

In particular, this can make good use of an index on (StandardFamily, Standards, Date).


text:
Q: Python - Property and updating attribute values I'm currently trying to wrap my head around Python properties.
Suppose I am to convert between Celsius and Kelvin. I have a class Degrees, that handles these calculations:
class Degrees(object):

    def __init__(self, celsius):
        self.celsius = celsius

    #Celsius
    def set_celsius(self, celsius):
        self._celsius = celsius
    def get_celsius(self):
        return self._celsius
    celsius = property(fget=get_celsius, fset=set_celsius)

    #Kelvin
    def set_kelvin(self, kelvin):
        self._kelvin = kelvin
    def get_kelvin(self):
        return self._kelvin
    kelvin = property(fget=get_kelvin, fset=set_kelvin)

    def to_kelvin(self):
        self.kelvin = self.celsius + 273.15
        return self.kelvin

    def to_celcius(self):
        self.celsius = self.kelvin - 273.15
        return self.celsius

Then, I use the following:
deg = Degrees(20) #Set celsius to 20
print ("In Kelvin {0:.3f}.").format(deg.to_kelvin()) #Works
deg.kelvin = 300 #Should alter celsius
print ("New celsius {0}").format(deg.celsius)

The output:
>>>> New celsius 20

For the last print I expect 26.850 (the new Celsius value). Instead, I get 20 (the old). That is, the value celsius has not been updated.
How can I solve this? Any pointers are highly appreciated.

A: You shouldn't store two separate attributes that depend on each other. They are bound to get out of sync. Instead, pick a canonical value to store, and convert to and fro. Since you start with celcius, it probably makes sense to use that throughout.
class Degrees(object):

    def __init__(self, celsius):
        self._celsius = celsius

    #Celsius
    def set_celsius(self, celsius):
        self._celsius = celsius
    def get_celsius(self):
        return self._celsius
    celsius = property(fget=get_celsius, fset=set_celsius)

    #Kelvin
    def set_kelvin(self, kelvin):
        self._celsius = self.to_celsius(kelvin)
    def get_kelvin(self):
        return self.to_kelvin(self._celsius)
    kelvin = property(fget=get_kelvin, fset=set_kelvin)

    def to_kelvin(self, celsius):
        return celsius + 273.15

    def to_celsius(self, kelvin):
        return kelvin - 273.15

A: Change your set_kelvin function to -
def set_kelvin(self, kelvin):
    self._kelvin = kelvin
    self._celsius = self.to_celcius()


text:
Q: Function does not automatically update when values are changed, except first cells in ranges I have created an Excel / VBA function to calculate students marks having the features:

*

*Two ranges are formed through only first cells specified up to Number of cells right:
one for marks_obtained and other for Maximum_marks

*Total Number of subjects to study

*if all cells in Rng1 are blank then returns "_"

*if a single cell in Rng1 has the word "Left" then returns "Left"

*if total number of cells containing marks in Rng1 are less than NUm argumnt then returns "RL"

*if Else: then calculates in two forms i.e. Subtotal if True & Sum if False

All is working but, the problem is:

It does not update automatically as the values are changed on worksheet.

It requires using Ctrl+Alt+F9 or Edit (F2) then pressing Enter.
The honorable experts are requested to assist me thanks.
Function RSLT_N(r1 As Range, r2 As Range, Num As Integer, Level As Integer, Optional Calc_Type As Boolean = False)

Dim i As Byte
        If Level = 1 Then
          i = 40
        ElseIf Level = 2 Then
          i = 45
        Else
          RSLT_N = "Error"
         ' Exit Function
        GoTo L1
        End If

Dim cell1 As Range, cell2 As Range, cell3 As Range, cell4 As Range
Dim Rng1 As Range, Rng2 As Range
    Set cell1 = Cells(r1.Row, r1.Column)
    Set cell2 = Cells(r1.Row, r1.Column + Num - 1)
    Set cell3 = Cells(r2.Row, r2.Column)
    Set cell4 = Cells(r2.Row, r2.Column + Num - 1)

    Set Rng2 = Range(cell3, cell4)
    Set Rng1 = Range(cell1, cell2)

    With WorksheetFunction

        If Check_Left(Rng1) Then
            RSLT_N = "Left"
            GoTo L1

        ElseIf .CountBlank(Rng1) = Num Then
            RSLT_N = "-"

        ElseIf .Count(Rng1) < Num Then
            RSLT_N = "RL"
            GoTo L1
        Else

            For c = 1 To Num
                If Rng1.Cells(1, c) / Rng2.Cells(1, c) * 100 < i Then
                    RSLT_N = "RL"
                    GoTo L1
                End If
            Next

            If Calc_Type = True Then
                RSLT_N = .Subtotal(109, Rng1)
                GoTo L1
            ElseIf Calc_Type = False Then
                RSLT_N = .Sum(Rng1)
                GoTo L1
            Else
                RSLT_N = "Error"
                GoTo L1
            End If

        End If
    End With

L1:
End Function

Function Check_Left(Rng As Range)
    Dim strTextString, Str As String
    Dim btCount As Byte
        btCount = Rng.Cells.Count

            For c = 1 To btCount
                On Error GoTo Last
                Set cl = Rng.Cells(1, c)
                strTextString = strTextString & cl
            Next

    With WorksheetFunction
        On Error GoTo Last
        Str = .IsNumber(.Search("left", strTextString))
    End With

        Check_Left = True
        Exit Function
Last:     Check_Left = False
End Function

A: Have you tried to insert on your code:
application.calculatefull

Hope it works with you.
Andre
p.s. i forgot to mention, there are some calculation methods:
F9 - Recalculate
Application.Calculate

CTRL/ALT/F9 – Full Calculation
In Excel 2000/2002/2003:
Application.CalculateFull

Shift F9 – Sheet Recalculate
Worksheets("SheetName").Calculate

Range Calculate
Range("$a$1:$d$10").Calculate

(I think now it is a more complete answer)


text:
Q: Shadow with Corner radius in cell with IBDesignables I have a 2 sub views in cell. One for shadow view and another for corner radius as it sounds a good approach that I found from this link. So I tried to make it in Objective-C with IBDessignables. Everything works fine if the cell is of same size but for a dynamic size shadow is showing over another cell but the cornerview is fine.
-- View hierarchy of cell --
-- UITableViewCell
  -- contentView
     -- shadowView
       -- CornerView

Here is my code for shadow View
ShadowView.h
IB_DESIGNABLE
@interface ShadowView : UIView
@property (nonatomic) IBInspectable CGFloat cornerRadius;
@property (nonatomic) IBInspectable CGFloat shadowRadius;
@property (nonatomic) IBInspectable CGSize  shadowOffset;
@end

ShadowView.m
@implementation ShadowView

-(void)setup{
    self.cornerRadius = 5.0f;
    self.shadowRadius = 2.0f;
    self.shadowOffset  = CGSizeMake(0, 0);
    self.backgroundColor = [UIColor clearColor];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [self updateLayerProperties];
}

- (void)updateLayerProperties {
    self.layer.shadowOffset = self.shadowOffset;
    self.layer.shadowRadius = self.shadowRadius;
    self.layer.shadowOpacity = 0.3;
    self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:self.cornerRadius].CGPath;
    self.layer.masksToBounds = NO;
    self.layer.shouldRasterize = YES;
    self.layer.rasterizationScale = [UIScreen mainScreen].scale;
}

@end

So does anyone know what the exact issue is? Because the corner view bounds work perfectly but not the shadow view.
Demo File
And here is the demo file if anybody wants to test it .. https://www.dropbox.com/s/myxjyj5pu3ey3aw/demoDesignables.zip?dl=0

A: Views are responsible for drawing content, handling multitouch events, and managing the layout of any subviews.
So, you need to override layoutSubviews function of your ShadowView.
-(void)layoutSubviews {
    [super layoutSubviews];
    [self updateLayerProperties];
}


text:
Q: How to format a big number into string for display in Delphi I have a double type big number, say 1111111111111110000000000000.000. How to format it to string for display in Delphi?
I've tried FloatToStr and FormatFloat, but I receive the Scientific Notation which is not what I want.

A: Using the System.Str conversion works:
var
  d: Double;
  s: String;
begin
  d := 1111111111111110000000000000.000;
  Str(d:0:3,s);
  WriteLn(s);
end;

Outputs: 1111111111111109950000000000.000
Note: double precision has not the precision to exactly hold the digits you are trying to input.
Normally in that case you would not show all digits, since this can give the impression that they all are accurate. This is why the scientific notation is prefered.


text:
Q: MSCRM QueryExpression returning null in UnitTest I am trying to return the first entity that has a value within a value. The only way I can test it is via Unit Testing and they fail every time because its returning null. Not an empty EntityCollection but null. What am I doing wrong here. I just can't see it? ec = null and throws an error when trying to get FirstOrDefault
QueryExpression query = new QueryExpression()
{
    EntityName = "myentity",
    ColumnSet = new ColumnSet(true),
    Criteria = new FilterExpression
    {
        FilterOperator = LogicalOperator.And,
        Conditions =
        {
            new ConditionExpression("myattribute", ConditionOperator.Like, "%" +somevalue+ "%")
        }
    }
};

EntityCollection ec = service.RetrieveMultiple(query);
return ec.Entities.FirstOrDefault();

A: This turned out to be the Unit Test had a Stub of IOrganizationService which was just returning null for the method.


text:
Q: React Router Redirected too many times I have the following Router.jsx, and what I want to accomplish is to have any wildcard redirect back to root level (Home).
i.e. http://xxxxxxx.com/randomPath should redirect to -> http://xxxxxxx.com/
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/home" component={Home} />
    <Route path="/faq" component={Faq} />
    <Route path="/more" component={Faq} />
    <Route path="/signup" component={SignUp} />
    <Route path="/legal" component={Legal} />
    <Route path="/ugc" component={Ugc} />
    <Route path="/pricing" component={Pricing} />

    <Redirect from="*" to='/' />
  </Switch>

However, when testing this out, I'm getting: ERR_TOO_MANY_REDIRECTS
Your help is appreciated, thanks in advance!

A: Normally I'd just set <Redirect to="/" /> (no extra parameters), and it works fine.


text:
Q: Rendering image field in SSRS to fill the page I have an SSRS report that renders image field and description.
When I execute the report, the data will be rendered as two columns, description and image, but I need to view more than one image column per page, i.e. I need it to be as:
image1    image2   image3
image4    image5   image6
image7    image8   image9
image10   image11 image12

in all pages. Is it possible in SSRS?


text:
Q: How do I place 2 SVGs side-by-side within a container and make the container adjust in height? I have two SVGs I want side-by-side within its container:
HTML

  <svg viewBox="100 185 275 655"></svg>
  <svg viewBox="100 185 275 655"></svg>

Another div

CSS
#container{width:100%;}
svg{width:50%;float:left;}

As of now, the div with id anotherdiv will spawn on the exact same place where the container starts. It looks like the container does not care about the height both SVGs bring with them. How can I solve this? Thanks!

A: You have to clear floated elements. Example:

#container {
  width: 100%;
}

svg {
  width: 50%;
  float: left;
}

#anotherdiv {
  background: red;
  clear: both;
}

  <svg viewBox="100 185 275 655"></svg>
  <svg viewBox="100 185 275 655"></svg>

Another div


text:
Q: PHP MVC. Am I doing it correctly? I've created a simple ServiceFactory class, which runs other Service classes, stores and gets instances. The same ServiceFactory object is shared between both the View object and Controller object.
The Controller changes the state of the Service:
class User extends Controller
{
    public function index($user)
    {
        $userService = $this->service->run('User');

        $userService->index($user);
    }
}

The View gets data from the Service and decides which template to use:
class User extends View
{
    public function index()
    {
        $userService = $this->service->get('User');

        $this->data = $userService->data;

        $this->template = 'user/index'; // render
    }
}

Am I doing it correctly?
In this answer tereško said that: "Controller is responsible for changing the state of both View and Model." My Controller has nothing to do with the View. I would like to see some examples of how Controller and View should work (Model2 MVC).

A:
Am I doing it right?

Sort of.
Let's start with extends. When you use extends, you're implying an is-a relationship, so when you say User extends Controller, you're saying that a User is-a Controller. Is that the case? No. Perhaps you could rename to UserController and that would make more sense contextually.

$userService = $this->service->get('User');

This is called a service locator, and it's well known as an anti-pattern. Why is it an anti-pattern? Because in object oriented programming, each object's public methods are an API to it's usage, and you should be able to see an objects requirements entirely from it's constructor and method signatures.
With your code, a developer has to read through the whole thing to see "oh, so here's where I'm using another object" and further down "here's where I'm using another".
Your code should read like this:
public function index(UserService $userService)
{
    $user = $userService->getData();
}

With that code change, developers can see what external objects your object requires to function - and now this is testable (not that you would test your controllers that contain no logic - they're just the 'glue' for your code that is already tested).
You should be injecting your components and the View into the Controller:
class UserController extends Controller
{
    public function index(UserService $userService, View $view)
    {
        /** This or something similar **/
        return $view->render($userService->getData());
    }
}

Some people inject a View, some people inject a TemplateEngine like twig, and called render on that with the data. It's up to you, you can delve more into the specifics given your current scenario.
If you're wondering how you would inject your user service into the index action, that's the job of a dependency injector like Auryn that uses reflection to read object constructor or method signatures to determine what to create before injecting them automatically in your controllers.
Laravel stole the idea and now has that implemented for their controllers, hopefully Symfony will follow along soon.
Closing note: Don't try and strictly adhere to 'MVC' - it's not possible in the classical sense for PHP with the request -> response -> dead cycle. Instead, focus on the separation of concerns associated with it and make your code maintainable, testable and easy to read.

A: In a client-server architectures there is a problem to implement the "original" idea of MVC. In theory the Controller should modify the Model. Than the Model should be liked by e.g. an event with the View to update it.
Example:
I change the state of a user e.g. the firstname by clicking some button. This leads to a action in a controller which updates the User-Model ( a domain model living in the model-layer). Now the Model should "imform" the View to update the firstname of the user. You could use "commet"-architecture ( https://en.wikipedia.org/wiki/Comet_%28programming%29 ) to link the Model to the View. So an update of the User-Model would couse an update of the View.


text:
Q: Push Android artifact to Azure DevOps Feed I am building my Android projects with Azure pipelines, but I'm still copy pasting aar files from libraries to apps. How do I publish my libs in a private package manager, so I can use them in my apps?
With c# / nuget I got this working easily. Feeds seem to support Maven/Gradle, but I don't see how I can push my libs into a feed (builds are successfull). What's the "nuget push" equivalent?
I find alot about how to sign/publish apps, and documentation on how to do it with Xamarin, which uses ... nuget. Do I need to write Grade / Maven stuff myself, eventhough pipeline tasks are all over the place and there's a DevOps for Mobile youtube series (Xamarin)?
Please point me in the direction of some not outdated documentation and/or how I can learn what to put in my yaml files.

A:
Push Android artifact to Azure DevOps Feed

You could use maven new maven-publish plugin with following gradle build config to publish Android artifact to Azure DevOps Feed:
apply plugin: 'maven-publish'

task sourceJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    classifier "sources"
}

publishing {
    publications {
        bar(MavenPublication) {
            groupId 'com.foo'
            artifactId 'bar'
            version '0.1'
            artifact(sourceJar)
            artifact("$buildDir/outputs/aar/bar-release.aar")
        }
    }
    repositories {
        maven {
            url "$buildDir/repo"
        }
    }
}

You could check this thread and this thread for some details.
Hope this helps.

A:
but I'm still copy pasting aar files from libraries to apps

In this case, if you want to publish a set of related files from a pipeline as a single package, you can use Universal Packages hosted in Azure Artifacts feeds.
Universal Packages are created from a directory of files. By default, the Universal Packages task will publish all files in $(Build.ArtifactStagingDirectory). To prepare your Universal Package for publishing, either configure preceding tasks to place output files in that directory, or use the Copy Files utility task to assemble the files that you want to publish.
To publish a Universal Package to your feed, add the following snippet to your azure-pipelines.yml file.
- task: UniversalPackages@0
  displayName: Universal Publish
  inputs:
    command: publish
    publishDirectory: '$(Build.ArtifactStagingDirectory)'
    vstsFeedPublish: '<Feed name>'
    vstsFeedPackagePublish: '<Package name>'
    packagePublishDescription: '<Package description>'

You can refer to this official document for details.


text:
Q: How to apply MICE imputations on test set? I have two separate data sets: one for train (1000000 observation) and the other one for test (1000000 observation). I divided the train set into 3 sets (mytrain: 700000 observations, myvalid: 150000 observations, mytest:150000 observations). Thetest set with 1000000 observations doesn't include the target variable, so it should be used for the final test. Since there are some missing values for categorical variables, I need to use mice to impute them. I should reuse the imputation done on mytrain set to fill the missing values in the myvalid, mytest and test sets. Based on the answer to this question, I should do this:
data2 <- rbind(mytrain,myval,mytest,test)
data2$ST_EMPL <- as.factor(data2$ST_EMPL)
data2$TYP_RES <- as.factor(data2$TYP_RES)

imp <-  mice(data2, method = "cart", m = 1, maxit = 1, seed = 123,
             ignore = c(rep(FALSE, 700000),rep(TRUE, 1300000)))
data2.imp <- complete(imp,1)
summary(imp)

mytrainN <- data2.imp[1:700000,]
myvalN <- data2.imp[700001:850000,]
mytestN <- data2.imp[850001:1000000,]
testN <- data2.imp[1000001:2000000,]

However, since the test set does not have the target column, it is not possible to merge it with mytrain, mytest, and myvalid. Is it possible to add a hypothetical target column (with the value of say 10 for all 1000000 observations) to the test set?


text:
Q: What trig identities are used to solve $4\sin θ\cos θ(\cos^2θ−\sin^2θ)=2\sin(2θ)\cos(2θ)$ I'm trying to follow the answer from this question - Verifying $\sin 4θ=4\cos^3 θ \sin θ - 4\cos θ \sin^3θ$
and I'm referencing the trig identities from the Khan academy website here - https://www.khanacademy.org/math/precalculus/x9e81a4f98389efdf:trig/x9e81a4f98389efdf:using-trig-id/a/trig-identity-reference
but I'm having trouble finding out how the equation $4\sin θ\cos θ(\cos^2θ−\sin^2θ)=2\sin(2θ)\cos(2θ)$ is solved.

A: \begin{align}
\sin4\theta&=2\color{blue}{\sin2\theta}\color{red}{\cos2\theta}\\
&=2(\color{blue}{2\sin\theta\cos\theta})(\color{red}{\cos^2\theta-\sin^2\theta})\\
&=4\sin\theta\cos\theta(\cos^2\theta-\sin^2\theta)
\end{align}
Does this help?


text:
Q: Logstash - Split escape character " \ " is not working I have logstash to check log from window file ; there is many app running on window show I think using the folder to determinate this log come from what app ; but it is not working  and get the exception :

Failed to execute action
  {:action=>LogStash::PipelineAction::Create/pipeline_id:main,
  :exception=>"LogStash::ConfigurationError", :message=>"Expected one of
  \', ', any character at line 21, column 1 (byte 237)

my config
input {
  beats {
    port => 5044
  }
}

filter {
        mutate {
                split => { "source" =>  '\\' }
        }

}
output {
 elasticsearch {
    hosts => ["localhost:9200"]
    sniffing => true
    manage_template => false
    index => mt4log
  }
}

someone can help me find out what is  problem here thanks


text:
Q: Using Multiprocessing on a Collection of DataFrames Setup
I have a multiple datasets each with their own DataFrame. I'm running calculations within them before comparing my results to a separate DataFrame which we can think of as constraints.
For example lets say 2 sets of data in a dictionary:
df_data_1 = pd.DataFrame(np.random.randint(0,50,size=(10, 4)), columns=list('ABCD'))
df_data_2 = pd.DataFrame(np.random.randint(0,50,size=(10, 4)), columns=list('ABCD'))

data_sets = {'data_1': df_data, 'data_2': df_data_2}

and one set of constraints:
df_constraints = pd.DataFrame([['a', 10, 20, 10000000],
                               ['b', 100, 200, 20000000],
                               ['c', 1000, 2000, 30000000]])
df_constraints.columns = ['index', 'sumMin', 'sumMax', 'productMax']
df_constraints.set_index('index', inplace=True)

Visually:
data_set_1
data_set_2
constraints
Function
I'm making calculations within each set of data and then comparing them to a set of constraints. For the sake of simplifying my question I am only comparing the data to the first row of constraints here, but in reality I have to compare the results of my calculations within each data-set to up to 20 sets of constraints.
Here is a simplified version of the function that I am trying to have run in parallel:
def test_func(df_data, df_constraints):
    # Run some calculations
    df = df_data.copy()
    df['sum'] = df.sum(axis=1)
    df['product'] = df.product(axis=1)

    # Compare results to constraints
    df['sumFit'] = ((df['sum'] > df_constraints.loc['a', 'sumMin']) &
                    (df['sum'] < df_constraints.loc['a', 'sumMax']))
    df['productFit'] = df['product'] < df_constraints.loc['a', 'productMax']

    # Analyze results
    count_sumFits = df['sumFit'].sum()
    count_productFits = df['productFit'].sum()

    df_results = pd.DataFrame([['data_set_1', count_sumFits, count_productFits]],
                                columns=['DataSet', 'FittingSums', 'FittingProducts'])
    df_results.set_index('DataSet', inplace=True)

    return df_results

Sequential Version
I can run this function sequentially through each set of data; iterating through the dictionary with a while loop and then append the results as shown here, but with increased complexity this is taking way longer than I would like. (It's ugly but it works)
n=0
while n < len(data_sets):
    data_set_names = list(data_sets.keys())
    df_temp = test_func(data_sets[data_set_names[n]], df_constraints)

    df_all_results.loc[n, 'FittingSums']     = df_temp.loc[0, 'FittingSums']
    df_all_results.loc[n, 'FittingProducts'] = df_temp.loc[0, 'FittingProducts']
    n+=1

The Problem
When I have 25 data-sets and I'm running more complex analysis with more calculations, the run time ends up being minutes long. Leading me to pursue concurrency/multiprocessing. I'm hoping to make this significantly faster as it is one step of many that I'm trying to optimize and then run them all a few thousand times.
So, Multiprocessing...
Due to the need to pass two arguments to the function I've been looking at mp.Pool.starmap, and pool.map(partial(test_func, b=df_constraints), data_sets, but I haven't been able to get either method to work.
ex.1) mp.Pool.starmap
if __name__ == '__main__':
    pool = mp.Pool(processes = 8)
    output = pool.starmap(test_file.test_func, zip(data_sets, itertools.repeat(df_contraints)

This is as far as I've been able to get. Is it possible to process data concurrently like this and then append results to a dataframe? I don't need them to be in any particular order I just want to get the data into the right format.

A: I don't fully understand your code and your logic but replace data_sets by data_sets.values():
if __name__ == '__main__':
    pool = mp.Pool(processes = 8)
    output = pool.starmap(test_file.test_func, zip(data_sets.values(),itertools.repeat(df_contraints)))


text:
Q: Why does my little Flask app with keras and tensorflow backend crash on subsequent image uploads? for an assignment, we did image classifcation with Keras and TF that image classifies dogs vs cats. I wrote a simple Flask app that allows for a demo of uploading a pic and display whether the uploaded image scores dog or cat.
I can run a single upload and that displays nicely, but if I upload another image, I get:
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(3, 3, 3, 32), dtype=float32) is not an element of this graph.

with the line:
  model = load_model('/Volumes/T5_500G/Capstone/v2/flask/models/model_weights.h5')

highlighted in flask debug page
I'm new to this so I'm confused as to how to fix this. Here is my code:
@app.route('/upload_image', methods=['GET', 'POST'])
def upload_image():

    prediction_results = {}
    animals = ['% Cat Score', '% Dog Score']
    animals_scores = []
    imageUrl = ""

    if request.method == 'POST':

        if request.files:
            import keras
            from keras.models import load_model
            from keras import backend as K
            import numpy as np
            model = load_model('/Volumes/T5_500G/Capstone/v2/flask/models/model_weights.h5')
            print(request.files)
            print(request.files['image'].filename)
            imageUrl = "/static/uploads/"+request.files['image'].filename
            image2 = app.config['IMAGE_UPLOADS']+"/"+request.files['image'].filename
            request.files['image'].save(image2)
            img_path = image2
            img = keras.preprocessing.image.load_img(img_path, target_size=(224,224))
            img_array = keras.preprocessing.image.img_to_array(img)
            expanded_img_array = np.expand_dims(img_array, axis=0)
            preprocessed_img = expanded_img_array / 255. # Preprocess the image
            prediction = model.predict(preprocessed_img)
            pred_list = prediction.tolist()
            animals_scores.append(pred_list[0][0])
            animals_scores.append(pred_list[0][1])
            print(prediction_results)

            imageUrl = "/static/uploads/"+request.files['image'].filename
    return render_template('/upload_image.html',imageUrl=imageUrl, animals=animals, animals_scores=animals_scores)

The upload paths are paths on my laptop. I'm hoping to fix this an push to heroku or related.
I've read some posts about clearing the keras session. Is this the issue?
Thanks for any assistance.

A: I've changed your code a bit according to my comment, it should be working now.
import keras
from keras.models import load_model
from keras import backend as K
import numpy as np

model = load_model('/Volumes/T5_500G/Capstone/v2/flask/models/model_weights.h5')

@app.route('/upload_image', methods=['GET', 'POST'])
def upload_image():
    prediction_results = {}
    animals = ['% Cat Score', '% Dog Score']
    animals_scores = []
    imageUrl = ""

    if request.method == 'POST':

        if request.files:

            print(request.files)
            print(request.files['image'].filename)
            imageUrl = "/static/uploads/"+request.files['image'].filename
            image2 = app.config['IMAGE_UPLOADS']+"/"+request.files['image'].filename
            request.files['image'].save(image2)
            img_path = image2
            img = keras.preprocessing.image.load_img(img_path, target_size=(224,224))
            img_array = keras.preprocessing.image.img_to_array(img)
            expanded_img_array = np.expand_dims(img_array, axis=0)
            preprocessed_img = expanded_img_array / 255. # Preprocess the image
            prediction = model.predict(preprocessed_img)
            pred_list = prediction.tolist()
            animals_scores.append(pred_list[0][0])
            animals_scores.append(pred_list[0][1])
            print(prediction_results)

            imageUrl = "/static/uploads/"+request.files['image'].filename
    return render_template('/upload_image.html',imageUrl=imageUrl, animals=animals, animals_scores=animals_scores)```


text:
Q: cordova plugin camera flipped image Very strange for me, occupy the same code in another application if it works on Android reverses the image in -90. Try set correctOrientation = true does not work for me. Someone with the same error and could fix it ??
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
  console.log(imageURI);
  $scope.lastPhoto = imageURI;
   }, function() {
     //error
   }, {
      quality: 75,
     correctOrientation: true
   });
};

A: I think the problem is the resolution of the image depending on the device. What I did was use a parameter that cuts the image after taking a photograph. When cut, the picture came out correctly, but that was not what I needed because it is one step more to add to the flow so remove that parameter, change the image type from PNG to JPEG, identify which platform was the device and image stored correctly.
var options = {
    quality: 50,
    destinationType: Camera.DestinationType.FILE_URI,
    encodingType: Camera.EncodingType.JPEG,
    correctOrientation: true
  };


text:
Q: Stop double click action on a action-column I've a grid panel in extJS 4.1.1. With other columns I've an actioncolumn(xtype:'actioncolumn'). I include a handler with that column. When I click it , it works fine and open a new window with many things loading. But I got error when I double click on that column. Advance welcome for any help.......
{
        text            : 'Signature',
        menuDisabled    : true,
        sortable        : false,
        id              : 'signature',
        xtype           : 'actioncolumn',
        width           : 60,
        items           : [{
            icon        : "${resource(dir: 'images', file: 'ADD01003.png')}",
            tooltip     : 'Add Signature',
            scope       : this,
            handler     : function(grid, rowIndex, colIndex) {
                var records = grid.getStore().getAt(rowIndex).data,
                  fullName    = records.fullName,
                  nickName    = records.nickName,
                  salutation  = grid.getStore().getAt(rowIndex).raw.m00i012001.name,
                  searchValue = records.id ;

                  var filters    = new Array();
                  var store =Ext.data.StoreManager.lookup('S02X004001');
                  store.clearFilter();
                  filters.push({property:'member', value:searchValue});
                  store.loadPage(1, {
                      filters  : filters,
                      callback : function(records, options, success) {
                      var view = Ext.widget('v02x004001');
                      view.show();
                      Ext.getCmp('fullName-sv02x00400104').setValue(fullName);
                      Ext.getCmp('nickName-sv02x00400104').setValue(nickName);
                      Ext.getCmp('member-sv02x00400104').setValue(searchValue);
                      Ext.getCmp('salutation-sv02x00400104').setValue(salutation);
                      }
                  });
            }
        }]
    }

A: Not to resurrect any Zombies, but for anyone having the same Problem in ExtJS 4, 5 or 6 this workaround should work (maybe the Classnames need to be slightly modified, pasted Code is proven to work in 5.1.1).
The trick is to not modify the actioncolumn but to fix the itemdblclick event handler one might have like so:
listeners:
{
    itemdblclick: function(v, record, item, index, e)
    {
        var flyTarget = Ext.fly(e.target);
        if(flyTarget.hasCls('x-action-col-icon') || flyTarget.hasCls('x-grid-cell-inner-action-col'))
        {
            e.stopEvent();
            return;
        }
        //your code here
    }
}


text:
Q: How to create CRAN ready R package that has external dependency libxml2 I have created an R package that I would like to submit to CRAN. It contains code that needs to be compiled in plain C and this code depends on the libxml2 library.
My current solution is to let Linux and Mac users install the libxml2-dev package, which lets them compile and install the R source package.
For Windows, I have created a special binary R-package that contains the required binary dependency. When reading the CRAN guidelines I see that only source packages may be uploaded and that they may not contain any binary files.
After those guidelines, my questions are:

*

*Is it ok for Mac/Linux to have the user install libxml2-dev prior to installing the R package or are there alternative solutions?

*How should I do for Windows where the libxml2 is not straight forward to install for an end user?

A: As mentioned above, you can just copy over what the xml2 package does:

*

*To get things to work on Linux/MacOS, copy the files configure and /src/Makevars.in. Note that macOS includes a copy of libxml2 by default, so you can safely link to -lxml2 as you would do on Linux.

*For Windows need to copy the files src/Makevars.win and tools/winlibs.R from xml2. This is a simple script that automatically downloads and statically links libxml2 from rwinlib when building the R package on Windows.
These build scripts are tested to work on (almost) any platform.


text:
Q: calling executable with system command I'm calling an executable from within  a c++ program via the system() command. Although each call is successful, I run into problems when the c++ code calls the executable many times while running. At that point, the executable takes a lot longer to run than it is supposed to.
I should add that the c++ code where the executable is called from is an optimisation routine. Yet, the executable is only called sequentially. After it finishes the c++ code continues to the next iteration and calls the executable once again with another set of parameters.
Are there any restrictions behind the system command that might be generating this? Is there a maximum number of times you can call it in a short time interval?
Thank you for your help.
MDR.

A: There is no restrictions behind system command, but you can have restrictions from OS. http://blogs.technet.com/b/markrussinovich/archive/2009/07/08/3261309.aspx

A: system calls return immediately - when the command process is launched.  If you make multiple calls in short succession, you could be creating many instances of a process or shell command simultaneously.  This would consume memory and processor resources - thus causing the slowdown.
You want to know the time between system calls when you notice and issue and how long the process or command issued by the system call takes to complete.
if (time to complete > time between calls) then you will be creating multiple instances of the created process


text:
Q: Generating function of binary string Let $A=\{10,101\}$ and $B=\{001,100,1001\}$.Write $AB$ and $BA$ ,determine if they are uniquely created and their generating functions with respect to length.
If $A$ and $B$ are sets of binary string, then $AB= \{ab \}$ where $a$ is in $A$ and $b$ in $B$.
Do you have any idea for generating function ? Or uniqueness part.
Thank you.

A:
We obtain
  \begin{align*}
AB&=\{10,101\}\{001,100,1001\}\\
&=\{10001,10100,\color{blue}{101001},\color{blue}{101001},101100,1011001\}\\
&=\{10001,10100,101001,101100,1011001\}\\
\end{align*}
  with  generating    function
  \begin{align*}
\Phi_{AB}(x)=2x^5+2x^6+x^7
\end{align*}

We see $AB$ is not uniquely created due to $10\cdot1001=101\cdot  001$. The coefficient  $[x^n]$ of the generating function $\Phi_{AB}$ gives the number of words of length $n$.

We obtain
  \begin{align*}
BA&=\{001,100,1001\}\{10,101\}\\
&=\{00110,001101,10010,100101,100110,1001101\}
\end{align*}
  with generating  function
\begin{align*}
\Phi_{BA}(x)=2x^5+3x^6+x^7
\end{align*}

We  see $BA$  is uniquely created and we consequently have $AB\neq BA$. We also have $\Phi_{AB}(x)\neq \Phi_{BA}(x)$.


text:
Q: Classe java com float e int Estou desenvolvendo um projeto MVC com Java para web utilizando eclipse.
Na tabela produto de banco de dados está assim
       create table Produto
(
    Idproduto int identity primary key,
    Nome varchar(40),
    Preco decimal(6,2),
    Categoria int,
    Estoque int

    )

}
Tenho uma classe chamada produto
public class Produto {

private int Idproduto;
private String Nome;
private float Preco;
private int Categoria;
private int Estoque;
public int getIdproduto() {
    return Idproduto;
}
public void setIdproduto(int idproduto) {
    Idproduto = idproduto;
}
public String getNome() {
    return Nome;
}
public void setNome(String nome) {
    Nome = nome;
}
public float getPreco() {
    return Preco;
}
public void setPreco(float preco) {
    Preco = preco;
}
public int getCategoria() {
    return Categoria;
}
public void setCategoria(int categoria) {
    Categoria = categoria;
}
public int getEstoque() {
    return Estoque;
}
public void setEstoque(int estoque) {
    Estoque = estoque;
}
public Produto() {
    super();
    // TODO Auto-generated constructor stub
}
public Produto(int idproduto, String nome, float preco, int categoria, int estoque) {
    super();
    Idproduto = idproduto;
    Nome = nome;
    Preco = preco;
    Categoria = categoria;
    Estoque = estoque;
}

Função inserir produto
public void Inserirproduto(Produto produto) {

        try {
            Connection con = conectar();
            CallableStatement cls = con.prepareCall("{call Inserirprodutoadm(?,?,?,?)}");
            cls.setString(1, produto.getNome());
            cls.setFloat(2, produto.getPreco());
            cls.setInt(3, produto.getCategoria());
            cls.setInt(4, produto.getEstoque());
            cls.execute();
            con.close();
        } catch (Exception e) {
            System.out.println("Erro" + e.getMessage());
        }
    }

Quando chamo essa classe no controller com os tipos de dados int e float ele não reconhece

Como faço para os tipos int e float ser reconhecidos quando chama a classe ?

A: Basta fazer um parse, exemplo:
produto.setPreco(Float.parseFloat(request.getParameter("Preco")); //para Float
produto.setCategoria(Integer.parseInt(request.getParameter("Categoria"))) // Para Int


text:
Q: How do I recognize fast-forward and rewind gestures for an audio player? I'm developing a tvOS application with an audio player, and I need to support fast-forward and rewind using the same gestures as Apple Music and other audio apps. Specifically, to fast-forward, the user presses and holds on the right side of the remote control's touch surface, and to rewind, the user presses and holds on the left side.
I'm creating two UILongPressGestureRecognizer instances, one for fast-forward and one for rewind, and adding them to the view controller's top-level view. For the fast-forward gesture recognizer, I'm setting allowedPressTypes to @[UIPressTypeRightArrow], and for the rewind recognizer, I'm setting allowedPressTypes to @[UIPressTypeLeftArrow]. But these gestures have no effect.
Can anyone provide sample code that implements these gestures properly?

A: Don't set those allowedPressTypes and it will work.  You'll have to determine where the user tapped in your handler, but the gestures will register.


text:
Q: How to make projection to display limited data How to display only limited data into response rather than whole object
  {
        "message": "Records",
        "data": [
            {
                "_id": "5f3ccf2448e5181dc80a70d3",
                "string": "string",
                "records": [
                    {
                        "_id": "5f3ccfc35417491564bbe2z9",
                        "product_id": "5ecd3a93f1314915404xd6ds",
                        "my_detail": {
                            "_id": "5ecc00f97c96f408384d57c4",
                            "active": 0,
                            "status": "pending",
                            "deleted_at": 0,
                            "email": "records@yopmail.com",
                            "password": "$2a$12$7h3mttR8TUlZZKIzQvnVV.1sdfsd56.sdfsdfBOxA6UBkpRBLFVC",
                            "first_name": "Johny",
                            "last_name": "Hales",
                            "createdAt": "2020-05-25T17:31:37.016Z",
                            "updatedAt": "2020-05-25T17:31:37.016Z",
                        }
                    },
                    {
                        "_id": "5f3ccfc35417491564bbe2z9",
                        "product_id": "5ecd3a93f1314915404xd6ds",
                        "my_detail": {
                            "_id": "5ecc00f97c96f408384d57c4",
                            "active": 0,
                            "status": "pending",
                            "deleted_at": 0,
                            "email": "records@yopmail.com",
                            "password": "$2a$12$7h3mttR8TUlZZKIzQvnVV.1sdfsd56.sdfsdfBOxA6UBkpRBLFVC",
                            "first_name": "Steve",
                            "last_name": "harvey",
                            "createdAt": "2020-05-25T17:31:37.016Z",
                            "updatedAt": "2020-05-25T17:31:37.016Z",
                        }
                    },
                ]
            }
        ],
    }

my_detail should display only first_name, last_name and status from my_detail object not to display everything like _id, active email, password an all, tried difference way does not get success please guide.
How to make projection to display limited data
$project : {
    "string":1,
    "records":1,
    "records.my_detail.first_name":1,
    "records.my_detail.last_name" :1,
    "records.my_detail.status" :1

}

A: What you have done was correct, but you have one upper level array data[]. So you need to include it also
db.collection.aggregate([
  {
    $project: {
      "data.records.my_detail.first_name": 1,
      "data.records.my_detail.last_name": 1,
      "data.records.my_detail.status": 1
    }
  }
])

Working Mongo playground

A: Use this if not going for aggregation:
db.collection.find({},
{
_id: 0,
"data.records.my_detail.first_name": 1,
"data.records.my_detail.last_name": 1,
"data.records.my_detail.status": 1
})


text:
Q: Can't Connect to MongoDB on new Azure VM I created a new "Container App" in Azure Portal for MongoDB.  This used the official MongoDB container from Docker Hub and created an Ubuntu 15.04 box.  I have never worked with Docker before.
I am able to SSH into the VM and connect to mongo on the VM. From the ssh session, if I type:

docker ps

I get the following output:
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
a9af4c2e2b95        mongo               "/entrypoint.sh mongo"   34 minutes ago      Up 24 minutes       0.0.0.0:27017->27017/tcp   compose_mongo_1

However, when I try to connect to Mongo from my local box, I get a connection error that says "Failed to connect to ... after 5000 milliseconds, giving up."
At first I thought it was because the port wasn't opened, but I went to the "Network Security Groups" in Azure portal and allowed port inbound TCP traffic on port 27017.
I am still unable to connect. If anyone could help me, I would appreciate it.
Thanks!

A: Ok, A couple of things to keep in mind (and I just tested this end to end, So I am sure it works).

*

*Make sure UFW (Ubuntu Firewall also called Uncomplicated Firewall) denies all forwarded traffic by default, so you need to set it to ACCEPT
sudo nano /etc/default/ufw
Replace
DEFAULT_FORWARD_POLICY="DROP"

With
DEFAULT_FORWARD_POLICY="ACCEPT"

and reload the UFW
sudo ufw reload

*this is how I run my docker Image
docker run -p 27017:27017 imageid &

*Add the endpoint for port 27017 - from your azure portal for this VM (Which you have already done)
this is it, I think you should be all set now...


text:
Q: Syntax error for calculated column I keep getting syntax errors for This calculated column
IF(ISBLANK([First Potential Purchasers Selling Price];"0"; TEXT([First Potential Purchasers Selling Price] - [NBV];"0000000,00"))

im trying to simulate
if(First Potential Purchasers Selling Price == null)
       display 0

       else display (First Potential Purchasers Selling Price - NBV)

any help will be appreciated

A: With the addition of a closing paren for the ISBLANK (just before the first ";") your formula works, at least in locales where ";" is used in place of ",".
=IF(
 ISBLANK( [First Potential Purchasers Selling Price] ) ;
 "0";
 TEXT([First Potential Purchasers Selling Price] - [NBV]; "0000000,00")
)

elsewhere it would look like this:
=IF(
 ISBLANK([First Potential Purchasers Selling Price] ) ,
 "0",
 TEXT([First Potential Purchasers Selling Price] - [NBV], "0000000.00")
)


text:
Q: Why does pressing the return key not trigger a KeyPressEvent in my Gtk.Entry? I have code like this:
    ...

    entry.KeyPressEvent += EntryKeyPressEvent;

    ...
}

void EntryKeyPressEvent(object o, KeyPressEventArgs args)
{
    Console.WriteLine("DEBUG: KeyValue: " + args.Event.KeyValue);
    ...
}

EntryKeyPressEvent is called when most keys are pressed, but not the return key. Why is this?
Edit: It's actually not called when most keys are pressed. Some call it (e.g. uparrow, downarrow, escape), but most do not (e.g. any letter key, return).
For reference, I'm trying to port PyGTK code that looks like this:
    ...

    entry.connect('key_press_event', self.entry_key_pressed)

    ...

def entry_key_pressed(self, widget, event):
    ...

A: I was able to figure it out from this mailing list thread. All I had to do was apply to the ConnectBefore Attribute to the handler method:
[ConnectBefore]
void EntryKeyPressEvent(object o, KeyPressEventArgs args)
{
    Console.WriteLine("DEBUG: KeyValue: " + args.Event.KeyValue);
    ...
}

A: From the PyGTK FAQ:

Keyboard events are handled differently. When your window receives a keyboard event, it is first dispatched to the toplevel window, which will check if it matches any keyboard shortcuts. If the key press doesn't match a shortcut, then the event is dispatched to the child widget that currently has focus.

In short: your Gtk.Entry is not seeing the key-press-event signal because the top-level window is doing something with it (namely, activating the currently selected widget).
A meta-answer: often, searching other languages' GTK docs is surprisingly helpful.

A: Are you trying to validate the input? The focus-out-event fires as focus leaves the entry box - like when the user hits Enter.


text:
Q: Is there a way, within my handler method, to determine which of the subscribed events triggered the handler? Assuming I have an EventListener tagged with more than one named event, or an EventSubscriber that subscribes to more than one event, how can I, within my handler method, determine which of the subscribed events triggered the handler?
In sylius, all the resource events use (a descendant of ) the Generic Event class.
I can see that the event name is not contained within the event class, so how can i establish which of the subscribed events caused the handler to run ?
    public static function getSubscribedEvents()
    {
        return [
            'sylius.order.post_complete' => 'dispatchMessage',
            'sylius.customer.post_register' => 'dispatchMessage',
        ];
    }

UPDATE: I am aware that in this instance i could call get_class($event->getSubject()) and at least know which resource i'm dealing with, I am however looking for a more generic solution that would work in any symfony project.

A: There are more parameters passed to the callbacks than just the event object (you might come across them by calling func_get_args() inside your callback (dispatchMessage) quicker than in the documentation :-)). They're not mandatory but they contain what you might need.
The callback gets called with, as parameters :
- event (the object)
- event name (what you're looking for)
- dispatcher instance
(see https://github.com/symfony/event-dispatcher/blob/master/EventDispatcher.php#L231)
So in your case you can use the following :
public static function getSubscribedEvents()
{
    return [
        'sylius.order.post_complete' => 'dispatchMessage',
        'sylius.customer.post_register' => 'dispatchMessage',
    ];
}

public function dispatchMessage(GenericEvent $event, string $eventName, EventDispatcherInterface $eventListener)
{
    // Here, $eventName will be 'sylius.order.post_complete' or 'sylius.customer.post_register'
}


text:
Q: Are there any integers a and b such that $a^2+b^2 = 10^{100}+3$ I try to find  integers $a$ and $b$ such that $a^2+b^2 = 10^{100}+3$, I try some number without any result

A: hint
$a^2+b^2 $ is odd, so $ a$ and $ b $ have not the same parity.
Assume
$$a=2A \; \text{ and } \; b=2B+1$$
thus
$$4A^2+4B^2+4B=10^{100}+2$$
or
$$2A^2+2B^2+2B=5.10^{99}+1$$
the LHS is even, while the RHS is not.


text:
Q: Swift - Get XML attrributes I am trying to loop through the following example XML using CheatyXML
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.16.0">
<indexes lastModified="1524417436798" ignoredArticles="The El La Los Las Le Les">
<index name="E">
<artist id="14" name="Editors"/>
</index>
<index name="K">
<artist id="27" name="Kings Of Leon"/>
</index>
</indexes>
</subsonic-response>

I have an artist object that contains the artist name and artist ID. My goal is to populate an array of Artists with the relevent information.
I am struggling to loop through the XML correctly though, the code below returns the same artist (Editors) twice. Please help.
func getArtists()->[Artist]{
    var artist = [Artist]()
    //GET SAVED SUBIFY INFORMATION
    let defaults = UserDefaults.standard
    let server:String = defaults.string(forKey: "Server")!
    let username:String = defaults.string(forKey: "Username")!
    let password:String = defaults.string(forKey: "Password")!

    //PARSE XML TO GET VALUE
    let url = URL(string:"\(server)/rest/getIndexes?u=\(username)&p=\(password)&v=1.12.0&c=Subify")
    let parser:CXMLParser! = CXMLParser(contentsOfURL:url!)
    for element in parser["indexes"] {
        var artistAdd = Artist()
        artistAdd.id = parser["indexes"]["index"]["artist"].attribute("id").string!
        artistAdd.name = parser["indexes"]["index"]["artist"].attribute("name").string!
        dump(artistAdd)

    }
    //RETURN VALUE
    dump(artist)
    return artist

}

This is the library I'm using https://github.com/lobodart/CheatyXML

A: In your for loop, you define element as the variable that contains the current element on each iteration:
for element in parser["indexes"] {

...but then inside the loop, you don't use element, you go back to the root of the document, so the library has no way of knowing which element you want, and defaults to giving you the first one:
artistAdd.id = parser["indexes"]["index"]["artist"].attribute("id").string!

I think all you need to do is actually use your loop variable in the loop:
artistAdd.id = element["artist"].attribute("id").string!


text:
Q: copy list into other list I know this is asked many times and i am trying to implement same . I have list below
internal class GenList
{

    public string Col1 { set; get; }
    public string Col2 { set; get; }

}

List<GenList> MainList = new List<GenList>();

I want to copy list into other list and dont want content to change in cloned list if something is changed in main list. So i am trying to do below
List<GenList> cloned = MainList.ConvertAll(GenList => new GenList {});

I dont know what to enter inside those curly braces in above line.

A: Here is a quick deep clone solution via serialization:
[Serializable]
public class GenList
{
    public string Col1 { set; get; }
    public string Col2 { set; get; }

    public GenList DeepClone()
    {
        using (var stream = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, this);

            stream.Position = 0; //reset stream

            var cloned = formatter.Deserialize(stream) as GenList;
            return cloned;
        }
    }

and a test to verify:
[TestClass]
public class DeepCloneTests
{
    [TestMethod]
    public void ReferencesAreNotMaintained()
    {
        var object1 = new GenList() { Col1 = "a", Col2 = "b" };
        var cloned = object1.DeepClone();
        Assert.AreEqual(object1.Col1, cloned.Col1);
        Assert.AreEqual(object1.Col2, cloned.Col2);

        cloned.Col1 = "c";
        cloned.Col2 = "d";

        Assert.AreNotEqual(object1.Col1, cloned.Col1);
        Assert.AreNotEqual(object1.Col2, cloned.Col2);
    }
}

A:
dont want content to change in cloned list if something is changed in main list.

That sounds like you want a deep clone, basically. In other words, creating a new list where each element is a copy of an element in the original list, not just a reference to the same object as the original list refers to.
In your case, that's as simple as:
var cloned = MainList.ConvertAll(x => new GenList { Col1 = x.Col1, Col2 = x.Col2 });

Or with LINQ:
var cloned = MainList.Select(x => new GenList { Col1 = x.Col1, Col2 = x.Col2 })
                     .ToList();

But note that:

*

*If you add a new property, you will need to change this code

*If you add a property of a mutable type, you'd need to clone that too

Options to consider:

*

*Adding a DeepClone() method to GenList, to keep the logic in one place however many places need it.

*Adding a constructor instead: GenList(GenList) which copies appropriately

*Using immutable types instead (e.g. make GenList immutable) at which point shallow clones of collections are sufficient.


text:
Q: LINQ IN type query to get records based on result set of another query UserAuthorizations table has Company per User wise, and I want to get the list of Companies for the Users which are assigned as to them.
        // GET: odata/Companies/GetUserCompanies
        [EnableQuery]
        public IQueryable<UserAuthorization> GetUserCompanies()
        {
            List<int> userCompanyIds = db.UserAuthorizations.Where(u => u.Cwid == this.UserId).Select(s => s.CompanyId).ToList();
            return db.Companies.Where(m => m.Id.ToString().Contains(userCompanyIds));

        }

For above I am getting error like
Cannot convert from 'System.Collections.Generic.List<int>' to 'string'

A: try it
        public IQueryable<Company> GetUserCompanies()
        {
            List<int> userCompanyIds = db.UserAuthorizations.Where(u => u.Cwid == this.UserId).Select(s => s.CompanyId).ToList();
            return db.Companies.Where(m => userCompanyIds.Contains(m.Id));
        }


text:
Q: boost::iostream bzip2_decompressor not decompressing file compressed by bzip2_compressor boost::iostream bzip2_decompressor not decompressing file compressed by bzip2_compressor

A: Here's a simple self-contained example showing it to work:
Live On Coliru
#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <sstream>

namespace io = boost::iostreams;

int main()
{
    std::stringstream ss;

    {
        io::filtering_stream<io::output> of;
        of.push(io::bzip2_compressor{});
        of.push(ss);

        io::copy(std::cin, of);
    }

    std::cout << "Compressed input: " << ss.str().size() << " bytes\n";

    ss.seekg(0ul);
    {
        io::filtering_stream<io::input> if_;
        if_.push(io::bzip2_decompressor{});
        if_.push(ss);

        io::copy(if_, std::cout);
    }
}

On Coliru it shows it compresses itself to 331 bytes, and back again to stdout
Perhaps you are forgetting to flush, have non-binary, whitespace skipping. We can't tell without a SSCCE


text:
Q: IE11 ignores javascript matchMedia event listener I'm using the following Javascript code to capture changes in the width of the viewport, then add an event listener when the viewport crosses a minimum threshold.
 var y=window.matchMedia("(min-width: 500px)");
 y.addListener(changeWidth);
 changeWidth(y);

The code works for all browsers except IE11, which ignores it. The http://caniuse.com site says the window.matchMedia feature is supported by IE11. What gives?

A: I pulled the original piece of code off a website somewhere, but it is a shorthand method and IE11 doesn't recognise it as valid code.
The correct code for all browsers is:
 var y=window.matchMedia("screen and (min-width: 500px)");
 y.addListener(changeWidth);
 changeWidth(y);

I got the original code from the Mozilla website: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia. Beware!


text:
Q: Laravel | LinkedIn Login - '401 Unauthorized' I'm getting another error with my LinkedIn application to be able to login on my website, so I get redirected to the right url, I click on 'Authorize' once I'm on the LinkedIn login page, and I get redirected to a link like this:

http://localhost:8000/login/linkedin/callback?code=XXXXXXXXXXXXXXXXXXXXX...

With the following error:

Client error: POST https://www.linkedin.com/oauth/v2/accessToken resulted in a 401 Unauthorized response: {"error":"invalid_client","error_description":"Client authentication failed"}

I don't understand why because I did a Twitter application to login on my website that works with the same controller, and it's perfectly working.. Here is my SocialAuthController:
public function redirectToProvider($driver)
    {
        if( ! $this->isProviderAllowed($driver) ) {
            return $this->sendFailedResponse("{$driver} is not currently supported");
        }

        try {
            return Socialite::driver($driver)->redirect();
        } catch (Exception $e) {
            // You should show something simple fail message
            return $this->sendFailedResponse($e->getMessage());
        }
    }

public function handleProviderCallback( $driver )
    {
        try {
            $user = Socialite::driver($driver)->user();
        } catch (Exception $e) {
            return $this->sendFailedResponse($e->getMessage());
        }

        // check for email in returned user
        return empty( $user->email )
            ? $this->sendFailedResponse("No email id returned from {$driver} provider.")
            : $this->loginOrCreateAccount($user, $driver);
    }

My routes:
Route::get('login/{driver}', 'Auth\SocialAuthController@redirectToProvider')->name('social.oauth');
Route::get('login/{driver}/callback', 'Auth\SocialAuthController@handleProviderCallback')->name('social.callback');

I checked multiple time that all the data between the services.php and the LinkedIn application matchs exactly.. I can't figure this out.

A: You need to add
'x-li-src'    => 'msdk'

Into headers array in file vendor/laravel/socialite/src/Two/LinkedInProvider.php
Please check this link for more information Android LinkedIn SDK produces unusable access tokens


text:
Q: How do I make the images load after the user zoom in on it, but will not otherwise I am building a mosaic, where the user can  insert their own images, but because I don't want to send every user a million images on load and crash their browser, I want to send one whole image(the mosaic), and after they zoom in, the images in that area will load.
I have very limited experience so I have not tried anything yet.
Here's what I currently have:
def GetImages():
    return ImageInfo.query().order(ImageInfo.location).fetch()
class Home(webapp2.RequestHandler):
    def get(self):
        defaultdatas()
        homepage = the_jinja_env.get_template('/templates/home.html')
        self.response.write(homepage.render({"images":GetImages()}))

      {%for i in images%}

      {% endfor %}

I expect the user to see a beautiful mosaic that when zoomed in to a certain amount(say 70%), the images in that area will load.
Edit: This is the demo website I presented : http://inspired-victor-249919.appspot.com/


text:
Q: how to alter drupal-6 view-2 query I'm trying to update view query using drupal hook_views_pre_execute().
It's updating the query properly but even my query returning only couple of record, in view page it's showing pagination at the bottom but i've set the page limit 10. Can any one advise me how to resolve this issue.
function mymodule_views_pre_execute(&$view)
{
  switch($view->name)
  {
      case 'test_merchandise':
            $view->build_info['query'] = "MY QUERY";
            drupal_set_message($view->build_info['query']);
      break;
  }
}

A: if you want to alter views query then use this method
function modulename_views_query_alter(&$view, &$query){

    if ( $view->name == 'test_merchandise' ) {
        //here you will get the whole $query object and alter only the place you want change
        $query->orderby[0] = "substring(node_data_field_date_field_date_value,1,4) DESC";
        echo "<pre>";print_r($query);echo "</pre>";
    }
}


text:
Q: Creating a batch file to move photo from multiple directories into that directories own subdirectories I am hoping somebody can help me whip up a batch file.
I have a folder with over 800 directories, each directory has a photo.png and a sub-directoryA which contains 3 sub-directories, I need to move the photos from each directory 2 sub-directories down, into sub-directory1
I know a little bit about programming/scripting just not enough lol, I figure it would be some kind of for loop to recursively look through each directory and find every instance of the photo.png and somehow move each one into the sub-directories
For example

> ─Parent
>     ├─────directory1
>     │         ├──sub-directoryA
>     │                  ├──sub-directory1   <──────────│
>     │                  ├──sub-directory2              │
>     │                  ├──sub-directory3              │
>     │         photo.png <────────move this into here──│
>     ├─────directory2
>     │         ├──sub-directoryA
>     │                  ├──sub-directory1   <──────────│
>     │                  ├──sub-directory2              │
>     │                  ├──sub-directory3              │
>     │         photo.png <────────move this into here──│
>     ├─────directory800
>     │         ├──sub-directoryA
>     │                  ├──sub-directory1
>     │                  ├──sub-directory2
>     │                  ├──sub-directory3
>     │         photo.png

A: PowerShell:
$path       = 'c:\parent'
$filter     = 'photo.png'
$DestSubDir = 'subDirectoryA\SubDirectory1'

( gci $path $filter -recurse -depth 1 ) |
    Move-Item -Destination { Join-Path $_.DirectoryName $DestSubDir }

gci
Move-Item
Join-Path

A: Alright, so after googling around I finally found a solution that I will post here for future reference in case anybody else is wanting to do the same thing. I will post the full script and then a breakdown of what each part does.
Just place this batch file in the directory you are working in and it will scan through the directories below it and move the photos, just change up the names of the photo or directories, you can even change the file extension and move around videos, text files, etc :)
Remember use a single % for a CMD window, and 2 %% for a batch file
for /f "tokens=*" %%a in ('dir /b /A:D "*"')
do (
if not exist "%%a\sub-directoryA"
md "%%a\sub-directoryA\sub-directory1"
Echo >-------------------------------------------------------------------<

if exist "%%a\photo.jpg" echo  %%a photo.jpg found.
if exist "%%a\photo.jpg" move "%%a\photo.jpg" "%%a\sub-directoryA\sub-directory1\" >NUL
if exist "%%a\*.jpg" echo  %%a *.jpg found.
if exist "%%a\*.jpg" move "%%a\*.jpg" "%%a\sub-directoryA\sub-directory1\" >NUL
Echo:
)

Echo >-------------------------------------------------------------------<

timeout /t 5 >NUL

.
for /f "tokens=*" %%a in ('dir /b /A:D "*"')

:for /f  Loop command against a set of files
"tokens=*" cause all items to be processed
%%a is a command line parameter, just creates a parameter for each item found
('dir /b /A:D "*"')

/B - Bare format (no heading, file sizes or summary)
/A:D - file attributes in this case it's a Folder
"*" - just denotes all folders
do (
if not exist "%%a\sub-directoryA" md "%%a\sub-directoryA\sub-directory1"

:checks if a folder called sub-directoryA exists against all, if it doesn't it creates it, as well as sub-directory1
if exist "%%a\photo.jpg" echo  %%a photo.jpg found.
if exist "%%a\photo.jpg" move "%%a\photo.jpg" "%%a\aa\artwork\" >NUL

just checks against all files and if the file named is found ECHO displays the message on the screen and then moves it to the designated folder


text:
Q: Central Data Source for all my View Controllers So I have an app with a bunch (like 25+) view controllers.  And these vc's use a lot of data, most of which I could either store locally in the app, or store it on my server.  I would rather store this data on my server to minimize app size, so in order to do that, I read somewhere that the best practice for doing that is to have a data class, which would be a special class that gets all the data from the internet at one time in one place, rather than just getting the individual data as needed, in like viewDidLoad or somewhere similar.  So my question is, is it really better to make a central data source within my app and every class draw from it.  And if so, could you provide an example of how I should set up that class.  For example, how to make it run in the background (I guess a different thread) and how to pass NSDictionarys and NSArrays, etc. from the data source to individual class as needed.  Thanks in advance.  I can clarify if necessary.

A: You are talking about two different topics:

*

*Accessing data from a main source from all the view controllers.

*Accessing data from a server.

The best solution for you would be to create a new class that would hold variables that are used by some different classes. This tutorial explains how to do that - I think this would be one of the best solutions that you'll find on the internet.
For solving the second question, you should also create a class that execute SQLite statements and gets information from a database. You should use SQLite in order to do that, and if you won't like it, you could try to use Core Data, although SQLite in my opinion is much simpler.
This tutorial describes how to do that.
After you've done both of the things you can create an instance of the class that handles the database services for you in the class that shares information between the view controllers, and access that instance from different view controllers.
In the end, you could try to perform tasks like that on different threads. You should try doing it using NSOperationQueue objects - they will do most of the job for you. I suggest reading about them in the developer documentation provided by Apple in order to understand how it works.

A: Based on your replies in the comments, I would recommend this solution:

*

*Transferring data from your server to the device - After downloading
your data from your server, store it into an SQLite database in the
device.

*Accessing your data from your many view controllers - Use Core Data
to access the downloaded data in your database from any of your view
controllers.

If you don't know much about database programming, Core Data is an easy way to start. It encapsulates your tables into classes that you access like simple objective-c classes, so you don't have to learn SQL. You can also call them from any and all of your view controllers, whenever you need them, so you don't have to make a special class to handle your data. It is also better performance-wise and cleaner design-wise than passing your data through your view controller hierarchy. See the guide here.


text:
Q: Constants and Variables I'm curious about a rather simple terminology question: is there an umbrella term for constants and variables? Of course, a constant does not change while a variable can, but is there a term referring simply to using a symbol to represent a value? The closest I can think of is value, but value is normally used to mean the number being represented by a constant of variable.

A: Since Algebra uses letters to represent numbers that can vary, those letters are called variables. Some letters can be designated as constants, since their values remain constant, once assigned. Often letters are used as constants simply for the sake of convenience over using a large or complex number.
So I would simply call using a symbol to represent a value a variable in its simplest terms as the variable a for example can be used throughout an equation but can be changed in one place to a different number and so this makes it easier than simply having to write the same number in numerous places as this can cause errors.
So in short in its simplest terms  a symbol used to represent a number is called a variable.

A: Unfortunately, I think the most common word that encompasses what you mean by both constants and variables is "variable". While some high school algebra references distinguish variables from constants (e.g. this page), it's common in other contexts for "variable" to be use for any letter/symbol that stands for a number (and occasionally even that requirement is dropped).
In a context like Calculus, variables (in this broader sense) might stand for "constants", or they might be "independent" or "dependent" variables. The text on Wikipedia at the time of this writing is fairly inconsistent and may not perfectly represent consensus in math, but this Wikipedia section regardless serves as evidence that the word "variable" can be used for your "constants".
Note that the $\pi$ in "$\pi\approx 3.14$" is unlikely to be considered a variable, even though $\pi$ is a mathematical constant.


text:
Q: If $ab+bc+ca \geq 3k^2-1$, prove that: $a^3+b^3+c^3-3abc \geq 9k$.
If $ab+bc+ca \geq 3k^2-1$, prove that: $a^3+b^3+c^3-3abc \geq 9k$.

I recently came across a question in which we had to prove the above inequality using the given condition as mentioned above. Here $a,b,c$ are distinct positive integers and $k$ is also a positive integer. I absolutely have got no idea how to solve it or efficiently use the condition 'positive integers'. Furthermore, although the expression $a^3+b^3+c^3-3abc$ seems a bit familiar but I'm not able to understand how to make the condition useful.
Please help.

A: From $\displaystyle a^2+b^2+c^2-ab-bc-ca=\frac{1}{2}\bigg[(a-b)^2+(b-c)^2+(c-a)^2\bigg]\geq 3.$
Because $a,b,c$ are distinct integers.
So here we have taken $a,b,c$ as $3$ consecutive integers.
And $\displaystyle (a+b+c)^2-3(ab+bc+ca)\geq 0\Rightarrow (a+b+c)^2\geq 3(ab+bc+ca)=3(3k^2-1)$
So $\displaystyle (a+b+c)\geq \sqrt{9k^2-3}$
So we have taken $(a+b+c)\geq 3k.$
So we have $\displaystyle a^3+b^3+c^3-3abc\geq 3\cdot (3k)=9k.$
Equality hold when $a,b,c$ are $3$ consicutive posotive  integers
Namely we have taken  $k-1,k,k+1$

A: Use that $$a^3+b^3+c^3-3abc=\left( a+b+c \right)  \left( {a}^{2}-ab-ac+{b}^{2}-bc+{c}^{2}
 \right)
$$