text:
Q: cassandra get all records in time range I have to work with a column family that has (user_id, timestamp) as key. In my query I would like to fetch all records in a given time range independent of the user_id. This is the exact table schema:
CREATE TABLE userlog (
  user_id text,
  ts timestamp,
  action text,
  app_type text,
  channel_name text,
  channel_session_id text,
  pid text,
  region_id text,
  PRIMARY KEY (user_id, ts)
)

I tried to run
SELECT * FROM userlog  WHERE ts >= '2013-01-01 00:00:00+0200' AND  ts <= '2013-08-13 23:59:00+0200' ALLOW FILTERING;

which works fine on my local cassandra installation containing a small data set but fails with
Request did not complete within rpc_timeout.

on the productive system containing all the data.
Is there a, preferably cql, query that runs smoothly with the given column family or de we have to change the design?

A: It appears the hotness for being able to query by time (or any range) is to specify some "other column" as your Partition key, and then specify timestamp as a "clustering column"
CREATE TABLE postsbyuser (
     userid bigint,
     posttime timestamp,
     postid uuid,
     postcontent text,
     PRIMARY KEY ((userid), posttime)
   ) WITH CLUSTERING ORDER BY (posttime DESC);

insert fake data
  insert into postsbyuser (userid, posttime) values (77, '2013-04-03 07:04:00');

and query (the important part being that it is a "fast" query and ALLOW FILTERING is not required, which is how it should be):
  SELECT * FROM postsbyuser where userid=77 and posttime > '2013-04-03 07:03:00' and posttime < '2013-04-03 08:04:00';

You can also use tricks to group by day (and thus be able to query by day) or what not.
If you use the "group by day" style trick then a secondary index would also be an option (though secondary indexes seem to only work with "EQ" = operator?).

A: The timeout is because Cassandra is taking longer than the timeout (default is 10 seconds) to return the data. For your query, Cassandra will attempt to fetch the entire dataset before returning. For more than a few records this can easily take longer than the timeout.
For queries that are producing lots of data you need to page e.g.
SELECT * FROM userlog WHERE ts >= '2013-01-01 00:00:00+0200' AND  ts <= '2013-08-13 23:59:00+0200' AND token(user_id) > previous_token LIMIT 100 ALLOW FILTERING;

where user_id is the previous user_id returned. You will also need to page on ts to guarantee you get all the records for the last user_id returned.
Alternatively, in Cassandra 2.0.0 (just released), paging is done transparently so your original query should work with no timeout or manual paging.
The ALLOW FILTERING means Cassandra is reading through all your data, but only returning data within the range specified. This is only efficient if the range is most of the data. If you wanted to find records within e.g. a 5 minute time window, this would be very inefficient.

A: In general, this may be an indication that you've not modelled your schema to suit your data query, which is the Cassandra way of doing things (https://docs.datastax.com/en/cql/3.3/cql/ddl/dataModelingApproach.html)...
So, ideally, you'd model your schema to suit the query. There are some resources around on how to do time series modelling for Cassandra, although e.g. this slideshare seems to be similar to what you've got - but it's not advertising support for the kind of query you want to do. I don't think I've actually found examples of Cassandra schemas that support "get me all data for a certain time range" queries.
In any case, for the rest of this answer I'll assume you're stuck with the schema you've got for this iteration.
You can do this as two queries:
SELECT DISTINCT user_id FROM userlog;

And then, for each user,
SELECT * FROM userlog WHERE
  user_id='<user>'
  AND ts >= '2013-01-01 00:00:00+0200'
  AND ts <= '2013-08-13 23:59:00+0200';

If the set of user IDs is small to medium sized, you might be able to get away with using an IN query:
SELECT * FROM userlog WHERE
  user_id IN ('sampleuser', 'sampleadmin', ...)
  AND ts >= '2013-01-01 00:00:00+0200'
  AND ts <= '2013-08-13 23:59:00+0200';

Note that this works without ALLOW FILTERING.


text:
Q: Grouping elements based on sec value using xslt 2.0 I have elements in sequential order. I need to group the elements based on sec value. Below I mentioned my input.

    <title>first</title>
    <entry><sec>s 2</sec>
<text>some text 1</text>
</entry>
    <entry><sec>s 3</sec>
<text>some text 2</text>
</entry>

section title

<entry><sec>Sh 1</sec>
<text>some text 3</text>
</entry>
    <entry><sec>Sh 1Pt 2</sec>
<text>some text 4</text>
</entry>
    <entry><sec>Sh 1item 1</sec>
<text>some text 5</text>
</entry>
    <entry><sec>s 8</sec>
<text>some text 2</text>
</entry>
    <entry><sec>s 9</sec>
<text>some text 2</text>
</entry>
    <entry><sec>Sh 2item 2</sec>
<text>some text 10</text>
</entry>
    <entry><sec>Sh 2</sec>
<text>some text 20</text>
</entry>

I am expecting the below output.

<title>first</title>
    <entry><sec>s 2</sec>
<text>some text 1</text>
</entry>
    <entry><sec>s 3</sec>
<text>some text 2</text>
</entry>

section title

    <group>
    <entry><sec>Sh 1</sec>
<text>some text 3</text>
</entry>
    <entry><sec>Sh 1Pt 2</sec>
<text>some text 4</text>
</entry>
    <entry><sec>Sh 1item 1</sec>
<text>some text 5</text>
</entry>
    </group>
    <entry><sec>s 8</sec>
<text>some text 2</text>
</entry>
    <entry><sec>s 9</sec>
<text>some text 2</text>
</entry>
    <group>
    <entry><sec>Sh 2item 2</sec>
<text>some text 10</text>
</entry>
    <entry><sec>Sh 2</sec>
<text>some text 20</text>
</entry>
    </group>

Please try to help me.

A: You can try:
<xsl:template match="body">

    <xsl:for-each-group select="entry"
        group-adjacent="starts-with(sec, 'Sh ')">
        <xsl:choose>
            <xsl:when test="current-grouping-key()">
                <group>
                <xsl:copy-of select="current-group()"/>
                </group>
            </xsl:when>
            <xsl:otherwise>
                    <xsl:copy-of select="current-group()"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:for-each-group>

</xsl:template>

Output

    <entry><sec>s 2</sec>
<text>some text 1</text>
</entry>
    <entry><sec>s 3</sec>
<text>some text 2</text>
</entry>
    <group>
    <entry><sec>Sh 1</sec>
<text>some text 3</text>
</entry>
    <entry><sec>Sh 1Pt 2</sec>
<text>some text 4</text>
</entry>
    <entry><sec>Sh 1item 1</sec>
<text>some text 5</text>
</entry>
    </group>
    <entry><sec>s 8</sec>
<text>some text 2</text>
</entry>
    <entry><sec>s 9</sec>
<text>some text 2</text>
</entry>
    <group>
    <entry><sec>Sh 2item 2</sec>
<text>some text 10</text>
</entry>
    <entry><sec>Sh 2</sec>
<text>some text 20</text>
</entry>
    </group>

A: If you don't want to wrap the items if there is only one item in a group then use
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

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

     <xsl:template match="body">
       <xsl:copy>
                  <xsl:for-each-group select="entry" group-by="sec/text()[1]">
                    <xsl:choose>
                        <xsl:when test="current-group()[2]">
                            <group>
                              <xsl:apply-templates select="current-group()"/>
                            </group>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:apply-templates select="."/>
                        </xsl:otherwise>
                    </xsl:choose>
                </xsl:for-each-group>
       </xsl:copy>

       </xsl:template>
</xsl:transform>

http://xsltransform.net/pNmBy2c

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django - How to use decorator in class-based view methods? I am developing a site with django 1.8. This is an example of one of the Views:
class ProfileView(View):
    template_name = 'index.html'

    # Return profile of any role (client/employee/admin)
    # Login required
    def get(self, request, *args, **kwargs):
        try:
            profile = Profile.objects.get(user=request.user)
            agency = None

            if request.user.is_employee():
                employee = EmployeeProfile.objects.get(profile=profile)
                agency = employee.agency

            if request.user.is_manager():
                agency = Agency.objects.get(manager=request.user)

        except (Profile.DoesNotExist, EmployeeProfile.DoesNotExist, Agency.DoesNotExist) as e:
            return HttpResponseRedirect('/404')

        return render(request, self.template_name, {"profile": profile, "agency": agency})

    # Client sign up
    # No decorator is needed
    def post(self, request):
        sign_up = SignUpForm(request.POST, request.FILES)

        response = json.loads(utils.create_user(sign_up,request.POST['avatar']))
        if response['profile'] is None:
            return JsonResponse({"code": 400, "response": response['message']})
        profile = serializers.deserialize("json", response['profile']).next().object

        group = Group.objects.get(name='clients')
        profile.user.groups.add(group)

        return HttpResponseRedirect('/')

The question is, can I have different decorators according to the type of request that is made to a controller (view)?

A: You can override dispatch method and call different decorators based on type of request:
from django.utils.decorators import method_decorator

class ProfileView(View):
    ...

    def dispatch(self, *args, **kwargs):
        dispatch_method = super(ProfileView, self).dispatch

        if self.request.method == 'GET':
            dispatch_method = method_decorator(my_get_decorator)(dispatch_method)
        elif self.request.method == 'POST':
            dispatch_method = method_decorator(my_post_decorator)(dispatch_method)

        return dispatch_method(*args, **kwargs)

A: Some decorators like never_cache can be used in the urls.py in stead of the old way: in views.py
e.g. the never_cache decorator:
in the old style views.py:
from django.views.decorators.cache import never_cache

@never_cache
def oldstyle_view(request):
    # and so on

when using class based views, in urls.py:
from django.views.decorators.cache import never_cache

urlpatterns = patterns('',
     (r'someurl/^$', never_cache(SomeClassBasedView.as_view())),
)

Edit 1st aug 2015
Note: this can be handy for those views where you do not have a complete view defined in views.py, otherwhise the decorator can be applied to the depatch method in the view as well.

A: You need to apply the decorator to the dispatch method of the class based view. This can be done as follows:
class ProfileView(View):

    @youdecorator
    def dispatch(self,request,*args,**kwargs):
        return super(ProfileView,self).dispatch(request,*args,**kwargs)
    //Rest of your code.

A: Since Django 1.9, as per the docs, it is possible to apply decorator in the next way:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class YourClassBasedView(TemplateView):
    ...

where name is the name of the method to be decorated.
or in case of few decorators:
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.utils.decorators import method_decorator

decorators = [never_cache, login_required]

@method_decorator(decorators, name='dispatch')
class YourClassBasedView(TemplateView):
    ...

A: There is a very simple solution to achieve what you want, and it doesn't implies decorating dispatch method. You must use the method_decorator over your methods (get/post) and pass the decorator call (not the decorator itself) as a parameter.
In your case it would be:
from django.utils.decorators import method_decorator

class ProfileView(View):
    template_name = 'index.html'

    # Return profile of any role (client/employee/admin)
    @method_decorator(login_required())
    def get(self, request, *args, **kwargs):
        ...

    # Client sign up
    # No decorator is needed
    def post(self, request):
        ...

Note the parethesis in the login_required decorator.
You can pass any function-oriented decorator, even a custom one. For instance:
def white_list_check():
    def decorator(func):
        def wrapper(request, *args, **kwargs):
            ip = request.META.get('REMOTE_ADDR', '0.0.0.0')
            if ip in WHITE_LIST:
                return func(request, *args, **kwargs)
            else:
                return HttpResponseForbidden()
        return wrapper
    return decorator

And then, again:
class YourView(View):

    @method_decorator(white_list_check())
    def get(self, request):
        ...


text:
Q: ASP.NET Core DataProtection master key from environment variables I am trying to set up the Data Protection on a distributed environment so that the same keys would be used in multiple instances. I want the users to be able to decrypt the cookies despite the server instance they are hitting. External key storage like Redis/Azure Storage or storing data protection keys to a database is not an option in our case.
Is there a simple way to set the master key from the environment variables? In our case, we want to be able to specify the keys using Kubernetes.


text:
Q: Attach tooltip to just the div with class I want to attach the tooltip just the div with the class hello, if I hover over the span, the tooltip is getting attached to the span element and its just stuck over there and not getting destroyed.
What am I missing here

    Hello

$('.hello').hover(function(e){
    $(this).tooltip({
        content: function(callback) {
            callback("hello");
        },
        items: '*'
    }).tooltip("open");
}, function() {
    $(this).tooltip('destroy');
});

fiddle

A: Firstly thank you for providing a fiddle
Secondly, the Tooltip initialization code apply's mouseover/mouseleave events to the element so you don't need to embed it in a "hover" method
And if you wish to only show the Tooltip once, then destroy it so it will not show again, use the Close method i.e.
$('.hello').tooltip({
    content: function(callback) {
        callback("hello");
    },
    items: '*',
    close: function( event, ui ) {
         $( this ).tooltip( "destroy" );
    }
})

See http://jsfiddle.net/sjmcpherso/n8kjdzgc/ for working example


text:
Q: How to prove that the KL divergence is increasing with more noise Assume I have a continuous random variable $X$, whose support is all $\mathbb R$. Let $Z$ be a standard normal independent on $X$, and let
$$Y = X + \sigma Z$$
$Y$ essentially is equal to $X$ plus "random noise". Clearly, its pdf is $f_Y = (f_X * \varphi(x, \sigma))(x)$ where $\varphi(x, \sigma)$ is the pdf of $\sigma Z$.
Let $$D_{KL}(\sigma) = D_{KL}(X \mid Y) = \int_\mathbb R f_X(x) \log\frac{f_X(x)}{f_Y(x)}dx$$
be the Kullback-Leibler divergence between $X$ and $Y$. It's immediate to see that $D_{KL}(\sigma) > 0$ for $\sigma > 0$ and $D_{KL}(0) = 0$. I would like to prove that $D_{KL}(\sigma)$ is increasing with $\sigma$. This seems reasonable; the KL divergence is a measure of how "divergent" the two distributions are, and with bigger $\sigma$ we add more noise, hence I would expect the KL divergence to increase. I am struggling to prove this, do you have any ideas?
Thoughts
Some numerical analysis suggests that is true (I tried when $X$ is a normal, a student t, and a member of the stable distribution for different combination of parameters). These analysis even suggest that $D_{KL}(\sigma)$ is convex in $\sigma$.
I can't seem to prove it though. I tried to use the data processing inequality and the chain rule for KL divergence (the formula that uses the conditional KL divergence) but with little luck.
Note that a straightforward differentiation with respect to $\sigma$ yields
$$\frac{\partial D_{KL}(\sigma)}{\partial \sigma} = -\sigma \int_\mathbb R f_X(x) \frac{f_Y''(x, \sigma)}{f_Y(x, \sigma)}dx$$
But proving that this term is positive is not so easy ($'$ indicates the derivative with respect to $x$) It may help to notice that $\int_\mathbb R f''_Y(x, \sigma) dx = 0$, but I haven't really made any progress with this either.


text:
Q: Prove that for any multiplicative arithmetic function $\phi$ we have $\phi(1) = 1$. Prove that for any multiplicative arithmetic function $\phi$ we have $\phi(1) = 1$.
I know there is a clever way to prove this by it is not coming to mind.
Definition: An arithmetic function $f : \mathbb{N} \rightarrow C$ is called multiplicative, if $f \neq 0$, and for every two natural numbers $m, n \in \mathbb{N},  \gcd(m, n) = 1$, and
$f(mn) = f(m)f(n)$.

A: Usually one requires that $\phi(1)\neq 0$ (for example, see Landau's Lectures). Then $\phi(1)=\phi(1\cdot 1)=\cdots$ does it.
Note that if $\phi(1)=0$, $\phi(n)=0$ for any $n$ since $(n,1)=1$, i.e.$\phi(n)=\phi(1)\phi(n)=0$, so asking $\phi\neq 0$ is the same as asking $\phi(1)\neq 0$, which is equivalent to asking $\phi(1)=1$.


text:
Q: "Your file was not found" error appears when I click a button in an HTML form I am new to HTML and javascript.
I am writing a basic form that (for now) is supposed to take the names of "male staff members" and "female staff members" entered by the user, and show a list of each once a button is pressed. Initially, the button seemed to be working, and a list of both male and female staff members was displayed beneath the form. I'm not sure what I did to change this, but now when I press the button, I get an error page with "your file was not found."
Here is the HTML form that contains the button:
    <form method="post" action="new_ele2.php" id = "form1">

            Add New Male Name

             Enter male staff names (click 'add new' for each new name):

                    <input type="text" name="feedName[]" value="" size="50">

            Add New Female Name

             Enter female staff names (click 'add new' for each new name):

            <button onclick="validate(this)">Submit names</button>

    </form>

And here is the javascript "validate" function being called by the button:
function validate(frm) {
    var ele = frm.elements['feedName[]'];
    var eleList = [];
    if (! ele.length) {
        //alert(ele.value);
    }
    for(var i=0; i<ele.length; i++) {
        eleList[i] = ele[i].value;
    }

    var ele1 = frm.elements['feedName1[]'];
    var eleList1 = [];
    if (! ele1.length) {
        //alert(ele.value);
    }
    for(var j=0; j<ele1.length; j++) {
        eleList1[j] = ele1[j].value;
    }
    document.getElementById("testing").innerHTML = eleList;
    document.getElementById("testing1").innerHTML = eleList1;
    return false;
}


text:
Q: NHibernate: Discriminators without inheritance I have the following model:
public class SomeObject1 {
  public virtual Guid Id {get; set; }
  public string Property1 {get; set; }
}
public class SomeObject2 {
  public virtual Guid Id {get; set; }
  public string Property2 {get; set;}
}

and the table
SOME_OBJECTS
  PK_SOME_OBJECTS Guid
  WHICH_OBJECT Integer
  PROPERTY1 varchar2
  PROPERTY2 varchar2

when the WHICH_OBJECT column = 1 the row contains information for SomeObject1, when the WHICH_OBJECT column = 2 the row contains information for SomeObject2.
How would I go about doing these mappings?  I've found the discriminator feature but it seems to only apply when you have subclasses in an inheritance hierarchy.

A: I'm pretty sure it's not possible to map two unrelated entities to the same table; however, you may be able to map them to two different views that reference the same table.


text:
Q: extract digits from string in Obj-C I'm new to Objective-C, but experienced in other higher languages. I want to normalize a string by removing all non-numeric characters. In other words given the input string "206-555-1212" the normalized result should be "2065551212". The code snippet below works, but given my experience in other languages that seems like overkill. Is there a better way to do it?
EDIT: The input strings "(206) 555-1212", "206.555.1212", "206 555 1212", etc. should also return the same normalized result.
NSString * normalize(NSString * number)
{
    NSString *normalizedNumber = @"";
    NSString *tmpString = nil;

    NSRange searchRange;
    NSRange resultRange;
    searchRange.location = 0;
    searchRange.length = number.length;

    while (0 < searchRange.length)
    {
        resultRange = [number rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]
                                        options:NSLiteralSearch
                                          range:searchRange];
        tmpString = [number substringWithRange:resultRange];
        normalizedNumber = [normalizedNumber stringByAppendingString:tmpString];
        searchRange.location = resultRange.location + resultRange.length;
        searchRange.length = number.length - searchRange.location;
    }

    return normalizedNumber;
}

A: All of these answers don't address the "removing all non-numeric characters" part of the question. Here's a simple way to do it:
NSString *normalize(NSString *number) {
    NSMutableCharacterSet *nonNumberCharacterSet = [NSMutableCharacterSet decimalDigitCharacterSet];
    [nonNumberCharacterSet invert];

    return [[number componentsSeparatedByCharactersInSet:nonNumberCharacterSet] componentsJoinedByString:@""];
}

A: Resh32 suggests this code in their answer to a similar question:
NSString * val = @"(555) 555-555 Office";
NSString * strippedNumber = [val stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [val length])];
NSLog(@"%@", strippedNumber);

A: I have a little helper method for this:
+ (NSString *)strip:(NSString *)str keep:(NSString *)chars {
    NSCharacterSet *cs = [NSCharacterSet characterSetWithCharactersInString:chars];
    NSMutableString *res = [NSMutableString stringWithString:str];
    for (int i = [res length] - 1; i >= 0; i--) {
        if (![cs characterIsMember:[res characterAtIndex:i]]) {
            [res deleteCharactersInRange:NSMakeRange(i, 1)];
        }
    }

    return res;
}

It can be called like this:
NSString *cleanString = [UtilityClass strip:originalString keep:@"0123456789+*#"];

A: Even this one will work:
NSString *s = @"234-1243-123";
NSString *ss=[[s componentsSeparatedByString:@"-"] componentsJoinedByString:@""];

A: One option would be creating an NSFormatter subclass to encapsulate the logic, or use an open source one. PhoneNumberFormatter looks promising, and lets you remove formatting as follows:
PhoneNumberFormatter *formatter = [[PhoneNumberFormatter alloc] init];
id objectValue;
NSError *error;
[formatter getObjectValue:&objectValue forString:@"1 (234) 567-8900" errorDescription:&error];
// objectValue = @"12345678900"

A: This depends on your specific goal.
If you are really certain that all of your input will be of the form xxx-xxx-xxxx, this is the same basic question as removing all the whitespace form a string (with answers similar to those already posted), only instead of removing whitespace you are removing the - character. Summary: use -[NSString stringByReplacingOccurrencesOfString:withString:] (-[NSString componentsSeparatedByCharactersInSet:] is slight over-kill in this case, but may be sufficient to use in place of the NSScanner technique below).
If you are trying to sanitize phone numbers with an arbitrary format, the approach you're using is reasonable, however it would be slightly more idiomatic to use an NSScanner as described in the answer to "Remove all but numbers from NSString". Also note that if you're building up a string (as your code is), it is far more efficient to use an NSMutableString and -appendString: rather than -[NSString stringByAppendingString:].
rmaddy's approach is also a good one here, with the caveat that it would probably make the most sense as a category on NSString with a name that follows Apple's conventions.
Note that none of these techniques will validate a phone number, only naïvely pull the base-10 digits from a string.
The most robust solution would be to use some form of dedicated phone number detector (a la Stuart's linked PhoneNumberFormatter).
However, if what you want to do is identify and extract phone numbers without necessarily normalizing your data, Apple provides a class, NSDataDetector, that can be configured for this purpose. A simple example would look like this:
NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];

if(!detector) {
   NSLog(@"Error creating phone number detector: %@", [error localizedDescription]);
   return;
}

NSString *phoneNumberString = @"(555) 555-5555";

NSArray *matches = [detector matchesInString:phoneNumberString
                             options:0
                               range:NSMakeRange(0, [phoneNumberString length])];

if([matches count] < 1) {
   NSLog(@"No phone numbers found!");
   return;
}

NSTextCheckingResult *match = [matches lastObject];
if([match resultType] != NSTextCheckingTypePhoneNumber) {
    NSLog(@"Matched something, but not a phone number!");
    return;
}

NSString *phoneNumber = [match phoneNumber];
NSLog(@"Matched phone number: %@", phoneNumber);


text:
Q: Code optimization tool Would it be possible to develop a program that could optimize algorithms, detect design patterns and then rewrite the code? For example:

*

*Detect a Bubble sort and transform it into a Quick sort or a Merge sort

*Replace unnecessary repetitions of instances of a class into a Singleton

*Refactor similar functions into a more generic one that accepts
parameters

This program should be applicable to the sources of any programming language through configuration files containing the various rules such as grammar

A: No, this is not possible.
Deciding whether a program performs a certain algorithm (e.g. bubble sort) is equivalent to solving the Halting Problem, and thus undecidable.
Deciding whether two programs compute the same function is equivalent to solving the Halting Problem, and thus undecidable. Deciding whether they perform a "similar" function will have similar problems.

A: Firstly, this is impossible in general due to the halting problem, as already stated.
Secondly, if it were possible, I wouldn't let such an optimizer do any of the things you suggest, so it's far from obvious that it would be any use.

Detect a Bubble sort and transform it into a Quick sort or a Merge sort

This is a terrible idea. Bubble sort is faster than either quicksort or mergesort for sufficiently small inputs, it just scales up poorly. The programmer is better-placed to know the expected input size than a code analyzer.

Replace unnecessary repetitions of instances of a class into a Singleton

Knowing when this is the correct thing to do requires understanding intent. It's not obvious how this will be visible in the code. Perhaps a singleton would be semantically correct, but I have chosen to keep one instance per thread for cache reasons. Perhaps I want to keep one instance for myself, and another one will later be shared with a dynamically-loaded library which is not visible at source analysis time.

Refactor similar functions into a more generic one that accepts parameters

So now I have to also let it rewrite all my unit tests and trust that both the code and tests remain correct. And the generalized function will now put more pressure on my instruction cache and branch predictors, so may well perform worse.

A: Optimizing compilers perform program transformations every day, but they don't do it at the source level, and they need to do it in a semantics-preserving way. For example, loop unrolling and strength reduction are common techniques (which could even be applied to source code but may hamper readability.)
Refactoring can be done using tool support both in identifying places that might benefit from refactoring and in applying source code transformations. However, the decision and responsibility for the refactoring normally stays with the developers. In many cases, proving that a refactoring preserves the code's semantics is harder to do, and it's often a subjective judgement whether code is better readable and maintainable after such a refactoring.


text:
Q: Create Bezier Curve in Objective C using Paul de Casteljau algorithm I am trying to use Paul de Casteljau algorithm to draw Bezier Curve for my homework, but it seems it is not perfect, here are the codes

- (void)recursive_bezier :(double)x1 :(double)y1
                         :(double)x2 :(double)y2
                         :(double)x3 :(double)y3
                         :(double)x4 :(double)y4
{

  count = count+1;
  // Calculate all the mid-points of the line segments
  //----------------------
  double x12   = (x1 + x2) / 2;
  double y12   = (y1 + y2) / 2;
  double x23   = (x2 + x3) / 2;
  double y23   = (y2 + y3) / 2;
  double x34   = (x3 + x4) / 2;
  double y34   = (y3 + y4) / 2;
  double x123  = (x12 + x23) / 2;
  double y123  = (y12 + y23) / 2;
  double x234  = (x23 + x34) / 2;
  double y234  = (y23 + y34) / 2;
  double x1234 = (x123 + x234) / 2;
  double y1234 = (y123 + y234) / 2;

  if(isFlat)
  {
    //    // Draw and stop
    //    //----------------------
    [self drawLine:x1 :y1 :x4 :y4];

  }
  else
  {
    // Continue subdivision
    //----------------------
    if (count == 5) {
      isFlat=true;
    }

    [self recursive_bezier:x1 :y1 :x12 :y12 :x123 :y123 :x1234 :y1234];
    [self recursive_bezier:x1234 :y1234 :x234 :y234 :x34 :y34 :x4 :y4];

  }
}

- (void)drawLine :(double)x1 :(double)y1
                 :(double)x4 :(double)y4{
  countDraw = countDraw+1;
  NSLog(@"============%d============",countDraw);
  NSLog(@"x1 = %f y1 = %f",x1, y1);
  NSLog(@"x4 = %f y4 = %f",x4, y4);

  UIBezierPath *path = [UIBezierPath bezierPath];
  [path moveToPoint:CGPointMake(x1, y1)];

  [path addLineToPoint:CGPointMake(x4, y4)];

  CAShapeLayer *shapeLayer = [CAShapeLayer layer];
  shapeLayer.path = [path CGPath];
  shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
  shapeLayer.lineWidth = 2.0;
  shapeLayer.fillColor = [[UIColor clearColor] CGColor];

  [self.view.layer addSublayer:shapeLayer];

}

Can anyone help me why the right side not calculated and how to make the curve smooth?
ps : i got the algorithm on Bezier Curve Algorithm

A: The problem is that once isFlat is set to true, any further segments won't be subdivided properly, even at the top level. This is because it is information related to a specific level of the recursive calls and not something global to the whole thing. If you step through the execution of the code this should be more clear.
A better way to do it is to declare count as an int parameter to recursive_bezier and pass 0 at the top level when you call it, and pass count + 1 when you call it recursively. You can get rid of the isFlat variable and just test for count >= 5.


text:
Q: For loops creating black screen without reading integer array Whenever I tried to get the pixel array in the ori class, which extends the Screen class, to render to the canvas (that, in turn, is written in the canvas in the main class) it just generated a black image over the canvas in the JFrame. This only happened when the 'for' loops are written as "x = 0" as opposed to "int x = 0". When the loops are written as "int x = 0" or "int y= 0", it did not generate anything, including the black screen.
This is from the origin method in the ori class:
    if(x <= ax && y <= ay){

        for(int y = 0; y < height; y++){
            for(int x = 0; x < width; x++){
                pixels[x + y * width] = 0xff00ff;
            }
        }
    }

screen class:
    void waves(){
            rand = new Random();

    for(y = 0; y < height; y++){

        int r = 24 + 1;
        int s = 10;

        waves++;
        if(waves == 75){
            sel = rand.nextInt(2);
            waves = 0;
        }

        if(sel == 0){

            if(blue > 0){
                float f = ray - r;

                double uir = f * 0.0001;
                u = blue *= uir;
            }
            else{

            }
        }

        if(sel == 1){

            if(blue > 0){
                float f = ray + r;
                double uir = f * 0.0001;
                u = blue *= uir;
            }
            else{

            }
        }
        for(x = 0; x < width; x++){

            Color wacol = new Color(0, 0, u);
            int water = wacol.getRGB();

            pixels[x + y * width] = water;
            orga.origin();
        }
    }
}

It appears that the 'for' loops written as "x = 0" are called upon and then, somehow, render without reading the pixel array. The same happens when "int x = 0" but with the opposite result. What is causing this and what is causing the code to ignore the pixel array?


text:
Q: Export Lottie animation as a layer by AVVideoComposition I want to add an animated sticker to an iOS video and export it through AVVideoComposition. I am able to do it by using a Lottie animation, but the problem is while exporting the Lottie animation as a layer in AVvideocoreanimationtool it is not properly synced with the video timing. The animation speed is variable in different device while exporting. The animation is actually not rendered correctly depending on device, etc.
The animation timespace is not linked to the video timespace. I know there is an easy solution that is take screenshot and add it in video layer but it's costly. Any suggestion how to solve this problem and use Lottie as a layer and export video efficiently?


text:
Q: Observe error property on Ember.Model I'm trying to create a component, which creates an input field for a specific field on a Ember.model.
When calling model.save() I would like to display the possible error messages regarding that field, right beneath the field. But I can't seem to get notified when my Errors property on Ember.Model changes.
Is there a way to observe the model.errors property, in order to display the correct error messages?
I tried:

*

*.property{'model.errors'} and Ember.computed

*.observes('model.errors')

*.observes('model').on('becameInvalid')

I think i'm pretty close, as my errors with the solution below, are being dipslayed, however when I change my input to something else invalid, and try to save again, my original errors do not get cleared, and the new ones do not get added.
When I put breakpoints, or console.logs, I can see that the code never enters that particular section for displaying errors again, so my guess is that the computed property is not working. And my template is never updated with new errors.
Here's my code at the moment:
My component: components/inputfield-text.js
import Ember from 'ember';

export default Ember.Component.extend({
    value: Ember.computed('model', 'field', {
    get: function() {
            return this.get('model').get(this.get('field'));
    },
    set: function(key, value) {
        this.get('model').set(this.get('field'), value);
            return value;
    }
    }),
    errors: function(){
        var errors = this.get('model.errors');
        console.log(errors)
        return errors.errorsFor(this.get('field'));
    }.property('model.errors', 'model', 'field')
});

My Component's template: templates/components/inputfield-text.hbs
{{input type='text' value=value class='form-control' placeholder=placeholder}}

{{#each errors as |error|}}
  <div class="error">
    {{error.message}}
  </div>
{{/each}}

And for the sake of completeness, the code I use for embedding the component in a template:
{{inputfield-text model=model field='name'}}

A: Found it, I had to add [] to my computed property, correct code below, notice difference between.
property('model.errors', 'model', 'field')

And
property('model.errors.[]')

Correct component code: components/inputfield-text.js
import Ember from 'ember';

export default Ember.Component.extend({
    value: Ember.computed('model', 'field', {
    get: function() {
            return this.get('model').get(this.get('field'));
    },
    set: function(key, value) {
        this.get('model').set(this.get('field'), value);
            return value;
    }
    }),
    errors: function(){
        var errors = this.get('model.errors');
        console.log(errors)
        return errors.errorsFor(this.get('field'));
    }.property('model.errors.[]')
});


text:
Q: Appending values to array in a class? ####update:
i have a curl connection method which has an array to set options and i need to append an option in the listDirectory method and send it to the first method (connection)
I would like to append the values in method two to the array in method one
and when I call method one, I would like to display:
Array ( [one] => 111 [two] => 2222[three] => 3333)

Can anyone help?

<?php

class test{

   public $myarray;

   public function one(){

     return $this->myarray=array(
      "one"=>"111",
      "two"=>"222"
      );

   }

   public function two(){

      return $this->myarray["three"]="333";
   }
}
$myclass=new test();
$myclass->one();
$myclass->two();

print_r($myclass->one());

A: I don't know exactly what you need. I think something like this:
class test{

   public $myarray = [];

   public function add(array $array = []){
     return $this->myarray = array_merge($this->myarray, $array);
   }

   public function get(){
     return $this->myarray;
   }
}

$myclass=new test();

$arr0 = $myclass->get();
// array(0) { }

$arr1 = $myclass->add(["one"=>"111","two"=>"222"]);
//array(2) { ["one"]=> string(3) "111" ["two"]=> string(3) "222" }

$arr2 = $myclass->add(["three" =>"333"]);
//array(3) { ["one"]=> string(3) "111" ["two"]=> string(3) "222" ["three"]=> string(3) "333" }

$arr4 = $myclass->get();
//array(3) { ["one"]=> string(3) "111" ["two"]=> string(3) "222" ["three"]=> string(3) "333" }


text:
Q: DATASTAGE- SQL Server from datastage: load table with strange name I have a SQL Server table, whose name is like Vers-xxx_yyy.
As you can see, there is a character "-".
I don't know why this table was made so, but I have to load it from datastage job.
So when I run my job, I obtain error "table doesn't exist".
I use odbc stage.
Directly on SQL Server it is possible to use syntax [Vers-xxx_yyy], but not in datastage.
This db already exists and it is used by other applications.
Is there a way to avoid/resolve the problem?

A: Try using double quotes over the table name. Also it is good practice not to use hyphen, instead you can use underscore

A: Try using a backslash \ to escape the - character - Vers\-xxx_yyy.

A: You should be able to put the table name in this form on the ODBC Connector too: [Vers-xxx_yyy]
Another solution would be to inform the SQL to query this table: SELECT * FROM [Vers-xxx_yyy]


text:
Q: How can i get value from child to parent on button click when button is in parent? I have been using Stepper view by flutter.And I am having an issue on getting value from child to parent on button click as the button is in parent widget.
Here is my Parent class and my child class.
Parent Class
This is my parent class which has a Stepper view with next and back button.I want to get value from my child class to parent class when next button is clicked.
   class DeliveryTimeline extends StatefulWidget {
      DeliveryTimeline({Key key, this.title}) : super(key: key);

      final String title;

      @override
      _MyHomePageState createState() => new _MyHomePageState();
    }

    class _MyHomePageState extends State<DeliveryTimeline> {
      int _currentStep = 0;
      String shippingtype;

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.white,
              centerTitle: true,
              iconTheme: new IconThemeData(color: Colors.black),
              elevation: 0,
              title: Text(
                "Checkout",
                style: TextStyle(color: Colors.black),
              ),
            ),
            body: Stepper(
                type: StepperType.horizontal,
                steps: _mySteps(),
                currentStep: this._currentStep,
                onStepTapped: (step) {
                  setState(() {
                    this._currentStep = step;
                  });
                },
                onStepContinue: () {
                  setState(() {
                    if (this._currentStep == 0) {
                      this._currentStep = this._currentStep + 1;

**//need to get value here on first next click**

                    } else if (this._currentStep == 1) {
                      this._currentStep = this._currentStep + 1;
                    } else {
                      print('Completed, check fields.');
                    }

                  });
                },
                onStepCancel: () {
                  setState(() {
                    if (this._currentStep > 0) {
                      this._currentStep = this._currentStep - 1;
                    } else {
                      this._currentStep = 0;
                    }
                  });
                },
                controlsBuilder: (BuildContext context,
                    {VoidCallback onStepContinue,
                    VoidCallback onStepCancel,
                    Function onShippingNextClick}) {
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      OutlineButton(
                          child: new Text("Back"),
                          onPressed: onStepCancel,
                          shape: new RoundedRectangleBorder(
                              borderRadius: new BorderRadius.circular(4.0))),
                      MaterialButton(
                        child: Text("Next"),
                        color: AppColors.primarycolor,
                        textColor: Colors.white,
                        onPressed: onStepContinue,
                      ),
                    ],
                  );
                }));
      }

      List<Step> _mySteps() {
        List<Step> _steps = [
          Step(
            title: Text('Delivery'),
            content: Center(
              child: Container(
                height: MediaQuery.of(context).size.height / 1.5,
                child: Delivery(onShipingTypeClicked: (shippingtype){
                  shippingtype = shippingtype;
                  print("myvalue${shippingtype}");
                },),
              ),
            ),
            isActive: _currentStep >= 0,
          ),
          Step(
            title: Text('Address'),
            content: Address(),
            isActive: _currentStep >= 1,
          ),
          Step(
            title: Text('Payment'),
            content: Payment(),
            isActive: _currentStep >= 2,
          )
        ];
        return _steps;
      }

    }

Child Class
This is my child class i have a Listview which act like a radio button.I want the selected item and its value to the parent class when button is clicked..
class Delivery extends StatefulWidget {
  final ValueChanged<String> onShipingTypeClicked;

   Delivery({this.onShipingTypeClicked});

  @override
  _DeliveryState createState() => _DeliveryState();
}

class _DeliveryState extends State<Delivery> {

  List<RadioModel> sampleData = new List<RadioModel>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    sampleData.add(new RadioModel(false, 'A', 0xffe6194B, "Standard Delivery",
        "Order will be delivered between 3 - 5 business days", 1));
    sampleData.add(new RadioModel(
        true,
        'A',
        0xffe6194B,
        "Next Day Delivery",
        "Place your order before 6pm and your items will be delivered the next day",
        2));
    sampleData.add(new RadioModel(
        false,
        'A',
        0xffe6194B,
        "Nominated Delivery",
        "Pick a particular date from the calendar and order will be delivered on selected date",
        3));

  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new ListView.builder(
        itemCount: sampleData.length,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          return new InkWell(
              onTap: () {
                setState(() {
                  sampleData.forEach((element) => element.isSelected = false);
                  sampleData[index].isSelected = true;
                  widget.onShipingTypeClicked(sampleData[index].buttonText);
                });
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  TextSmallTitleSize(
                    title: sampleData[index].title,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 20.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: <Widget>[
                        Flexible(
                          child: TextSmallDimText(sampleData[index].label),
                        ),
                        RadioItem(sampleData[index]),
                      ],
                    ),
                  )
                ],
              ));
        },
      ),
    );
  }
}

class RadioItem extends StatelessWidget {
  final RadioModel _item;

  RadioItem(this._item);

  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: new EdgeInsets.all(15.0),
      child: new Row(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          new Container(
            height: 25.0,
            width: 25.0,
            alignment: Alignment.center,
            child: Container(
                height: 15.0,
                width: 15.0,
                decoration: new BoxDecoration(
                  color: AppColors.primarycolor,
                  borderRadius:
                      const BorderRadius.all(const Radius.circular(15)),
                )),
            decoration: new BoxDecoration(
              color: Colors.transparent,
              border: new Border.all(
                  width: 3.0,
                  color: _item.isSelected
                      ? AppColors.primarycolor
                      : Colors.transparent),
              borderRadius: const BorderRadius.all(const Radius.circular(25)),
            ),
          ),
          new Container(margin: new EdgeInsets.only(left: 10.0))
        ],
      ),
    );
  }
}

class RadioModel {
  bool isSelected;
  final String buttonText;
  final int colorCode;
  final String title, label;
  final int buttonid;

  RadioModel(this.isSelected, this.buttonText, this.colorCode, this.title,
      this.label, this.buttonid);
}

A: You can copy paste run full code below
You can use GlobalKey to get deliveryState of Delivery, and use deliveryState to get attribute of Delivery, attribute here is RadioModel selected
Step 1: Use GlobalKey _key = GlobalKey();
class _MyHomePageState extends State<DeliveryTimeline> {
  ...
  GlobalKey _key = GlobalKey();

Step 2: Use deliveryState to get seleted item
onStepContinue: () {
          setState(() {
            if (this._currentStep == 0) {
              this._currentStep = this._currentStep + 1;

              final _DeliveryState deliveryState =
                  _key.currentState;
              print("hi ${deliveryState.selected.title} ${deliveryState.selected.label} ");

Step 3: Delivery need key
child: Delivery(
              key: _key,
              onShipingTypeClicked: (shippingtype) {
 ...
 Delivery({Key key, this.onShipingTypeClicked}) : super(key:key);

Step 4: Set variable selected
RadioModel selected = null;
...
return InkWell(
              onTap: () {
                setState(() {
                  ...
                  selected = sampleData[index];

working demo

output of working demo
I/flutter ( 6246): hi Standard Delivery Order will be delivered between 3 - 5 business days

full code
import 'package:flutter/material.dart';

class DeliveryTimeline extends StatefulWidget {
  DeliveryTimeline({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<DeliveryTimeline> {
  int _currentStep = 0;
  String shippingtype;
  GlobalKey _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          centerTitle: true,
          iconTheme: IconThemeData(color: Colors.black),
          elevation: 0,
          title: Text(
            "Checkout",
            style: TextStyle(color: Colors.black),
          ),
        ),
        body: Stepper(
            type: StepperType.horizontal,
            steps: _mySteps(),
            currentStep: this._currentStep,
            onStepTapped: (step) {
              setState(() {
                this._currentStep = step;
              });
            },
            onStepContinue: () {
              setState(() {
                if (this._currentStep == 0) {
                  this._currentStep = this._currentStep + 1;

                  final _DeliveryState deliveryState =
                      _key.currentState;
                  print("hi ${deliveryState.selected.title} ${deliveryState.selected.label} ");

                } else if (this._currentStep == 1) {
                  this._currentStep = this._currentStep + 1;
                } else {
                  print('Completed, check fields.');
                }
              });
            },
            onStepCancel: () {
              setState(() {
                if (this._currentStep > 0) {
                  this._currentStep = this._currentStep - 1;
                } else {
                  this._currentStep = 0;
                }
              });
            },
            controlsBuilder: (BuildContext context,
                {VoidCallback onStepContinue,
                VoidCallback onStepCancel,
                Function onShippingNextClick}) {
              return Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  OutlineButton(
                      child: Text("Back"),
                      onPressed: onStepCancel,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(4.0))),
                  MaterialButton(
                    child: Text("Next"),
                    color: Colors.blue,
                    textColor: Colors.white,
                    onPressed: onStepContinue,
                  ),
                ],
              );
            }));
  }

  List<Step> _mySteps() {
    List<Step> _steps = [
      Step(
        title: Text('Delivery'),
        content: Center(
          child: Container(
            height: MediaQuery.of(context).size.height / 1.5,
            child: Delivery(
              key: _key,
              onShipingTypeClicked: (shippingtype) {
                shippingtype = shippingtype;
                print("myvalue${shippingtype}");
              },
            ),
          ),
        ),
        isActive: _currentStep >= 0,
      ),
      Step(
        title: Text('Address'),
        content: Text("Address()"),
        isActive: _currentStep >= 1,
      ),
      Step(
        title: Text('Payment'),
        content: Text("Payment()"),
        isActive: _currentStep >= 2,
      )
    ];
    return _steps;
  }
}

class Delivery extends StatefulWidget {
  final ValueChanged<String> onShipingTypeClicked;

  Delivery({Key key, this.onShipingTypeClicked}) : super(key:key);

  @override
  _DeliveryState createState() => _DeliveryState();
}

class _DeliveryState extends State<Delivery> {
  List<RadioModel> sampleData = List<RadioModel>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    sampleData.add(RadioModel(false, 'A', 0xffe6194B, "Standard Delivery",
        "Order will be delivered between 3 - 5 business days", 1));
    sampleData.add(RadioModel(
        true,
        'A',
        0xffe6194B,
        "Next Day Delivery",
        "Place your order before 6pm and your items will be delivered the next day",
        2));
    sampleData.add(RadioModel(
        false,
        'A',
        0xffe6194B,
        "Nominated Delivery",
        "Pick a particular date from the calendar and order will be delivered on selected date",
        3));
  }

  RadioModel selected = null;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: sampleData.length,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          return InkWell(
              onTap: () {
                setState(() {
                  sampleData.forEach((element) => element.isSelected = false);
                  sampleData[index].isSelected = true;
                  selected = sampleData[index];
                  widget.onShipingTypeClicked(sampleData[index].buttonText);
                });
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  ListTile(
                    title: Text(sampleData[index].title),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 20.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: <Widget>[
                        Flexible(
                          child: Text(sampleData[index].label),
                        ),
                        RadioItem(sampleData[index]),
                      ],
                    ),
                  )
                ],
              ));
        },
      ),
    );
  }
}

class RadioItem extends StatelessWidget {
  final RadioModel _item;

  RadioItem(this._item);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(15.0),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          Container(
            height: 25.0,
            width: 25.0,
            alignment: Alignment.center,
            child: Container(
                height: 15.0,
                width: 15.0,
                decoration: BoxDecoration(
                  color: Colors.blue,
                  borderRadius:
                      const BorderRadius.all(const Radius.circular(15)),
                )),
            decoration: BoxDecoration(
              color: Colors.transparent,
              border: Border.all(
                  width: 3.0,
                  color: _item.isSelected ? Colors.blue : Colors.transparent),
              borderRadius: const BorderRadius.all(const Radius.circular(25)),
            ),
          ),
          Container(margin: EdgeInsets.only(left: 10.0))
        ],
      ),
    );
  }
}

class RadioModel {
  bool isSelected;
  final String buttonText;
  final int colorCode;
  final String title, label;
  final int buttonid;

  RadioModel(this.isSelected, this.buttonText, this.colorCode, this.title,
      this.label, this.buttonid);
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: DeliveryTimeline(),
    );
  }
}


text:
Q: Finding Dual Plane Curve Using Eliminate I want to find the dual curve of the projective plane curve
    $$F(x,y,z)=(x^2+y^2+z^2)x+t(x^3+y^3+z^3)=0$$
where $[x,y,z]$ is homogeneous coordinate in proejective 2-space $\mathbb P^2$. The dual curve is the common algebraic equation $G(u,v,w)=0$ under the constraint $F(x,y,z)=0$, where
    $$
\begin{cases}
u=\frac{\partial F}{\partial x}=2x^2+(x^2+y^2+z^2)+3tx^2,\\
v=\frac{\partial F}{\partial y}=2xy++3ty^2,\\
w=\frac{\partial F}{\partial z}=2xz++3tz^2.
\end{cases}
$$
So we need to eliminate variables $x,y,z$ and find algebraic relation between $u,v,w$.
I feed the following into Mathematica:
    Eliminate[{(x^2 + y^2 + z^2) x + t (x^3 + y^3 + z^3) == 0,
    u == 2 x^2 + (x^2 + y^2 + z^2) + 3 tx^2, v == 2 xy + 3 ty^2,
    w == 2 xz + 3 tz^2}, {x, y, z}];

But the output is
    v == 3 ty^2 + 2 xy && w == 3 tz^2 + 2 xz;

Note that they are exactly the same as the last two equations from the input, so Mathematica doesn't solve at all! I don't understand why it doesn't eliminate variables $x,y,z$ as instructed. In this post, OP find the dual curve successfully using Eliminate with exactly the same as mine, what's wrong with my method?

A: Since the coefficients of the $u^pv^qw^r$ monomials of the dual will be polynomials in t, we can use FindSequenceFunction[] on the results for numeric values for t to deduce the coefficients.  One could also use InterpolatingPolynomial[].
FF = (x^2 + y^2 + z^2) x + t (x^3 + y^3 + z^3);

vars = {x, y, z};
newvars = {u, v, w};

ClearAll[cc, gb];
(* memoization is helpful when testing & recomputing *)
mem : gb[t0_] := mem = Block[{t = t0},
    Last@CoefficientArrays[
      First@
       GroebnerBasis[Flatten@{FF, D[FF, {vars}] - newvars}, newvars,
        vars],
      newvars]
    ];
cc[t0_] := gb[t0]["NonzeroValues"];

coeffseq = Transpose@Table[
    cc[t],
    {t, 25}];

coeff = FindSequenceFunction[#/First@coeffseq, t] & /@ coeffseq

dual = Nest[
  #.newvars &,
  SparseArray@Thread[gb[1]["NonzeroPositions"] -> coeff],
  6]


text:
Q: Bind function to the event "onclick" of the elements of an array of buttons Preamble: I'm Italian, sorry for my bad English.
This is my problem:
I want to assign a function to a set of buttons.
I need to send a parameter to the function.
this is the code that I've tried:
function test(atxt) {
    var buttons = $('.tblButton');

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].onClick(sayHello(atxt));
    }
}

function sayHello(txt){alert('hello' + txt)};

...getting the following error:
Uncaught TypeError: Object #<HTMLButtonElement> has no method 'onClick'

can you tell me where I went wrong and how can I fix it?
EDIT: I need iteration because I need the 'id of the button as a parameter of the function so i need to do buttons[i].onClick(sayHello(buttons[i].id))

A: buttons[i].onClick(sayHello(atxt));

Supposed to be
$(buttons[i]).on('click', function() { sayHello(atxt) });

If you want to get the current button id then I think you are looking for this..
for (var i = 0; i < buttons.length; i++) {
     $(buttons[i]).on('click', function() { sayHello(this.id) });
}

A: If you want to iterate through all of the buttons then you have to do that with .each() handler of the jquery:
$(function(){
  $(".tblButton").each(function () {
    $(this).click(function(){
       alert($(this).attr('id'));
    });
  });
});

checkout the jsbin: http://jsbin.com/usideg/1/edit

A: Would this not work for your example: Do you have another reason for the iteration?
function test(atxt) {
    $('.tblButton').on('click',function(){sayHello(atxt);});
}

function sayHello(txt){alert('hello' + txt)};

OR optionally if the elements are static and present:
function test(atxt) {
    $('.tblButton').click(function(){sayHello(atxt);});
}

function sayHello(txt){alert('hello' + txt)};

Alternate approach: just change
to this style:
var txt = "fred";
var atext = "hello" + txt;

function sayHello(atext) {
    alert(atext);
}
$('.tblButton').on('click', function() {
    sayHello(atext);
});
//below here just to demonstrate
$('.tblButton').eq(0).click();//fires with the fred
txt = "Johnny";// new text
atext = 'hello' + txt;
$('.tblButton').eq(1).click();//fires the Johnny

see it working here:
http://jsfiddle.net/dFBMm/
SO based on your note:
this markup and code:
<button class="tblButton" id="Ruth">Hi</button>
<button class="tblButton" id="Betty">Hi again</button>

$('.tblButton').on('click', function() {
    alert("Hello "+$(this).attr("id"));
});
$('.tblButton').eq(0).click();//fires with the Ruth
$('.tblButton').eq(1).click();//fires the Betty

http://jsfiddle.net/dFBMm/1/


text:
Q: How to change the color of intern Android drawables? I've tried to put the intern icons of Android (anrdoid.R.drawable.bla) into an ImageButton
and I wanted to change the color of Icon (not the Background!), but it doesn't work like I want to.
Here is what I've tried:
my ImageButton from the Layout:
<ImageButton
    android:id="@+id/imageButton1"
    android:layout_marginTop="100dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/background"
    android:src="@android:drawable/ic_lock_silent_mode" />

what I've tried in my Activity:
Drawable myIcon = getResources().getDrawable( android.R.drawable.ic_lock_silent_mode);
    ColorFilter filter = new LightingColorFilter( R.color.blue, R.color.blue);
    myIcon.setColorFilter(filter);

No matter what Values I've tried for the LightingColorFilter it always gives the same result. The icon inside the Imagebutton gets dark. But thats not what I wnated. I just wanted to apply a color from my colors.xml, it somehow doesnt work out.
Is this even the right direction I'm going? Or is there another opertunity (And I don't mean coloring myself in Photoshop and putting them into the drawables folder)

A: this worked for me, for example it will paint in dark gray:
ImageButton imgBtn = (ImageButton) findViewById(R.id.imageButton11); // image button
            imgBtn.setColorFilter(getResources().getColor(android.R.color.darker_gray), Mode.SRC_ATOP);


text:
Q: How can I make something when I click my chart? I would like to make an onClick event that when I click on a bar it makes a console log, how can I do it?
state = {
    chartData: {
      labels: [],
      datasets: [
        {
          label: 'Covid-19',
          data: [],
          backgroundColor:'red',
          borderColor: 'red',
          hoverBackgroundColor: 'green',
          hoverBorderColor: 'green',
          borderWidth: 4,
          responsive: true,
        }
      ],
    }
  }

    <Bar  data={this.state.chartData}}/>

A: please try like as below snippet code.
onClick = (e) => {
   var data = e.target.data;
   console.log(data);
}

...
state = {
    chartData: {
      labels: [],
      datasets: [
        {
          label: 'Covid-19',
          data: [],
          backgroundColor:'red',
          borderColor: 'red',
          hoverBackgroundColor: 'green',
          hoverBorderColor: 'green',
          borderWidth: 4,
          responsive: true,
        }
      ],
    }
  }

    <Bar  onClick={(e)=>this.onClick()} data={this.state.chartData}}/>


text:
Q: Nested routes in Padrino I want to group routes into hierarchies. To that end I have created a top level controller thus:
MyApp.controllers :group do
  disable :layout

  get '/' do
    {'dummy' => 'value'}.as_json
  end
end

Now I want to create routes with :group as parent thus:
MyApp.controllers :items, :parent => :group do
  disable :layout

  get '/', :provides => :json do
    # get list of items
  end
end

My problem is that I can access localhost:port/group (200 OK) from my REST client but I cannot access localhost:port/group/items (404 NOT FOUND).
Everything works beautifully if I remove the :parent option. My padrino version 0.10.5.5. Any ideas?

A: The way nested routes work is different than what you're trying to do.
When you use :parent, it expects the parent resource to be identified somehow. For instance:
MyApp.controllers :items, :parent => :group do
  get :index do
    # returns list of items for a group
  end
end

Will generate the following route:
"/group/#{params[:group_id]}/items"

It expects you to specify which group you're talking about in order to fetch the items for that specific group.
That's why it says it cannot find "/group/items", it's not the route that you create by using :parent => :group, you're not passing a :group_id in the params.
If you really want to use "/group/items" then your items controller should look like:
MyApp.controllers :items do
  get '/group/items' do
    # returns list of items
  end
end


text:
Q: Redirection https to https within same Apache I have a requirement where I have to redirect my hostname to particular application which is again hosted on same Apache. Let's take an example, When I hit on host(https://domain1.example.com), It should internally redirect me to Apache Web Application (https://domain1.example.com/application1) without changing the browser URL.
I am not sure how to achieve SSL to SSL redirection. Thanks in Advance..!!!

A: This should work.  This will  redirect all incoming urls that are going to domain1.example.com/ to domain1.example.com/application1
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain1.example.com$
RewriteRule ^$ https://domain1.example.com/application1 [L,R=301]

A: If without changing browsing URL  is your goal then PROXY is your way.
Put following in your apache vhost or global file,
ProxyPass https://domain1.example.com/ https://domain1.example.com/application1
ProxyPassReverse https://domain1.example.com/ https://domain1.example.com/application1

PS shibboleth has nothing to do with this, at least you have not mentioned any case.
EDIT

*

*ProxyPass should come to virtural host not in location

*Ideally all the location tag should be out of virtual host


text:
Q: addFieldToFilter to column from joined table in EAV Table I am trying to filter columns from a joined table using addFieldTofilter. I have tried the code below but throws an exception.
$collection->getSelect()
    ->joinInner(array('customerphotos' => $collection->getTable('myphotos/customerphotos')),
    'e.entity_id = customerphotos.customer_id',
    array(
        'customerphotos.entity_id as entity_id',
        'customerphotos.customer_id',
    ));
$collection->addFieldToFilter('customerphotos_created_at', $condition);

I have tried $collection->addFilterToMap('customerphotos_created_at', 'customerphotos.created_at'); but it only works on non EAV table.


text:
Q: How can I extract data from a 3rd party application's UI controls? In 2003 I found a little utility which allowed me to select a control (like a listview) on any application, and it would copy it's contents into the clipboard.
For example, you could select the list in Windows Explorer, and all the filenames, sizes, dates, etc. would be copied for you to paste into Notepad.
I don't remember the name of it, but I do remember the name was so unrelated that I could never find it when I needed it. So now, years later, I can't find it.
Does anybody know of any utilities which might do this? Or possibly even the utility I'm talking about?

A: Sounds a lot like NirSoft's SysExporter:

SysExporter utility allows you to grab the data stored in standard list-views, tree-views, list boxes, combo boxes, text-boxes, and WebBrowser/HTML controls from almost any application running on your system, and export it to text, HTML or XML file.

A: I just downloaded Count Characters v4.1 for 64 bit and it is working on Win 7 64 bit. It worked even to copy text from a listview inside a QT app !
Just my 2 cents so you guys know this tool is still working...

A: For the record, the software I was looking for is called Count Characters and is available at http://www.funduc.com/countchars.htm
Unfortunately, it doesn't appear to work anymore.  At least not on the 64 bit Windows 7 machine I tested it on.


text:
Q: Building a wiki like data model in rails question I have a data model in which I would like to have an item that has a description that can be edited. I would like to also keep track of all edits to the item. I am running into issues with my current strategy, which is:
class Item < ActiveRecord::Base
  has_one  :current_edit,
           :class_name => "Edit",
           :foreign_key => "current_edit_id"
  has_many :edits
end

class Edit < ActiveRecord::Base
  belongs_to :item
end

Can the Item have multiple associations to the same class like this?
I was thinking that I should switch to keeping track of the edit version in the Edit object and then just sorting the has_many relationship base on this version.

A: Yes it can. But you have to use belongs_to not has_one. Then your models have to look like:
(Item, current_edit_id, ...)
(Edit, item_id, ....)

The rails doc explains this in more detail: Is it a belongs_to or has_one association?


text:
Q: Input strings being treated as text objects by browser I have a popup that displays a user's form input for review/edit prior to submission. All the information is being retrieved and displayed with no problem except that the input field values are being treated as text objects, and therefor not displayed quite properly. I know WHAT is happening, I just haven't the slightest clue how to fix it. I've never encountered this problem before. Should the values be stuffed into a string variable first or is there some obscure conversion issue i'm unaware of? The snapshot is from the latest version of chrome... The second image shows the text in question being treated as a separate object from the text beside it...

function chkThis() {
  var isChk = document.getElementsByName('agecert');
  var isSub = document.getElementById('submit');
  isSub.disabled = !isChk[0].checked;
}

function shPop() {
  var shPop = document.getElementById("myOlay");
  var rvwBdy = '';
  rvwBdy = '
Name: ' + document.getElementById('fname').value + ' ' + document.getElementById('lname').value + '
' +
    'Email: ' + document.getElementById('email').value + '
' +
    'Phone: ' + document.getElementById('phone').value + '
' +
    'Address: ' + document.getElementById('maddr').value + '
';

  shPop.classList.remove('dk-hidden');
  shPop.classList.add('dk-show');
  document.getElementById('reviewHere').innerHTML = rvwBdy;
}

function hdPop() {
  var hdPop = document.getElementById("myOlay");
  hdPop.classList.remove('dk-show');
  hdPop.classList.add('dk-hidden');
}
:root {
  --dkVar: '';
}

* {
  margin: 0;
  padding: 0;
  position: absolute;
  font-family: sans-serif;
  @include pre1(box-sizing, border-box);
}

html,
body {
  width: 100%;
  height: 100%;
}

body {
  background: #8080FF;
}

a {
  text-decoration: none;
}

.dk-center {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.dk-vertz {
  top: 50%;
  transform: translateY(-50%);
}

.dk-hortz {
  left: 50%;
  transform: translateX(-50%);
}

#dk-wrapper {
  width: 100%;
  height: 100%;
}

#dk-logo {
  top: 0;
  width: 100%;
  height: 125px;
}

#dk-menu {
  top: 125px;
  left: 0;
  min-width: 500px;
  width: 100%;
  height: 75px;
  background: #338833;
  text-align: center;
}

#dk-body {
  top: 210px;
  width: 75%;
  height: 75%;
  background: rgba(192, 192, 255, 0.8);
  border-radius: 25px;
}

h1,
h2,
h3,
h4,
h5 {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.dk-logo {
  width: 400px;
}

.dk-order {
  min-width: 500px;
  min-height: 700px;
}

.input {
  width: 175px;
  height: 40px;
  padding-left: 20px;
  margin-left: 20px;
  display: inline-block;
  border: 2px solid #309930;
  border-radius: 5px;
  line-height: 40px;
  z-index: 9;
  position: relative;
  font-size: 18px;
}

.label {
  display: block;
  margin-left: 30px;
  position: relative;
  font-size: 8pt;
  color: red;
  z-index: 10;
}

.icon {
  height: 35px;
  width: 35px;
  padding-top: 3px;
  background: #fff;
  border: 2px solid #309930;
  border-radius: 100%;
  z-index: 10;
  font-size: 32px;
  text-align: center;
  overflow: hidden;
}

.input:focus {
  border: 2px solid #30ff30;
  background: #ffddff;
}

#inp1 {
  top: 15px;
  left: 25px;
  width: 175px;
  position: absolute;
}

#inp2 {
  top: 15px;
  left: 190px;
  width: 175px;
  margin-left: 50px;
}

#inp3 {
  top: 85px;
  left: 25px;
  width: 175px;
}

#inp4 {
  top: 85px;
  left: 190px;
  width: 175px;
  margin-left: 50px;
}

#inp5 {
  top: 150px;
  left: 25px;
}

.dk-mydiv {
  top: 210px;
  width: 500px;
  height: 750px;
  position: absolute;
  border: none;
  background: #bbbbff;
  border-radius: 25px;
}

.maddr {
  width: 400px;
  height: 125px;
  line-height: 22px;
}

button {
  color: #555555;
  font-weight: bold;
  width: 100px;
  height: 35px;
  background: #99ff99;
  border: 1px solid #44aaee;
}

button:enabled {
  transition: all 250ms linear 0.0ms;
}

button:disabled {
  color: #bbbbbb;
  font-weight: bold;
  width: 100px;
  height: 35px;
  border: #44aaee;
  background: #555555;
  opacity: 0.75;
  cursor: not-allowed;
}

button:hover:enabled,
button:focus:enabled {
  color: black;
  font-weight: bold;
  width: 100px;
  height: 35px;
  background: #55ff55;
  border: 2px solid #44aaee;
  border-radius: 35px;
  box-shadow: 5px 3px 1px 1px rgba(0, 0, 0, .75);
}

.product {
  width: 40px;
  top: 10px;
  left: 10px;
  position: absolute;
  height: 25px;
  margin-left: 0px;
  padding: 0px;
}

.inplab {
  top: 15px;
  left: 60px;
  position: absolute;
}

#dk-intro {
  top: 210px;
  left: 15px;
}

#myOlay {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.75);
  display: block;
  z-index: 999;
  position: fixed;
}

#cbReview {
  min-width: 500px;
  height: 75%;
  position: fixed;
  background: white;
  color: black;
  border: 2px solid #0055cc;
  border-radius,
  25px;
  z-index: 1000;
}

.dk-hidden {
  visibility: hidden;
}

.dk-show {
  visibility: visible;
}

  <form name="cbOrder" method="post" action="php/cb-cont.php" enctype="multipart/form-data">

         *Required
        <input name="fname" id="fname" type="text" class="input chkIt" size="30" value="" placeholder="First Name" tabindex="1" />

         *Required
        <input name="lname" id="lname" type="text" class="input chksssaIt" size="30" value="" placeholder="Last Name" tabindex="2" />

         *Required
        <input name="email" id="email" type="text" class="input chkIt" size="30" value="" placeholder="Email Address" tabindex="3" />

        <input name="phone" id="phone" type="tel" class="input" size="10" placeholder="Phone Number" tabindex="4" />

         *Required
        <textarea name="maddr" id="maddr" class="input maddr chkIt" cols="60" rows="5" placeholder="Mailing Address" tabindex="5"></textarea>

NOTICE: At present, there is a limit of ten (10) items total per order.

        <input name="whorse" id="whorse" type="number" size="3" class="input product" placeholder="Qty." value="0" tabindex="6">
        White Horse

        <input name="wbbee" id="wbbee" type="number" size="3" class="input product" placeholder="Qty." value="0" tabindex="7">
        White Bumblebee

        <input name="agecert" type="checkbox" onclick="chkThis();" style="float: left;height: 20px;width: 25px;border: 1px solid red;" tabindex="8">

I certify that I am 18 years of age or older and legally able to enter into a contract of purchase and/or other negotiations in the State of Louisiana. I also certify my understanding that the personal information collected from me by Cypress
          Botanicals will be used for the sole and express purpose of order fulfillment and will never be made available to any third parties.

        <button name="submit" type="button" onclick="shPop();" id="submit" style="left: 65px;" tabindex="9" disabled="disabled">Review Order</button>
        <button name="reset" type="reset" style="left: 245px;" tabindex="10">Reset Form</button>

Please review your order information to make sure everything is correct. Orders with incomplete or invalid information will not be processed. Please remember that there is an order limit of ten (10) units TOTAL. Thank you!

<input type="button" onclick="hdPop()" value="Edit Info" />

</form>


text:
Q: On algebraic integers. I've question on algebraic integers. $z$ is a complex number and $n$ is a natural number, such that, $z^n=\pm 1$. So, $z-1/z$ is an algebraic integer.
I. If $r$ is a rational number, is $(z-1/z)^{r}$ still an algebraic integer?
Or more general, if $a$ is an alg. int. then $a^r$ is also alg. int.?
II. If $a-1/a$ is an alg. int., is $a$ an alg. int.?
Thanks
Edit. I've been reading about some more simple transcendental proofs, and I came across a few similar statements. But I just had these questions, because of this I can't find the answers so easily online.

A: I. Yes if $r$ is positive. Not necessarily if $r$ is negative. If $a_1,\ldots,a_{n-1}$ are algebraic integers, then any root of $x^n + a_{n-1}x^{n-1}+\cdots + a_1x + a_0$ is also an algebraic integer. Writing $r=p/q$ with $p$ and $q$ (positive) integers, it is clear that $(z-1/z)^p$ is an algebraic integer, and $(z-1/z)^r$ is a root of $x^q - (z-1/z)^p$, hence an algebraic integer itself. If $r$ is negative, then the answer may be negative: e.g., $z=i$, $z-(1/z) = i-(-i) = 2i$, and taking $r=-1$ yields $(2i)^{-1} = -\frac{i}{2}$, which is not an algebraic integer.
II. As mr_e_man noted, if $a-(1/a)$ is an algebraic integer, then $a$ is a root of $x^2 - (a-1/a)x -1$ which is a monic polynomial
with algebraic integer coefficients, hence $a$ is an algebraic integer.
In both cases, the key is

Theorem. If $f(x)$ is a monic polynomial with algebraic integer coefficients, and $a$ is a root of $f$, then $a$ is an algebraic integer.

So that's the theorem you want to prove.


text:
Q: How to access camera onclick on Android app? I am currently using Visual Studio to work on my project, and i need a function which allows the opening of camera on the press of a button. I have some codes from a previous project but they don't seem to work now. Below are my codes.
js:
function getImage() {
    // Retrieve image file location from specified source
    navigator.camera.getPicture(uploadPhoto,
        function (message) { alert('get picture failed'); },
        { quality: 10, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
    );
}

HTML:
<form id="buyforme">

<img id="myimg" height="100">
<input type="button" name="selectimg" id="selectimg" onclick="getImage();" value="Take a picture of this item :)">

Please advise & let me know if there's anything else you need to know! Thank you all!

A: For access to mobile phone camera for getting photo or video in android or ios you can simply use input[type="file"] like this:
Getting photo:
 <input type="file" accept="image/*" capture="camera">

Getting video:
<input type="file" name="video" accept="video/*" capture="environment">

For opening back camera:
<input type="file" name="image" accept="image/*" capture="environment">

And for selfie camera (front):
<input type="file" name="image" accept="image/*" capture="user">

Source


text:
Q: What's the storage solution used by search engines to store indexes to enable efficient querying and scalability? There are lots of articles on how search engines perform indexing, but couldn't find any information on how they store these indexed records in a way that enables fast querying with scalability. Could someone explain the index storing mechanisms used in search engines or point to any article ?

A: Solr is able to achieve fast search responses because, instead of searching the text directly, it searches an index instead. This is like retrieving pages in a book related to a keyword by scanning the index at the back of a book, as opposed to searching every word of every page of the book.
This type of index is called an inverted index, because it inverts a page-centric data structure (page->words) to a keyword-centric data structure (word->pages).
Inverted index is a major term in the domain of Information Retrieval and Natural Language Processing. Take a document, note down all the unique words appearing in that document as well as frequency of the words. Here you are ready with your own inverted index. Solr creates similar inverted index of the documents posted to its core using a defined schema. Schema is a blue print which helps Solr in creating invered index of the documents by giving a set of predefined fields in the schema.xml file.


text:
Q: How to use Numpy version 1.19.5 with Tensorflow and not get numpy.ndarray size changed error? I have been trying to use stable_baselines on my new m1 chip computer; however, after installing all of the packages from some sample code I found, I kept getting this error
ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject

I know this is something that is fixed in numpy >= 1.20; however tensorflow requires 1.19.5; any suggestions on a workaround for this?
Here is the full error log:
File "/opt/homebrew/lib/python3.9/site-packages/stable_baselines/__init__.py", line 4, in <module>
 from stable_baselines.a2c import A2C
File "/opt/homebrew/lib/python3.9/site-packages/stable_baselines/a2c/__init__.py", line 1, in <module>
 from stable_baselines.a2c.a2c import A2C
File "/opt/homebrew/lib/python3.9/site-packages/stable_baselines/a2c/a2c.py", line 5, in <module>
 import tensorflow as tf
File "/opt/homebrew/lib/python3.9/site-packages/tensorflow/__init__.py", line 41, in <module>
 from tensorflow.python.tools import module_util as _module_util
File "/opt/homebrew/lib/python3.9/site-packages/tensorflow/python/__init__.py", line 48, in <module>
 from tensorflow.python import keras
File "/opt/homebrew/lib/python3.9/site-packages/tensorflow/python/keras/__init__.py", line 25, in <module>
 from tensorflow.python.keras import models
File "/opt/homebrew/lib/python3.9/site-packages/tensorflow/python/keras/models.py", line 22, in <module>
 from tensorflow.python.keras.engine import functional
File "/opt/homebrew/lib/python3.9/site-packages/tensorflow/python/keras/engine/functional.py", line 32, in <module>
 from tensorflow.python.keras.engine import training as training_lib
File "/opt/homebrew/lib/python3.9/site-packages/tensorflow/python/keras/engine/training.py", line 50, in <module>
 from tensorflow.python.keras.saving import hdf5_format
File "/opt/homebrew/lib/python3.9/site-packages/tensorflow/python/keras/saving/hdf5_format.py", line 37, in <module>
 import h5py
File "/Users/josephnordling/venv/lib/python3.9/site-packages/h5py/__init__.py", line 25, in <module>
 from . import _errors
File "h5py/_errors.pyx", line 1, in init h5py._errors
ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject


text:
Q: How to execute git command from build.gradle? Could you guys clarify why
def getBuildSuffix() {
  return 'git rev-list HEAD | wc -l | tr -d " "'.execute().text.trim()
}

returns nothing to me taking into consideration there is data when you run git command from a command line:
prototype (master) $ git rev-list HEAD | wc -l | tr -d " "
72

May be I'm just executing a git command from my build.gradle in a wrong way?

A: You have to do your own piping or call by shell (see answer from @topr).  see the error:
def p1 = 'git rev-list HEAD | wc -l | tr -d " "'.execute()
p1.waitFor()
println p1.exitValue()
//-> 128
println p1.errorStream.text
//-> fatal: ambiguous argument '|': unknown revision or path not in the working tree.
//-> Use '--' to separate paths from revisions, like this:
//-> 'git <command> [<revision>...] -- [<file>...]'
println p1.text
//-> nothing

Use groovy e.g.:
println 'git rev-list HEAD'.execute().text.split().size()

A: Pipe is a shell feature so you need to go like:
['sh', '-c', 'git rev-list HEAD | wc -l | tr -d " "'].execute().text.trim()

A: If you're doing this for Android you need Integer.parseInt(), like so:
Integer.parseInt(['sh','-c','git rev-list --all --count']
.execute().text.trim())


text:
Q: Angular2 : Rerender component when there is a change for inner property of an object After modifying the inner property of an object as below
delete this.siteConfig.sites[siteKey].serverIpWhitelist[ip];

The list bind with ngFor is not updated.
I tried NgZone.run() and ChangeDetectorRef.detectChanges(), neither works.
The only way I found to update the list is adding the following line
this.siteConfig = JSON.parse(JSON.stringify(this.siteConfig));

Quite stupid, is there any other manner to force rerender the component?

UPDATE:
The ngFor loops the property of an object via KeysPipe
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]);
    }
    return keys;
  }
}

And the ngFor looks like *ngFor="let pair of (siteConfig.sites | keys)"

A: You can make your pipe impure.
@Pipe({name: 'keys', pure: false})

This way the pipe is called every time change detection runs, no matter if something changed or not. You should ensure the pipe works efficient because this way it's call very often.


text:
Q: Changing font size based on text input Say I have:
<input type="text" name="changefont" value="16">

How do I change a certain node's font-size (for example a paragraph) based on keyup when user types in the value of the font they want?
So far I thought it would be this, but I guess not:
 $('input[name="changefont"]').bind("keyup", function(){
 var fontSize = $(this).val();
 $('p').css('font-size', fontSize);
 });

A: Aside from the selector typo, you need to add a unit in addition to the inputs value:
$('input[name="changefont"]').bind("keyup", function() {
    var fontSize = $(this).val();
    $('p').css('font-size', fontSize + "px");
});

I also recommend using .on() in place of .bind() especially if you're using ver. 1.7+


text:
Q: iOS RTP live audio receiving I'm trying to receive a live RTP audio stream in my iPhone but I don't know how to start. I'm seeking some samples but I can't find them anywhere.
I have a Windows desktop app which captures audio from the selected audio interface and streams it as µ-law or a-law. This app works as an audio server that serves any incoming connection with that streaming. I have to say that I've developed an Android app that receives that stream and it works, so I want to replicate this functionality on iOS. In Android we have "android.net.rtp" package to manage this and transmit or receive data streams over the network.
Is there any kind of equivalent package for iOS to implement this? Could you give me any kind of reference / sample to do this, or just tell me where to start?

A: You can see this libraryHTTPLiveStreaming, But his protocol maybe is not standard one, You can check my fork aelam/HTTPLiveStreaming-1, I'm still working on it, it can be played by ffplay. You can try
check the file rtp.c in ffmpeg, I think it will help out


text:
Q: SQL date and time select query incorrect time I have a query where the view table in postgres is getting "record" from another table with jsonb records where the output is like this >["Created": "2022-06-27T18:32:36Z","Modified": "2022-06-27T18:32:36Z"]
But the view is giving back inaccurate time, so I would like to know a solution to time format please.
  to_timestamp(checklist.record ->> 'Time'::text, 'HH24:MI:SS'::text)::time without time zone AS "time",
    timezone('utc'::text, timezone('Europe'::text, to_timestamp(checklist.record ->> 'Modified'::text, 'YYYY-MM-DD HH24:MI:SS'::text)))::date + to_timestamp(checklist.record ->> 'Modified'::text, 'HH24:MI:SS'::text)::time without time zone AS modified,
    timezone('utc'::text, timezone('Europe'::text, to_timestamp(checklist.record ->> 'Created'::text, 'YYYY-MM-DD HH24:MI:SS'::text)))::date + to_timestamp(checklist.record ->> 'Created'::text, 'HH24:MI:SS'::text)::time without time zone AS created,

I tried changing and using different time format like HH:MI:SS


text:
Q: Add auto-clear notification on Cordova FirebaseX plugin I'm trying to clear automatically a notification I received from the FirebaseX plugin on Ionic after one minute. It means that even if the user doesn't click on it, I want the notification to disappear.
For that I modified the plugins/cordova-plugin-firebasex/src/android/FirebasePlugin.java file where it appears to have the onMessageReceived function.
I know nothing in Java so I tried to add a sleep method before the same content of the clearAllNotifications function as this :
  private void onMessageReceived(final CallbackContext callbackContext) {
    FirebasePlugin.notificationCallbackContext = callbackContext;
    if (FirebasePlugin.notificationStack != null) {
        for (Bundle bundle : FirebasePlugin.notificationStack) {
            FirebasePlugin.sendMessage(bundle, applicationContext);
        }
        FirebasePlugin.notificationStack.clear();
    }

    // I want to wait one minute before it executes the code
    TimeUnit.SECONDS.sleep(60);

    // This code is a copy/paste from the clearAllNotifications function
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            try {
                NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
                nm.cancelAll();
                callbackContext.success();
            } catch (Exception e) {
                handleExceptionWithContext(e, callbackContext);
            }
        }
    });

}

But I receive an error when I try to build the app :

platforms/android/app/src/main/java/org/apache/cordova/firebase/FirebasePlugin.java:485:
error: unreported exception InterruptedException; must be caught or
declared to be thrown
TimeUnit.SECONDS.sleep(3);

How could I do to automatically clear a notification after some time ? I've already tried with the Handler method as suggested here but I have a similar error, maybe i'm not importing it well.
Thanks


text:
Q: Why is italicise not working in the overleaf code-\emph not working here I have written the following markup:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Title: SOP LaTeX Template
%% Author: Soonho Kong / soonhok@cs.cmu.edu
%% Created: 2012-11-12
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Requirement:
%%     You need to have the `Adobe Caslon Pro` font family.
%%     For more information, please visit:
%%     http://store1.adobe.com/cfusion/store/html/index.cfm?store=OLS-US&event=displayFontPackage&code=1712
%%
%% How to Compile:
%%     $ xelatex main.tex
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass[letterpaper]{article}
\usepackage[letterpaper,margin=1.75in,noheadfoot]{geometry}
\usepackage{fontspec, color, enumerate, sectsty}
\usepackage[normalem]{ulem}
\usepackage[utf8]{inputenc}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                      YOUR INFORMATION
%
%      PLEASE EDIT THE FOLLOWING LINES ACCORDINGLY!!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand{\soptitle}{Research Interest}
\newcommand{\yourname}{Tanushree Bhattacharya}
\newcommand{\youremail}{ug18tb@iacs.res.in}
\newcommand\action{\par\bigskip\noindent\itshape}

%% FONTS SETUP
\defaultfontfeatures{Mapping=tex-text}
\setromanfont[Path = fonts/, Ligatures={Common}]{adobe_caslon_pro}
\setmonofont[Path = fonts/, Scale=0.8]{monaco}
\setsansfont[Path = fonts/, Scale=0.9]{Optima-Regular}
\newcommand{\amper}{{\fontspec[Scale=.95]{Adobe Caslon Pro}\selectfont\itshape\&~{}}}
\usepackage[bookmarks, colorlinks, breaklinks,
pdftitle={\yourname - \soptitle},pdfauthor={\yourname}, unicode]{hyperref}
\hypersetup{linkcolor=magneta,citecolor=magenta,filecolor=magenta,urlcolor=[named]{WildStrawberry}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                      Title and Author Name
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\begin{center}{\huge \scshape \soptitle}\end{center}
\begin{center}\vspace{0.2em} {\Large \yourname\\}
  {\youremail}\end{center}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                      SOP Body
% NOTE: Use \amper instead of \&
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\vspace{-1cm}
\section*{}
I am Tanushree Bhattacharya a final year master's student pursuing an Integrated Bachelor's and Master's Programme at the \emph{Indian Association for the Cultivation of Science, Kolkata, India}.
\end{document}

Why is italicise not working in the overleaf code?


text:
Q: Ruby - Iterate through records found with SQL statement I have a bunch of records found with this SQL

select id from employee_holiday_years where start_date = '2015-01-01' and employee_id in(select id from employees where join_date > '2014-12-31') and allowance_from_last_year <> 0;

I need to iterate through the records returned by this SQL using Ruby and run a couple of Ruby commands against each one. Is this possible?

A: By ruby you can try this lets you have mysql adapter and ruby installed Also you have
Database Name TESTDB
username testuser
password test123
host:      localhost
  require "dbi"

  begin
   dbh = DBI.connect("DBI:Mysql:TESTDB:localhost",
                    "testuser", "test123")
   sth = dbh.prepare("select id from employee_holiday_years where start_date = '2015-01-01' and employee_id in(select id from employees where join_date > '2014-12-31') and allowance_from_last_year <> 0;")
   sth.execute(1000)

   #iterate through the return records
   sth.fetch do |row|
    printf row[0], row[1] #to print the row

   end
   sth.finish

  rescue DBI::DatabaseError => e
   puts "An error occurred"
   puts "Error code:    #{e.err}"
   puts "Error message: #{e.errstr}"
  ensure
   # disconnect from server
   dbh.disconnect if dbh
  end

For more Ruby Database Access

A: sql return Array so use Array iteration.
e.g
recoreds.each do |record|
  p record.inspect
end

A: This is what I came up with
client = Mysql2::Client.new(:host => "localhost", :username => "root", :database => "mydatabase")
results = client.query("select * from mytable where...", :symbolise_keys => true)

results.each do |row|
  do stuff...
end


text:
Q: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=?;AT YEAR YEARS MONTH MONTHS DAY DAYS HOUR HOURS MINUTE MINUTES, DRIVER=3.64.82 My code is looking like this:
addToTable2(ObjectDTO objectDTO) {
   def sql = sql.execute(
    """INSERT INTO SCHEMA.TABLE2 (
        COLUMN1,
        COLUMN2,
        COLUMN3 )
        VALUES (
         ${objectDTO.property1}
         ${objectDTO.property2}
         ${objectDTO.property3})""")
}

ArrayList<ObjectDTO> fetchValuesFromTable1() throws CollectionsException {

    ArrayList<ObjectDTO> fetchValues= new ArrayList<ObjectDTO>()
    def sql = """
        SELECT *
        FROM SCHEMA.TABLE1
        ORDER BY DATE DESC FETCH FIRST 1 ROW ONLY"""

    try {
      if(this.sql != null) {
        this.sql.eachRow(sql) {
          resultSet ->
            ObjectDTO objectDTO = new ObjectDTO()
            objectDTO.setProperty1(resultSet.PROPERTY1)
            objectDTO.setProperty2(resultSet.PROPERTY2)
            objectDTO.setPropety3(resultSet.PROPERTY3)

             objectList.add(poulSifr)
           }
         }

      for(ObjectDTO objectDTO: objectList) {
        addToTable2(objectDTO)
      }

    } catch (SQLException se) {
      log.info "fetchValues error $se.message  executed sql: $sql"
       throw new CollectionsException("fetchValues message $se.message")
    } finally {
      if (this.sql != null) {
        this.sql.close()
      }
    }
    objectList
  }

I got this error/warning:

WARN  groovy.sql.Sql - Failed to execute:  INSERT INTO SCHEMA.TABLE (
COLUMN1,
COLUMN2,
COLUMN3 )
VALUES (
?,
?,
null)
because: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=?;AT
YEAR YEARS MONTH MONTHS DAY DAYS HOUR HOURS MINUTE MINUTES,
DRIVER=3.64.82

Whenever I fetch last value from Table1 I need to put that in Table2. I don't know is this proper way to do it or I'm doing something completely wrong.

A: you have missing commas in VALUES(...) part of insert


text:
Q: How to store special charaters in MySQL - [AîA] I am wondering how I would go about storing this in MySQL
I am storing it by posting it from a greasemonkey script to php to insert it into a MySQL database.
So far [AîA] turns into [AîA]
this is part of my post function:
GM_xmlhttpRequest({
    method: "POST",
    url: URL + "Script/player.php",
    data: LoginUrl,

    headers: {
        "User-Agent":"Update Script",
        "Content-Type": "application/x-www-form-urlencoded"
    },

I think I might need to change the Content type too UTF-8 but when I tried this it broke the script. I also tried using:
encodeURIComponent(Name)

But this didn't work properly or was broken because of not setting header properly.

A: In the PHP file that submits the information into the database I had to set the charset using
mysql_set_charset()

Final connection code:
$conn = mysql_connect($host, $user, $pass);
mysql_select_db($db, $conn);
mysql_set_charset('utf8',$conn);

Thanks Hakre for answer.


text:
Q: How to display LinkedIn feeds on my website in php? I would like to show my company Linkedin feed on my website (a WordPress site),For fetching LinkedIn feeds, i created LinkedIn company page and post some feeds on that page. After that i created app on https://www.linkedin.com/developer/, i and got client ID, client Secret Key, i also got access token of my app. But i'm not understanding, how can i make LinkedIn API so that i can display LinkedIn feeds on my website. Actually i don't want to display feeds by iframe way. I want display feeds on my custom html. I have tried Using PHP LinkedIn SDK as following.
$li = new LinkedIn(array(
    'api_key' => "client secret",
    'api_secret' => "client ID",
    'callback_url' => "redirecturl"
));

$token = $li->setAccessToken('Your access token');

$feeds = $li->fetch('GET', '/v2/companies/company-id/updates?event-type=status-update&start=0&count=6&format=json');

$posts = $li->get('/companies/79097881/updates/');

$pages = json_decode(file_get_contents($posts));

echo "<pre>"; print_r($pages);

But i didn't get anything. So please provide me some solution.


text:
Q: utf8x.def not found Mac I'm trying to compile a latex file from coq on Mac and get the following error:
File utf8x.def not found.
Where can I find utf8x.def?
Most of the other answers pertain to ubuntu and don't work on mac.

A: If you installed BasicTeX or a manual install on Linux, you can use tlmgr and run sudo tlmgr install ucs which installs the ucs package which includes utf8x.
If you installed with apt-get on linux, use sudo apt-get install texlive-latex-extra