text:
Q: PHP Array Unique I believe my issue is fairly basic and simple, but I think I am not getting through it.I have a PHP array which has been dynamically populated with data from the database
    $PInvoicesList=array();
    $SelectPInvoicesList ="SELECT * FROM AllDataEntriesList
                            WHERE BusinessID = '{$businessid}'
                            AND DocumentType = 'purchaseinvoice'
                            ORDER BY Time ASC;";
    $SelectPInvoicesList_query = mysqli_query($connection, $SelectPInvoicesList);
    if(!$SelectPInvoicesList_query){
        die ("Database query for searching Purchase Invoices failed.".mysqli_error($connection));
    }
    while ($SelectPInvoicesList_array = mysqli_fetch_assoc($SelectPInvoicesList_query)){

        $PInvoicesList[]=$SelectPInvoicesList_array["DocumentID"];
    }
    array_unique($PInvoicesList);
    print_r($PInvoicesList);

And this gives me an array
Array ( [0] => pk-000000003-purchaseinvoice-1
        [1] => pk-000000003-purchaseinvoice-1
      )

When I apply array_unique($PInvoicesList, SORT_STRING);, I get both of both elements in the array, whereas they both have the same data. I used this function as array_unique($PInvoicesList, SORT_REGULAR); but still both the elements in the array are appearing and they have the exact same data. Can anyone guide me how can I remove the elements with duplicate values from this array?

A: The array_unique() removes duplicate values from an array. Just use array_unique()
Refer this http://php.net/manual/en/function.array-unique.php
$result = array_unique($PInvoicesList);


text:
Q: Contains method in Java doesn't exist? I am trying to make a java script for a mobile app check if a string contains specific characters.
if(fn.contains(" ")){

}

The fn variable is declared twice in the following:
private EditText fn;
final EditText fn = (EditText) findViewById(R.id.fn);

Not sure why this doesn't work. In android studio, the contains function highlights red as it doesn't exist. You can click here to see what I am talking about. Is there another method than this?

A: That is an EditText not a string you must do first:
var str = fn.getText().toString()

if(str.indexOf(" ") !== -1;){ . . . }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Symbolic integration of Student's t density in MATLAB I want to integrate the student's t-density in MATLAB but MATLAB seems to fail and just returns the same expression without calculations. Any ideas on how to proceed. I know it should evaluate to 1 but what is the trick to force MATLAB to do it.
syms x s mu nu

g = @(x) gamma(1/2*(nu+1))/(gamma(nu/2)*sqrt(pi*nu*s^2))*(1 + 1/nu*(x-mu)^2/s^2)^(-1/2*(nu+1));

int(g(x), x, -inf, inf)

A: I just tried it in this way:
syms x nu mu s
f = gamma(1/2*(nu+1))/(gamma(nu/2)*sqrt(pi*nu*s^2))*(1 + 1/nu*(x-mu)^2/s^2)^(-1/2*(nu+1))
int(f)

And it works! I got some answer:
-(gamma(nu/2 + 1/2)*(mu - x)*hypergeom([1/2, nu/2 + 1/2], 3/2, -(mu - x)^2/(nu*s^2)))/(pi^(1/2)*gamma(nu/2)*(nu*s^2)^(1/2))

But if i try definite integration it doesn't works:
int(f, 0, 1)
ans =
int(gamma(nu/2 + 1/2)/(pi^(1/2)*gamma(nu/2)*((mu - x)^2/(nu*s^2) + 1)^(nu/2 + 1/2)*(nu*s^2)^(1/2)), x, 0, 1)

So i went to the help and read this:
If MATLAB is unable to find an answer to the integral of a function f, it just returns int(f). (http://www.mathworks.com/help/symbolic/integration.html)
so the answer is that it can't be solved!

A: I believe your expression is to complicated for analytical integration. However, your expression seems to be correct and gives exactly 1 if you're using numerical integration:
nu = 60.2; % random number
mu = 1.3; % random number
s = 1e6; % random number

g = @(x) gamma(1/2*(nu+1))/(gamma(nu/2)*sqrt(pi*nu*s^2))*(1 + 1/nu.*(x-mu).^2/s^2).^(-1/2*(nu+1));
integral(g, -inf, inf)

gives
ans = 1.000

Of course, this is just a small workaround for certain nu, mu and s.

A: I don't have Matlab, but I can do this in Maple, and I know that Matlab's symbolic computation is very similar to Maple. You need to assume s > 0, then make a substitution z = (x-mu)/s, then assume nu > 0. In Maple code:
f:= GAMMA(1/2*(nu+1))/(GAMMA(nu/2)*sqrt(Pi*nu*s^2))*(1 + 1/nu*(x-mu)^2/s^2)^(-1/2*(nu+1)):
J:= Int(f, x= -infinity..infinity):
J1:= IntegrationTools:-Change(J, z= (x-mu)/s, [z]) assuming s > 0:
value(J1) assuming nu > 0;

If you do this, then the answer 1 is returned nearly instantly. Note that GAMMA is uppercase and Pi is capitalized in Maple.


text:
Q: What is the Correct Term for a Curve Segment on the Surface of a Cylinder? A line segment defines a finite portion of an infinite line, and my understanding is that an arc defines a finite portion of the circumference of a circle.
What is the correct "umbrella term" for the segment defined by any two points on the surface of a cylinder?

My concern in definition is that, if two points are defined along the long axis of the cylinder, it can define a straight line segment.  If the points are defined circumferentially, the resulting segment can be a circular arc, but defined randomly, it is some arbitrary curve.
I am not looking for a "cylindrical segment" (truncated cylinder), a solid cut from a cylinder by a plane.  I am simply confused as to the name of the resulting finite curve defined by those two points.
Thank you.


text:
Q: Nginx if operators Good morning programmers, I'm trying to protect a file, and for that I'm checking the http_referer that is opening it. Example:
if ($http_referer != "stackoverflow.com") {
    return 403;
}

So far so good, this sentence works well, in this case I don't want the equal operator but I want the contain operator like "!~", so I turned it into:
if ($http_referer !~ "stackoverflow.com") {
    return 403;
}

Still, it works well too, but in order to make everything run flawless I need to use variables on the string like this:
set $website stackoverflow.com;
if ($http_referer != $website) {
    return 403;
}

The issue here is that I can use variables with the "!=" operator but it doesn't work with the "!~" in this case the sentence I gave works, but this sentence down here doesn't work:
set $website stackoverflow.com;
if ($http_referer !~ $website) {
    return 403;
}

What I'm doing wrong?
P.S: if you don't get the if, you can't open the file if your http referer doesn't contain "stackoverflow.com"

A: As far as I know you can't use variables inside the regex patterns in the nginx config. I think that's because they are compiled at the nginx startup. General solution for this is to use the map block:
map $http_referer $valid_value {
    ~stackoverflow\.com    1;
}

and then check the resulting variable value:
if ($valid_value != 1) {
    return 403;
}

But for checking exactly the Referer HTTP header value there exists a special valid_referers directive where you can use a regular expression(s):
valid_referers ~stackoverflow\.com;
if ($invalid_referer) {
    return 403;
}


text:
Q: getch undefined while compiling for the second time I am using visual studio 2017 .
First I wrote the following code :
void main()
{

printf("abcdefgh %d hjhjh %d", 5, 6);

getch();

}

It ran perfectly fine .
But after that I modified the code to the following :
void main()
{
char abc[100];

strcpy_S(abc, "premraj");
    printf("%s", abc);

printf("abcdefgh %d hjhjh %d", 5, 6);

getch();

}

But now I am getting an error with getch stating that "'getch' undefined, assuming extern returning int"
But this new code has been built on the existing code which recognized getch perfectly , how can it not recognize getch the second time ?
I checked out the following question :
getch() is working without conio.h - how is that possible?
which also carried a similar problem but here with modifications only I got this error .
There is an informative answer there by user named "Fatal Error" but still I would like to know about this intriguing phenomenon that is coming in after modifications . What can be the reason behind this ?
P.S : The following was my header file declarations for the first  time :
#include <stdio.h>

and the following for the second time :
#include <stdio.h>
#include <string.h>

A: Once upon a time, if you called a function which the compiler had never heard of, like this:
#include <stdio.h>
int main()
{
    int x = foo();
    printf("%d\n", foo);
}

Anyway, if you did that, the compiler quietly assumed that foo() was a function returning int.  That is, the compiler behaved just as if you had typed
extern int foo();

somewhere before you called foo.
But in, I think, C99, the language was changed.  It was no longer legal to call a function you had not explicitly declared.  Because there was lots and lots of code out there that was written under the previous set of rules, most compilers did not immediately begin rejecting the old-style code.  Some continued to quietly assume that unrecognized functions returned int.  Others -- like yours -- began noisily assuming that unrecognized functions returned int, emitting warnings along the lines of "'foo' undefined, assuming extern returning int".
It sounds like your question is that some time ago, your code containing calls to getch() was accepted without warning, but today, you're getting the warning  "'getch' undefined, assuming extern returning int".  What changed?
One possibility is that your code changed slightly.  If your code used to contain the line
#include <conio.h>

somewhere, that file would have contained a declaration along the lines of
extern int getch();

and this would have goven the compiler the declaration that it needed, and you would not have gotten the warning.  But if today your code does not contain that #include line, that explain why the warning started cropping up.
It's also possible that your compiler has changed somehow.  It's possible you're using a new version of the compiler, that's more fussy, that has gone from quietly assuming, to normally assuming.  Or, it's possible that your compiler options have changed.  Many compilers can be configured to accept different variants of the language, corresponding to the different versions of the language standards that have been released over the years.  For example, if some time ago your compiler was compiling for language standard "C89", but today, it's doing "C99" or "C11", that would explain why it's now being noisy with this warning.
The change in the compiler could be a change in the defaults as configured by a system administrator, or a change in the way you're invoking the compiler, or a change in your project's Makefile, or a change in the language settings in your IDE, or something like that.
A few more points:

*

*getch is not a Standard C function; it's specific to Windows.  Your program would be more portable, in general, if you didn't use it.  Are you sure you need it?  (I know what it's for; what I don't know if there's some other way of keeping your program's output window on the screen after if exits.)

*You should get in the habit of declaring main() as int, not void.  (void will work well enough, but it's not correct, and if nothing else, you'll get lots of negative comments about it.)

*I think there's something wrong with your call to strcpy_S, too,


text:
Q: Netty SSL handler fails incorrectly on badssl.com I'm developing an application that uses Netty to manage its SSL/TLS connections. I'm trying to test that it handles various certificate errors correctly, for which I use badssl.com.
However, when I attempt to connect to badssl.com, an exception is thrown (full callstack traces edited and removed for brevity & clarity):
 An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
    io.netty.handler.codec.DecoderException: javax.net.ssl.SSLHandshakeException: Handshake failed
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:442)
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:248)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:372)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:358)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:350)
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)

...
    Caused by: javax.net.ssl.SSLHandshakeException: Handshake failed
        at com.android.org.conscrypt.OpenSSLEngineImpl.unwrap(OpenSSLEngineImpl.java:436)
        at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:1006)
        at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1094)

...

    Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:318)
        at com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:219)
...
    Caused by: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:318)
        at com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:219)
        at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:113)

The following guide for Android developers links Trust anchor for certification path not found. exceptions with unidentified CAs, self signed certificates, or missing intermediate CAs. But this is not the case with badssl.com - the phone's browser recognizes the certificates, and I can even use HTTPSUrlConnection successfully to contact it.
When I use InsecureTrustManagerFactory.INSTANCE to initialize my security Netty connects successfully, but this isn't a long term solution.
Here are the relevant code snippets:
Initialize SslContext
    sslContext = SslContextBuilder
            .forClient()
            .sslProvider(SslProvider.JDK)
            // TODO p0: Ensure all the versions we support have this algorithm installed
            //.trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();

Add SSL handler:
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(sslContext.newHandler(ch.alloc(), host.getHostName(), host.getPort()));

Write HTTP request after authentication:
            ChannelFuture future = bootstrap.connect(host).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    String request = "GET https://badssl.com/\n" +
                            "Host: +" + host.getHostName() + "\n" +
                            "Accept: text/html,application/xhtml+xml,application/xml;"
                            + "DNT: 1\n\n";

                    future.channel().writeAndFlush(Unpooled.copiedBuffer(
                            request, Charset.forName("ASCII")));
                }

What's going on here? Why isn't badssl.com recognized? I also tried a few domains with known bad certificates where the connection seemed to erroneously succeed. The only example given for SSL clients is SecureChatClient, which uses InsecureTrustManager.
I'm using Netty 4.1 and my test phone is an LG G3 with Android 5.0.

A: My guess is that your code does not use Server Name Indication (SNI). In this case the TLS handshake to badssl.com will result in the certificate:
Subject: ...CN=badssl-fallback-unknown-subdomain-or-no-sni
Issuer:  ...CN=BadSSL Intermediate Certificate Authority

This certificate is issued by BadSSL itself and the code correctly complains about Trust anchor for certification path not found because this certificate is not signed by a trusted CA.

.. I can even use HTTPSUrlConnection successfully ..

HTTPSUrlConnection make use of SNI and this the server sends a different certificate which is signed by a trusted CA:
Subject: ... CN=*.badssl.com
Issuer:  ... CN=COMODO RSA Domain Validation Secure Server CA

Unfortunately documentation of how to use SNI on the client side seems to be rare but it looks like that missing support is a problem others noticed too and maybe there is fix in later versions of Netty.


text:
Q: should we delete the observer when unregister it? Observer *o = New Observer();
Subject *s = new Subject() ;
s->register(o);

//Is it a good practice to delete the observer in the unregister function?
//I feel it is not. As the Observer object might still be in use,  for example ,
//it might be registered to another Subject.
s->unregister(o);

//So it is safe to rely on the client code to delete the object or rely on the smart pointer things
delete o;

I want to confirm whether my above understanding is correct regarding who should delete the observer object.

A: I agree with your observation. It is not a good practice to delete the observer in the unregister function - for the simple fact that "one who creates the resource must be responsible for deleting the resource"
This will avoid

*

*Magic behavior as perceived by the creator.

*Code behavior will be well defined - one who creates must delete. Which will lay overall foundation of understanding of development for new developers to your system.

Similar topic are discussed under lengths in all books with different nomenclature.

A: I would say use smart pointers as no need to remember to call the delete explictly.

A: From a design point of view it should be superfluous (while not wrong) to unregister the subjects, if the observer is well implemented. Relying on external code for a behaviour to be robust if it can be enforced can always be considered as poor design.
Regarding the use of smart pointers, if you need the control on the destruction point for some reason (close files at a given point in time for example to avoid access problems in later code) then you should delete explicitly, otherwise it is far more comfortable to rely on smart pointers. That is why there are existing.

A: As the Subject did not allocate the Observer, it should not attempt to deallocate it. This allows the client of Subject to manage the lifetime and allocation strategy of Observers in any way it chooses (custom allocator, statically allocated, automatic variable). It doesn't force the client to use new.
Obviously it is still to clients responsibility not to allow the Observer to be destroyed before it is "unregistered".
E.g.
Observer o;
Subject s;

s.register(&o); // could take a reference

// ...

s.unregister(&o);

// No potential for forgotten deletes

A: It depends on your design. I personally prefer that deleting the Observer will automatically disassociate it with the subject, i.e deregister itself in the destructor. That saves the need to bother to deregister, which would require you to have references to both the Subject and the Observer at the point of destruction.

A: Smartpointer or client code  (do not transfer ownership if possible)
If client code has created the object let the same code to destroy it :)

A: Another argument against deleting is what the Subject object communicates.
By deleting the object your Subject object has taken ownership of the object, as it controls its lifetime. As a raw pointer is passed into the object, and not an auto_ptr or an unique_ptr I would assume as a user of Subject that it does not take ownership of the object without looking at the code. So I would say that the interface of Subject does not communicate that it takes ownership of the object. So Subject should not delete it, because someone else (probably) has ownership of it.

A: In general, you should avoid side effects like deleting the pointer to an object in a container, unless the container is responsible for creating the pointer as well.
The problems of pointers with the Observer pattern runs a bit deeper than this as well.
An Observer inherently has a reference of some kind to the Subject.  If that reference is a direct reference (e.g. not a handle), then if that object goes out of scope or gets deleted, when the Observer makes a Notify(...) call, it will throw an exception (or worse).  So you must ensure you Detach(...) from the observer when you delete the Subject.
Forgetting to do this is a problem, so I like the idea of building it into the base class of the virtual destructor.  This also means that the Subject has knowledge of the Observer (a reference to it) so it can call Detach(...).  Which puts you into a similar situation with the Observer (i.e. if it gets deleted).  The approach I have found simplest to use is to have the Observer actually be a singleton with Subjects registering for particular notifications, not just "I have some state for you to update".  This is consistent with the GoF Page 298, item 7, "Specifying modifications of interest explicitly".  Also, just plain makes sense to narrow the field on updates a bit.  It also allows hooking up any Subject form anywhere easier.
Another case to consider is when the Subject is deleted during your Notify(..) iteration.  In your Observer, you have a list of Subjects, A, B, and C.  You change state and call Notify(...) on A.  A deletes B.  Now you move on to call Notify(...) on B, which does not exist.  If you had it Detach(...) in the destructor, B may not be on the list any more.  But it might still if you chose to iterate over a copy of the Subjects you started with instead of the actual list (been there, done that).  Your Observer needs to handle a Detach(...) call during iteration for a Notify(...) for this reason.
I have a worked out example of this posted on a blog here.


text:
Q: How can I use CGContextDrawTiledImage to tile an image? I want to be able to an UI object like a UIImageView and tile an image inside of it.
I have been able to use CGContextDrawTiledImage to update the background in the main window, but not an image view. I can do this if I modify the drawRect function inside the MainView class.
I feel I'm close, but still missing something. Can someone point me in the right direction?
- (void)drawRect:(CGRect)rect {

CGImageRef image = CGImageRetain(currentImage.CGImage);

CGRect imageRect;
imageRect.origin = CGPointMake(160, 240);
imageRect.size = CGSizeMake(320.0, 480.0);

CGContextRef uiContext = UIGraphicsGetCurrentContext();

CGContextClipToRect(uiContext, CGRectMake(0.0, 0.0, rect.size.width, rect.size.height));

CGContextDrawTiledImage(uiContext, imageRect, image);

}

A: If you just want to tile an image in the view, change it to a normal UIView and tile the background with UIColor initWithPatternImage:
backgroundView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageWithContentsOfFile:[self bundlePath:@"some_tile_image.png" inDirectory:@"tiles"]]];

A: Rather than trying to modify a UIImageView, consider subclassing UIView instead.  UIImageView is specifically designed for one non-tiled image and some of the internals may be messing you up.  It's not really intended to be modified in the way you describe.
In a subclass of UIView (UITiledImageView?) you can use the drawRect: method to do what you want.  You can even create ivars for the image, its size and tiling properties for greater flexibility and extensibility.
Updated with sample project: http://github.com/kailoa/6tringle-tiledimageview/tree/master
The relevant drawing code:
- (void)drawRect:(CGRect)rect
{
    if (TiledImage) {

        //Since we are retaining the image, we append with ret_ref.  this reminds us to release at a later date.
        CGImageRef image_to_tile_ret_ref = CGImageRetain(TiledImage.CGImage);

        CGRect image_rect;
        image_rect.size = TiledImage.size;  //This sets the tile to the native size of the image.  Change this value to adjust the size of an indivitual "tile."

        CGContextRef context = UIGraphicsGetCurrentContext();

        CGContextDrawTiledImage(context, image_rect, image_to_tile_ret_ref);

        CGImageRelease(image_to_tile_ret_ref);
    }
}

A: Let's say you've got a CGImageRef for the image you want to tile called tileImage and a UIImageView called imageView. What you need to do is create a UIImage to assign to the image property of imageView. You can do that like this:
CGSize imageViewSize = imageView.bounds.size;
UIGraphicsBeginImageContext(imageViewSize);
CGContextRef imageContext = UIGraphicsGetCurrentContext();
CGContextDrawTiledImage(imageContext, (CGRect){ CGPointZero, imageViewSize }, tileImage);
UIImage *finishedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

imageView.image = finishedImage;

This will create a bitmap image context of the desired size, tile the image into that context, get a UIImage out of the context, then assign it to the UIImageView. You can really put this code anywhere so long as the image view and tile image are loaded and ready to go.

A: Sorry for not knowing how to add comment to other's answers, so I created a new answer here:
I just want to point out the answer provided by Kailoa Kadano has a bug, the image_rect.origin is not initialized properly.
About 3 weeks ago, I copied his code in my project, and it seems working. However, yesterday, I tried to run the code in ios simulator(iphone 4.3), it just hang in CGContextDrawTiledImage.
After adding the following line as showed in keremk's answer:
image_rect.origin = CGPointMake(0.0, 0.0);

it works again!
It's rather tricky, actually at first I tested under iphone 4.3 simulator, then recently I tested under iphone 4.0 simulator, then yesterday when I switched back to 4.3 simulator or 4.2 simulator, the problem occurs. That is the image_rect.origin is undefined, sometimes it's zero data, maybe sometimes it has some random data.

A: I recently did this by creating a custom UIView.
@interface TiledImageView : UIView {
@private
    UIImage *image_;
}

@property (nonatomic, retain) UIImage *image;
@end

and for the .m file:
@implementation TiledImageView
@synthesize image = image_;

- (void)dealloc {
    [image_ release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
        self.image = [UIImage imageNamed:@"BGTile.png"];

    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGImageRef image = CGImageRetain(image_.CGImage);

    CGRect imageRect;
    imageRect.origin = CGPointMake(0.0, 0.0);
    imageRect.size = CGSizeMake(CGImageGetWidth(image), CGImageGetHeight(image));

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToRect(context, CGRectMake(0.0, 0.0, rect.size.width, rect.size.height));
    CGContextDrawTiledImage(context, imageRect, image);
    CGImageRelease(image);
}

@end


text:
Q: Getting an Error- "generator.exe" exited with code -532462766" - RazorPay Integration Getting an Error- "generator.exe" exited with code -532462766" while converting the Razorpay .aar file into DDL by using the Xamarin android binding project.
Build Action: LibraryprojectZip click to view current configuration details of the application


text:
Q: What does this error means Cannot find source for binding with reference I am trying to bind Control Property
This is my second day trying and can't make it work. I am getting an error

"Cannot find source for binding with reference 'ElementName=_this'.
BindingExpression:Path=PlaceHolder; DataItem=null; target element is
'TextBlock' (Name='title'); target property is 'Text' (type 'String').
Cannot find source for binding with reference 'ElementName=_this'.
BindingExpression:Path=Text; DataItem=null; target element is
'TextBox' (Name='email'); target property is 'Text' (type 'String')"

I have follow the tutorial but cant find the error. thank you for your help.
frontend page
<CustomControls:TextBoxAnimatedPlaceholder
        Grid.Row="1"
        Grid.Column="2"
        PlaceHolder="Email" />
    <CustomControls:TextBoxAnimatedPlaceholder
        Grid.Row="2"
        Grid.Column="2"
        PlaceHolder="Password"
        />

Custom control
<UserControl x:Class="WpfApp1.CustomControls.TextBoxAnimatedPlaceholder"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WpfApp1.CustomControls"
         mc:Ignorable="d"
         MinWidth="300">
<UserControl.Resources>
    <Style x:Key="credentialTxTtitleStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="Text" Value="{Binding PlaceHolder, ElementName=_this}"/>
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="VerticalAlignment" Value="Center"/>
        <Setter Property="Foreground" Value="#a3a3a4" />
        <Setter Property="FontSize" Value="20"/>

        <Setter Property="Padding" Value="2,0" />
        <Style.Triggers >
            <DataTrigger Binding= "{Binding Text, ElementName=email}" Value="">
                <DataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard SpeedRatio="10">
                            <DoubleAnimation Storyboard.TargetProperty="FontSize" To="20"/>
                            <ThicknessAnimation Storyboard.TargetProperty="Margin" To="0" />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>

                <DataTrigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard SpeedRatio="10">
                            <DoubleAnimation Storyboard.TargetProperty="FontSize" To="15"/>
                            <ThicknessAnimation Storyboard.TargetProperty="Margin" To="0 0 0 30" />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.ExitActions>
            </DataTrigger>

        </Style.Triggers>

    </Style>
    <Style x:Key="credentialTxTStyle" TargetType="{x:Type TextBox}">
        <Setter Property="Text" Value="{Binding Text, Mode=TwoWay ,  ElementName=_this}"/>
        <Setter Property="TextAlignment" Value="Left"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
        <Setter Property="FontWeight" Value="SemiBold"/>
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="BorderThickness" Value="0" />
        <Style.Triggers >
            <DataTrigger Binding="{Binding FontSize, ElementName=title}" Value="15">
                <DataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard SpeedRatio="10">
                            <DoubleAnimation Storyboard.TargetProperty="FontSize" To="20"/>
                            <ThicknessAnimation Storyboard.TargetProperty="Margin" To="0 20 0 0 " />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>

                <DataTrigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard SpeedRatio="10">
                            <DoubleAnimation Storyboard.TargetProperty="FontSize" To="15"/>
                            <ThicknessAnimation Storyboard.TargetProperty="Margin" To="0" />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.ExitActions>
            </DataTrigger>

        </Style.Triggers>

    </Style>
</UserControl.Resources>
<Border
    CornerRadius="10"
    Background="White"
    Height="70">

    <Border.Effect>
        <DropShadowEffect BlurRadius="23" ShadowDepth="5" Direction="270" Color="WhiteSmoke"></DropShadowEffect>
    </Border.Effect>

    <Grid Margin="20,6">
        <TextBlock
            x:Name="title"
            Style="{StaticResource credentialTxTtitleStyle}" />
        <TextBox
            x:Name="email"
            Style="{StaticResource credentialTxTStyle}" />
    </Grid>

</Border>

code behind
 public string PlaceHolder
        {
            get { return (string)GetValue(PlaceHolderProperty); }
            set { SetValue(PlaceHolderProperty, value); }
        }

        // Using a DependencyProperty as the backing store for PlaceHolder.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PlaceHolderProperty =
            DependencyProperty.Register("PlaceHolder", typeof(string), typeof(TextBoxAnimatedPlaceholder));

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Test.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(TextBoxAnimatedPlaceholder));

A: Clemens comment solved my issue by changing the binding instruction to " {Binding PlaceHolder, RelativeSource={RelativeSource AncestorType=UserControl}} "
Thank you Clemens, I've been trying for days . I was following this video 1 I asked the author but he deleted my questions after my first post.


text:
Q: What does it mean by Kademlia keys are used to identify nodes as well as data? Okay, I've been reading articles and the paper about Kademlia recently to implement a simple p2p program that uses kademlia dht algorithm. And those papers are saying, those 160-bit key in a Kademlia Node is used to identify both nodes (Node ID) and the data (which are stored in a form of  tuple).
I'm quite confused on that 'both' part.
As far as my understanding goes, each node in a Kademlia binary tree uniquely represents a client(IP, port) who each holds a list of files.
Here is the general flow on my understanding.

*

*Client (.exe) gets booted

*Creates a node component

*Newly created node joins the network (bootstrapping)

*Sends find_node(filehash) to k-closest nodes

*

*Let's say hash is generated by hashing file binary named file1.txt

*Received nodes each finds the queried filehash in its different hash table

*

*Say, a hash map that has a list of files(File Hash, file location)

*Step 4,5 repeated until the node is found (meanwhile all associated nodes are updating the buckets)

Does this flow look all right?
Additionally, bootstrapping method of Kademlia too confuses me.
When the node gets created (user executes the program), It seems like it uses bootstrapping node to fill up the buckets. But then what's bootstrapping node? Is it another process that's always running? What if the bootstrapping node gets turned off?
Can someone help me better understand the concept?
Thanks for the help in advance.

A:
Does this flow look all right?

It seems roughly correct, but your wording is not very precise.
Each node has a routing table by which it organizes the neighbors it knows about and another table in which it organizes the data it is asked to store by others. Nodes have a quasi-random ID that determines their position in the routing keyspace. The hashes of keys for stored data don't precisely match any particular node ID, so the data is stored on the nodes whose ID is closest to the hash, as determined by the distance metric. That's how node IDs and key hashes are used for both.
When you perform a lookup for data (i.e. find_value) you ask the remote nodes for the k-closest neighbor set they have in their routing table, which will allow you to home in on the k-closest set for a particular target key. The same query also asks the remote node to return any data they have matching that target ID.
When you perform a find_node on the other hand you're only asking them for the closest neighbors but not for data. This is primarily used for routing table maintenance where you're not looking for any data.
Those are the abstract operations, if needed an actual implementation could separate the lookup from the data retrieval, i.e. first perform a find_node and then use the result set to perform one or more separate get operations that don't involve additional neighbor lookups (similar to the store operation).
Since kademlia is UDP-based you can't really serve arbitrary files because those could easily exceed reasonable UDP packet sizes. So in practice kademlia usually just serves as a hash table for small binary values (e.g. contact information, public keys and such). Bulk operations are either performed by other protocols bootstrapped off those values or by additional operations beyond those mentioned in the kademlia paper.
What the paper describes is only the basic functionality for a routing algorithm and most basic key value storage. It is a spherical cow in a vacuum. Actual implementations usually need additional features or work around security and reliability problems faced on the public internet.

But then what's bootstrapping node? Is it another process that's always running? What if the bootstrapping node gets turned off?

That's covered in this question (by example of the bittorrent DHT)


text:
Q: Double apps on Ubuntu Dock Last week I installed Ubuntu 20.04.2 LTS. It seems when computer goes to sleep and re login, this happens:

I used Tweaks & Dconf Editor to customize desktop.
Any help would be appreciated!

A: You may have more than one "Dock" extension enabled, e.g., Dash to Dock and Ubuntu Dock.


text:
Q: StructureMap, configure using container or objectfactory? I did my configuration like this:
var container = new Container(x =>
                                              {
                                                  x.For<IEngine>().Use<V6Engine>();
                                                  x.For<ICar>().Use<HondaCar>();
                                              }
);

Then in my mvc controller action I did:
ICar car = ObjectFactory.GetInstance<ICar>();

Should I be setting up my container using Container or ObjectFactory somehow?  It didn't resolve, so I tested things out in a c# console application and it worked if I did:
ICar car = container.GetInstance<ICar>();

But this only works if container is in local scope, and in a web app it isn't obviously since things are wired up in global.asax.cs

A: ObjectFactory is a static gateway for an instance of container. If you only ever want one instance of a container, and want a simple static way to get at it, use ObjectFactory. You must Initialize the ObjectFactory, and then retrieve your instances via ObjectFactory.
Alternatively, if you want to manage the lifetime of the container yourself, you can create an instance of Container, passing an initialization expression to the constructor. You then retrieve instances from the variable you declared to store the Container.
In your example, you are mixing the two approaches, which doesn't work.

A: I have got mine configured as below
global.asax
  ObjectFactory.Initialize(action =>
            {
                action.For<ISomething>().Use<Something>;
            });

Then everywhere else.
 ObjectFactory.GetInstance<ISomething>();

This may not be the only way though. Also I think what you might be looking for is the
Scan(scanner =>
        {
            scanner.AssemblyContainingType(....);
            scanner.AddAllTypesOf(....);
        }


text:
Q: How to connect a QgsMaptool with a widget pushButton I've write this QgsMaptool above and it works great in python console
imports...

class obsCreator(QgsMapToolEmitPoint):

    def __init__(self, iface):
        self.iface = iface
        self.canvas = QgsMapCanvas()
        QgsMapTool.__init__(self, self.canvas)
        QgsMapToolEmitPoint.__init__(self, self.canvas)
        self.layer = self.canvas.currentLayer()
        self.x = float
        self.y = float

    def canvasPressEvent(self, event):
        point = self.toLayerCoordinates(self.canvas.mouseLastXY())
        self.x = point[0]
        self.y = point[1]

    def canvasReleaseEvent(self, event):
        feats = []
        pr = self.layer.dataProvider()
        fields = self.layer.fields()
        fet = QgsFeature
        geom = QgsGeometry().fromPointXY(QgsPointXY(self.x, self.y))
        fet.setgeometry(geom)
        feats.append(fet)
        fet.setAttributes([1, 'test'])

        if event.button() == Qt.RightButton:
            self.canvas.unsetMapTool(self)
        else:
            pr.addFeatures(feats)
            self.layer.triggerRepaint()
        pr.addFeatures(feats)
        self.layer.triggerRepaint()

but, I want to connect it with a pushButton in my dockwidget:
    def run(self):
        if not self.pluginIsActive:
            self.pluginIsActive = True

            if self.dockwidget == None:
                self.dockwidget = revEnvDockWidget()

            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
            self.dockwidget.show()

            # Clear comboBox (useful so we don't create duplicate items in list)
            self.dockwidget.obsComboBox.clear()

            # Add all items in list to comboBox
            self.dockwidget.obsComboBox.addItems(Handler.obsListCombo(self))

            canvas_clicked = obsCreator(iface.mapCanvas())
            self.dockwidget.hookPushButton.clicked.connect(iface.mapCanvas().setMapTool(canvas_clicked))

and I get this error:
WARNING    Traceback (most recent call last):
              File "E:\_Code\QGIS\rev_env\rev_env.py", line 268, in run
              self.dockwidget.hookPushButton.clicked.connect(iface.mapCanvas().setMapTool(canvas_clicked))
             TypeError: argument 1 has unexpected type 'NoneType'

I`ve based my code in this question: How to get co ordinates of points on mouse click in PyQGIS.
Am I missing somethig?

A: Based on @BenW comment I use a lambda function to pass a dockwidget parameter and it works perfectly.
 def run(self):
        if not self.pluginIsActive:
            self.pluginIsActive = True

            if self.dockwidget == None:
                self.dockwidget = revEnvDockWidget()

            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
            self.dockwidget.show()

            # Clear comboBox (useful so we don't create duplicate items in list)
            self.dockwidget.obsComboBox.clear()

            # Add all items in list to comboBox
            self.dockwidget.obsComboBox.addItems(Handler.obsListCombo(self))

            self.canvas_clicked = HookCreator(self.iface.mapCanvas(), self.dockwidget)
            self.dockwidget.hookPushButton.clicked.connect(lambda: self.iface.mapCanvas().setMapTool(self.canvas_clicked))


text:
Q: TCP Server-Client disconnects after a single transmission I'm working on a Server-Client program for school and using a given code for the TCP connections.
The client side:
void func(int sockfd)
{
char entryArr[MAXSIZE][MAXLEN];
int n,c;
int i = 0;
char entry;
char iEntry[1];
char id[6];
char fname[5];
char lname[5];
char score[4];
for (;;) {
    bzero(id, sizeof(id));
    bzero(fname, sizeof(fname));
    bzero(lname, sizeof(lname));
    bzero(score, sizeof(score));
    printf("[1] Add a Student \n");     //Menu
    printf("[2] Display ID \n");
    printf("[3] Display Score \n");
    printf("[4] Display All \n");
    printf("[5] Delete an Entry \n");
    printf("[6] Exit \n");
    printf("Please Select from the Menu: ");  //get menu selection
    scanf("%1s", iEntry);   //read entry

    if (iEntry[0] == '1') //if entry = 1
    {
        getchar();
        printf("\n------Add a New Student------  \n");
        printf("\n6-Digit ID: ");
        scanf("%6s", id);           //read 6 digit id

        while ( (c = getchar()) != '\n' && c != EOF );
        printf("Student's First Name: ");
        scanf("%5s", fname);                //read first namae

        while ( (c = getchar()) != '\n' && c != EOF );

        printf("Student's Last Name: ");
        scanf("%5s", lname);                //read last name
        while ( (c = getchar()) != '\n' && c != EOF );
        printf("Student's Score: ");
        scanf("%3s", score);                //read score

        while ( (c = getchar()) != '\n' && c != EOF );

        write(sockfd, iEntry, sizeof(iEntry)); //write entry number
        write(sockfd, id, sizeof(id));          //write id
        write(sockfd, fname, sizeof(fname));    //write fname
        write(sockfd, lname, sizeof(lname));    //write lname
        write(sockfd, score, sizeof(score));    //write score
        printf("\n------Student Added------\n");
        i++;

    }
int main()
{
    int sockfd;
    struct sockaddr_in serverAddr;
    socklen_t addr_size;

    sockfd = socket(PF_INET, SOCK_STREAM, 0);
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(7891);
    serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);

    addr_size = sizeof serverAddr;
    connect(sockfd, (struct sockaddr *) &serverAddr, addr_size);

    func(sockfd);

    close(sockfd);
}

Server side:
void func(int sockfd)
{

int i = 0;
char idArr[MAXSIZE][MAXLEN];
char fnameArr[MAXSIZE][MAXLEN];
char lnameArr[MAXSIZE][MAXLEN];
char scoreArr[MAXSIZE][MAXLEN];
char entryArr[MAXSIZE][MAXLEN];
char iEntry[1];

char id[6];
char fname[5];
char lname[5];
char score[3];
int n,c;
char entry;
// infinite loop for chat
for (;;) {
    printf("HERE6\n");
    bzero(iEntry, sizeof(iEntry));
    bzero(id, sizeof(id));
    bzero(fname, sizeof(fname));
    bzero(lname, sizeof(lname));
    bzero(score, sizeof(score));
    read(sockfd, iEntry, sizeof(iEntry));
    strcpy(entryArr[0], iEntry);
    if (iEntry[0] == '1')
    {
        read(sockfd, id, sizeof(id));

        read(sockfd, fname, sizeof(fname));
        read(sockfd, lname, sizeof(lname));
        read(sockfd, score, sizeof(score));
        printf("HERE5\n");
        strcpy(idArr[i], id);
        strcpy(fnameArr[i], fname);
        strcpy(lnameArr[i], lname);
        strcpy(scoreArr[i], score);

        printf("Student Added.\n");
        i++;
}
int main()
{
int sockfd, connfd;
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;

sockfd = socket(PF_INET, SOCK_STREAM, 0);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(7891);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);

bind(sockfd, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
if(listen(sockfd,5)==0)
    printf("Listening\n");
else
    printf("Error\n");
addr_size = sizeof serverStorage;
connfd = accept(sockfd, (struct sockaddr *) &serverStorage, &addr_size);

func(connfd);
close(sockfd);
}

in my func() function I am running a menu with options. The program works as expected when it is running on the same terminal using PuTTy (i.e eros.tx.state.edu).
When I run on two different terminals (on the same machine) the program works but exits as soon as it reaches the first write().
Any idea why does this happen?
sorry for the long post I tried to keep it to minimum.

A: char iEntry[1];

Okay, iEntry contains a single character.
read(sockfd, iEntry, sizeof(iEntry));
strcpy(entryArr[0], iEntry);

Why are you passing iEntry to strcpy? It's a single character. How are you expecting strcpy to know that it should only copy a single character?
Why not just test iEntry[0]? Why is iEntry an array anyway?
Your code ignores the return value of read. You, at a minimum, need to handle short reads by writing some kind of "read all" function that reads in precisely the number of bytes specified.


text:
Q: How to zip a very large file in python I would like to zip a couple of files that may amount to about 99 GB using python. Please what is the most efficient way to do this using the zipfile library. This is a sample code I have
with gcs.open(zip_file_name, 'w', content_type=b'application/zip') as f:

    with  zipfile.ZipFile(f, 'w') as z:

        for file in files:

            is_owner = (is_page_allowed_to_visitor(page, visitor) or (file.owner_id == visitor.id) )

            if is_owner:
                file.show = True
            elif file.available_from:
                if file.available_from > datetime.now():
                    file.show = False
            elif file.available_to:
                if file.available_to < datetime.now():
                    file.show = False
            else:
                file.show = True

            if file.show:

                file_name = "/%s/%s" % (gcs_store.get_bucket_name(), file.gcs_name)

                gcs_reader = gcs.open(file_name, 'r')

                z.writestr('%s-%s' %(file.created_on, file.name), gcs_reader.read() )

                gcs_reader.close()

f.close() #closing zip file

Some points to note:
1) I am using the google app engine to host the files so I cannot use the zipfile.write() method. I can only get the file contents in bytes.
Thanks in advance

A: I have added a new method to the zipfile library. This enhanced zipfile library is open source and can be found on github (EnhancedZipFile). I added a new method with the inspiration from the zipfile.write() method and the zipfile.writestr()method
def writebuffered(self, zinfo_or_arcname, file_pointer, file_size, compress_type=None):
    if not isinstance(zinfo_or_arcname, ZipInfo):
        zinfo = ZipInfo(filename=zinfo_or_arcname,
                        date_time=time.localtime(time.time())[:6])

        zinfo.compress_type = self.compression
        if zinfo.filename[-1] == '/':
            zinfo.external_attr = 0o40775 << 16   # drwxrwxr-x
            zinfo.external_attr |= 0x10           # MS-DOS directory flag
        else:
            zinfo.external_attr = 0o600 << 16     # ?rw-------
    else:
        zinfo = zinfo_or_arcname

    zinfo.file_size = file_size            # Uncompressed size
    zinfo.header_offset = self.fp.tell()    # Start of header bytes
    self._writecheck(zinfo)
    self._didModify = True

    fp = file_pointer
    # Must overwrite CRC and sizes with correct data later
    zinfo.CRC = CRC = 0
    zinfo.compress_size = compress_size = 0
    # Compressed size can be larger than uncompressed size
    zip64 = self._allowZip64 and \
            zinfo.file_size * 1.05 > ZIP64_LIMIT
    self.fp.write(zinfo.FileHeader(zip64))
    if zinfo.compress_type == ZIP_DEFLATED:
        cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
             zlib.DEFLATED, -15)
    else:
        cmpr = None
    file_size = 0
    while 1:
        buf = fp.read(1024 * 8)
        if not buf:
            break
        file_size = file_size + len(buf)
        CRC = crc32(buf, CRC) & 0xffffffff
        if cmpr:
            buf = cmpr.compress(buf)
            compress_size = compress_size + len(buf)
        self.fp.write(buf)

    if cmpr:
        buf = cmpr.flush()
        compress_size = compress_size + len(buf)
        self.fp.write(buf)
        zinfo.compress_size = compress_size
    else:
        zinfo.compress_size = file_size
    zinfo.CRC = CRC
    zinfo.file_size = file_size
    if not zip64 and self._allowZip64:
        if file_size > ZIP64_LIMIT:
            raise RuntimeError('File size has increased during compressing')
        if compress_size > ZIP64_LIMIT:
            raise RuntimeError('Compressed size larger than uncompressed size')
    # Seek backwards and write file header (which will now include
    # correct CRC and file sizes)
    position = self.fp.tell()       # Preserve current position in file
    self.fp.flush()
    self.filelist.append(zinfo)
    self.NameToInfo[zinfo.filename] = zinfo

Points to note

*

*I am a newbie in python so the code I wrote above may not be very optimized.

*Please contribute to the project on github here https://github.com/najela/EnhancedZipFile


text:
Q: The method '[]' was called on null. (How to retrieving data from firestore?) I have data on firestore. I used json and serialization with bloc pattern.
Project is not run. Error is,

Unhandled Exception: NoSuchMethodError: The method '[]' was called on
  null. Receiver: null Tried calling:

my DB.dart file(for set data)
class DB {
  final db = Firestore.instance;

  getPhotography() async {
     await db
    .collection('photography')
    .document('0yUc5QBGHNNq6WK9CyyF')
    .setData(jsonDecode(jsonEncode(Photography(
  [AllImages(["list"])],
  "image_url",
  "Shanika",
  "inage_url",
  "lovely couple",
  "Bhanuka"
))));
  }}
DB db = DB();

photography_bloc class
class PhotographyBloc extends BlocBase{

PhotographyBloc(){
  init();
}
Photography photography;

  final _firestoreController = StreamController<Photography>();
  Stream<Photography> get outFirestore => _firestoreController.stream;
  Sink<Photography> get inFirestore => _firestoreController.sink;

  @override
  void dispose() {
    _firestoreController.close();
  }

  void init() async{
  Photography data;
  await db.getPhotography().then((v) => data = v);
    inFirestore.add(data);
  }
}

Widget(StreamBuilder)
child: StreamBuilder<Photography>(
                stream: bloc.outFirestore,
                initialData: null,
                builder: (context, snapshot) {
                  print(snapshot.data); //output is null
                  Photography data = Photography.fromJson(jsonDecode(jsonEncode(snapshot.data))); //try to retrieving data, error is coming here

Photography model class(I used build_runner)
import 'package:json_annotation/json_annotation.dart';
part 'Model.g.dart';

    @JsonSerializable()
    class Photography{
       List<AllImages> all_images;
       String couplePhoto;
       String female;
       String image_url;
       String info;
       String male;

      Photography();

      factory Photography.fromJson(Map<String, dynamic> json) => _$PhotographyFromJson(json);
       Map<String,dynamic> toJson() => _$PhotographyToJson(this);
    }

    @JsonSerializable()
    class AllImages {
      final List<String> imageUrl;

      AllImages(this.imageUrl);

      factory AllImages.fromJson(Map<String, dynamic> json) => _$AllImagesFromJson(json);
      Map<String,dynamic> toJson() => _$AllImagesToJson(this);
    }


text:
Q: when i start eclipse and run android project, it opens a new emulator every time , Eclipse Android Emulator takes average 7 minutes to launch an activity ,its quite a long time
Once emulator is Set ,Other projects can be run in same emulator which takes less times.
Sometimes when i start eclipse and run android project, it opens a new emulator every time instead of installing the project in same emulator.
I have searched about this problem,I found the Single good Reason, Connection refused for the sensor ports is a common problem I am not sure , This is the real reason
I am using Eclipse for Windows,not Mac or Linux and previous activity is properly set before i run the next project
Help me to figure out, what can be the reason behind this problem and how can i make it normal.

A: You can avoid starting emulator automatically by going to
run --> run configuration --> target tab. Then select "Always prompt to pick device." Run the project after this and select a different emulator device.
Here is a screenshot:

A: If you are running Eclipse with the ADT plug in what normally happens is (1) you run you project (2) it asks to to select an android device (3) if no device is available, e.g. a valid emulator, it will ask you to create one.
If Eclipse is asking you to creat a new emulator every time it is likley beacuse either (1) you have not selected the option on the pop up window indicating that you would like to always run the project in a specific listed instance of your emulator (2) there really is no compatable emulator available.
If an emulator is created but not being found (as I suspect is happeneing), you need to refresh your ADT plug in connectino to that emulator. You can do this from within eclipse by going to the devices view (window --> show view --> other --> android --> devices), selecting the downward facing triangle all the way on the right and choosing "reset adb". This will reboot the android device bridge, a.k.a. what connects eclipse to your emulator, and will allow it to recognize that instance again. You should be able to run your project on that emulator from then on.

A: Not sure if this is a solution, but I noticed that clearing the memory on the emulator helped me on a few occasions. Also, I had an issue where I didn't notice the console was stating that my emulator was running on a lower API that the app requested, so it opened the next best emulator instance.


text:
Q: Dynamic button - onclick just won't work I have used this code in a few other projects, but this time I just can't get it to work.
I am attempting to track the click event of a button control, but it just isn't firing.
I have tried re-loading in the controls in the page.init (I had to change the ControlsToLoad from viewstate to session for this to even load the controls in again) but this did not work either.
This is a page I'm using for test purposes:
Inherits System.Web.UI.Page
Private ReadOnly Property ControlsToLoad() As List(Of String)
    Get
        If ViewState("ControlsToLoad") Is Nothing Then
            ViewState("ControlsToLoad") = New List(Of String)()
        End If
        Return DirectCast(ViewState("ControlsToLoad"), List(Of String))
    End Get
End Property

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If ControlsToLoad.Count > 0 Then
        For Each sID As String In ControlsToLoad
            createControl(sID)
        Next
    End If

    If Not IsPostBack Then
        loadControls()
    End If

End Sub

Sub loadControls()

    createControl(123)
    ControlsToLoad.Add(123)

End Sub

Function createControl(ByVal sID As String)

    Dim oTile As New Button
    oTile.Text = Left(sID, 1)
    oTile.ID = sID
    oTile.Attributes("class") = "M_Tile_" & sID
    AddHandler oTile.Click, AddressOf click
    phMaze.Controls.Add(oTile)
    oTile.Dispose()
    oTile = Nothing

End Function
Protected Sub click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    Response.Write("Here")

End Sub

Any help is appreciated.
Thanks
Ben

A: For your dynamically added controls to participate in the page life cycle you need to create them in page PreInit event. see ASP.NET Page Life Cycle
Update:
You need to remove oTile.Dispose() as it destroys the object and removes the handler.


text:
Q: Android ScrollView doesn't have vertical scroll I'm trying to display a page with ability to scroll vertically. I've already added the android:fillViewPort="true", but the page just won't scroll vertically. I've been searching for some answers and have set the first and only child of scrollview to android:layout_height="wrap_content", but still not succeeded.
Here is the xml file.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
       android:fillViewport="true">
<RelativeLayout
    android:id="@+id/parentProfileLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/no_border_textfield">
   <RelativeLayout
        android:id="@+id/topProfileLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/larger_margin"
        android:paddingRight="@dimen/larger_margin"
        android:paddingTop="@dimen/larger_margin"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/photoImageView"
            android:layout_width="@dimen/default_photo_width"
            android:layout_height="@dimen/default_photo_height"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:gravity="left|center_vertical"
            android:layout_marginRight="@dimen/default_margin"
            android:background="@drawable/photo_drawable"/>
        <RelativeLayout
            android:id="@+id/doctorLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/photoImageView"
            android:orientation="vertical"
            android:layout_marginRight="@dimen/default_margin"
            android:layout_marginLeft="@dimen/default_margin">
            <TextView
                android:id="@+id/doctorNameText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:textColor="@color/default_text_color"
                android:text="@string/empty2"
                style="@style/BoldInfoTextView"/>
            <TextView
                android:id="@+id/doctorTitleText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/doctorNameText"
                android:paddingRight="@dimen/default_padding"
                android:textColor="@color/default_text_color"
                android:text="@string/empty2"
                style="@style/BoldInfoTextView"/>
        </RelativeLayout>
    </RelativeLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/doctor_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="@dimen/larger_margin"
        android:layout_marginRight="@dimen/larger_margin"
        android:layout_below="@+id/topProfileLayout">
        <android.support.v4.view.PagerTabStrip
            android:id="@+id/pager_header"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="@color/default_table_header"
            android:paddingBottom="4dp"
            android:paddingTop="4dp"
            android:textColor="#fff" />
    </android.support.v4.view.ViewPager>
</RelativeLayout>
</ScrollView>

A: Put that scrollview in relative layout like below.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:fillViewport="true">

    <RelativeLayout
     android:id="@+id/parentProfileLayout"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content">
    </RelativeLayout>

</ScrollView>

A: I'm not sure that it's good put ViewPager into ScrollView. I think that ViewPager catches motion events and ScrollView doesn't get any events.
If you want to hide tabs when scrolling content in ViewPager, use CoordinatorLayout. There many examples about how to use CoordinatorLayout. So I think that you find more information by yourself.

A: change your child layout ie RelativeLayout to LinearLayout.

A: This is ugly, it may be wrong to do, but it works.
In XML:
Place a fixed dp height in your ViewPager (this height needs be larger that the content). The container of the contents must have wrap_content height.
In Java:
Implement a Runnable which calculates the height of the container in px and copy to the ViewPager
activity_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="br.com.brhuearts.swipeview.MainActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:id="@+id/scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Texto\nwwwee\nwewwererwre\nwqewewe\ndnasuid\nsjdhsiufoiifjoj"
        android:background="#00FF00"
        android:id="@+id/tv1"
        />

        <android.support.v4.view.ViewPager
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="2000dp"
            android:background="#FFFF00"
            android:layout_weight="1"
            />

</LinearLayout>

</android.support.v4.widget.NestedScrollView>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />

fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="br.com.brhuearts.swipeview.MainActivity$PlaceholderFragment">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#00FFFF"
    android:padding="20dp"
    android:id="@+id/ll">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/lb"
        android:background="#FF0000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Texto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTexto\nTextofim"
        />

</LinearLayout>

MainActivity.java
    package br.com.brhuearts.swipeview;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    private static LinearLayout ll;

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

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

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        mViewPager.post(new Runnable() {
            @Override
            public void run() {
                //In Runnable can pick up the height of the objects
                Log.d("TAG","_VP1__"+mViewPager.getHeight());
                Log.d("TAG","_VP2__"+mViewPager.getLayoutParams().height);

                Log.d("TAG","_LL1__"+ ll.getHeight());
                Log.d("TAG","_LL2__"+ll.getLayoutParams().height);

                //calculates the height of the container in px and copy to the ViewPager
                mViewPager.getLayoutParams().height=ll.getHeight();
            }
        });

    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            ll = (LinearLayout) rootView.findViewById(R.id.ll);
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SECTION 1";
                case 1:
                    return "SECTION 2";
                case 2:
                    return "SECTION 3";
            }
            return null;
        }
    }
}


text:
Q: How to return only the left side when using joinWith in Scala so I have the following, and I am trying to use joinWith and I only want whats on the left side and then I want to run a function after that join, I'm doing the following but it doesn't work.
(FYI for clarity The left side has more additional columns in real life which is why i am running the function after the join, just using this as a basic example)
val df1 = Seq((1, "A1"), (2, "A2"), (3, "A3"), (4, "A4")).toDF("id", "value_left")
val df2 = Seq((3, "A3"), (4, "A4"), (4, "A4_1"), (5, "A5"), (6, "A6")).toDF("id", "value_right")

def anotherFunction(parm: Dataset[Row]): Dataset[Row]

 val transformedDf: Dataset[Row] = df1
      .joinWith(df2, df1("id")===df2("id"),"inner")
      .transform(anotherFunction)

the output of the inner join before i try to get the left side looks like this, i only want the left side in this case but when i pass my function through .transform() it says whats required is a Dataset[(Row, Row)]
INNER JOIN
+---+----------+-----------+
| id|value_left|value_right|
+---+----------+-----------+
|  3|        A3|         A3|
|  4|        A4|       A4_1|
|  4|        A4|         A4|
+---+----------+-----------+

A: If I understood you correctly, you don't want the actual join, but df1, filtered by ids in df2.
Take a look at left_semi join type. If you change your code to
df1.joinWith(df2, df1("id")===df2("id"),"left_semi"), you should get something like
LEFT SEMI JOIN
+---+----------+
| id|value_left|
+---+----------+
|  3|        A3|
|  4|        A4|

Some more info can be found here - https://jaceklaskowski.gitbooks.io/mastering-spark-sql/spark-sql-joins.html#joinWith
Also, you can just joined_df.drop("value_right")


text:
Q: how to configure a basic auth security policy in wso2 I want to secure some wso2 endpoints using basic auth security so that whoever invokes needs a username and policy
How do i configure this policy in wso2 esb?Can i create the username/password in a vault and validate the auth against it?
wso2 security policy screen
This doenst give an option to give username/password.. I dont need any roles validation ;but just need a username/password.. I know how to enable the security policy in the esb dataservice/endpoint ;but please help me in configuring the policy

A: you can refer to the answer in [1] regarding the basic authentication. If you want to use a security policy to achieve your requirements, you can modify the security policy and avoid using the following in the policy file.
<sec:CarbonSecConfig xmlns:sec="http://www.wso2.org/products/carbon/security">
        <sec:Authorization>
            <sec:property name="org.wso2.carbon.security.allowedroles">admin,role1</sec:property>
        </sec:Authorization>
    </sec:CarbonSecConfig>

[1]-https://stackoverflow.com/a/57811507/9990440
Modified Based on the comment
Ths document [1] and blog post [2] contain the steps that need to be followed to develop a security policy. The blog post explains on how to add WS-Policy type, Integrity. But for the basic OAuth, you can select UserNameToken as the basic scenario. After adding the policy as a registry resource you can point the policy file as follows at the end of the data service
 <data>
   ...
    <policy key="conf:security/ESE-DevOps_policy.xml"/>
    <enableSec>true</enableSec>
 </data>

In addition to using the security policy to secure the data service, you can expose the data service through an API. The data service can be configured to invoke only through local transport to avoid any security issues. Then the API can be secured with Basic Auth handler. The document [3] contains sample code and the steps in developing a handler.
[1]-https://docs.wso2.com/display/EI650/Applying+Security+to+a+Proxy+Service
[2]-https://medium.com/@prabushi/use-ws-policy-to-secure-a-wso2-proxy-service-33a1bfa19f5b
[3]-https://docs.wso2.com/display/ESB481/Securing+APIs#SecuringAPIs-BasicAuthUsingaBasicAuthhandler


text:
Q: Draw lines and Move the marker at the same time with KML format it is possible to draw a line and put the Marker in the top of the line with KML format? or have i to make two KML files, it's that to say, One KML file for the Lines and another one for The Markers?
We are about to develop a GIS track app, and we are testing what is the best way to achieve our project.
here is and example, about what we want to do:
GIS Track Example, Moving line and Marker
Well is good to explain, that we gonna get a new KML or the data every 20 seconds to redraw the lines and the markers in the map.
Or do you have better ideas? KML, Database(Mysql), Xml?
Thanks to all.

A: Well I did something for myself,since no one has responded, I've only managed to move the marker or icon ,i have a KML format to represent a plane track, in Openlayers Map, everything works great, but i can only see the plan track, i'd like to see the Line too, it is possible with the same KML file or have i to add something else? i'd, like to do something like this (Line and Point):
Example
Thanks, here are the codes:
    filter = new OpenLayers.Filter.Comparison({
   type: OpenLayers.Filter.Comparison.BETWEEN,
   property: "when",
   lowerBoundary: startDate,
upperBoundary: new Date(startDate.getTime() + (parseInt(spanEl.value, 10) * 1000))
 });

 filterStrategy = new OpenLayers.Strategy.Filter({filter: filter});

 var flights = new OpenLayers.Layer.Vector("Aircraft Locations", {
projection: geographic,
strategies: [new OpenLayers.Strategy.Fixed(), filterStrategy],
protocol: new OpenLayers.Protocol.HTTP({
    url: "kml-track.kml",
    format: new OpenLayers.Format.KML({
        extractTracks: true,
        extractStyles: true ,// use style from KML instead of styleMap below
        extractAttributes: true
    })
}),
/*styleMap: new OpenLayers.StyleMap({
    "default": new OpenLayers.Style({
        graphicName: "circle",
        pointRadius: 3,
        fillOpacity: 0.25,
        fillColor: "#ffcc66",
        strokeColor: "#ff0000",
        strokeWidth: 2
        })
    }),*/
   //  renderers: ["Canvas", "SVG", "VML"]
   });

  map.addLayers([osm, flights]);
   map.setCenter(new OpenLayers.LonLat(-93.2735, 44.8349).transform(geographic, mercator), 8);

and with this KML:
<?xml version="1.0" encoding="UTF-8"?>
 <kml xmlns="http://www.opengis.net/kml/2.2"          xmlns:gx="http://www.google.com/kml/ext/2.2">
 <Document>
<Style id="departure">
 <LineStyle>
   <color>FF00FF00</color>
   <width>3</width>
 </LineStyle>
  <IconStyle>
    <Icon>
      <href>http://localhost/Openlayers/FilterStrategy/lotus.ico</href>
   </Icon>
 </IconStyle>
 </Style>

<Folder>
  <name>Departures</name>
  <Placemark>
    <name>TEX2</name>
     <flightid>HOOK67</flightid>
   <styleUrl>#departure</styleUrl>

    <gx:Track>
         <gx:altitudeOffset>0</gx:altitudeOffset>
          <tessellate>0</tessellate>
        <altitudeMode>relativeToGround</altitudeMode>
        <extrude>0</extrude>
        <when>2010-05-01T13:02:46-05</when>
        <when>2010-05-01T13:02:50-05</when>
        <when>2010-05-01T13:02:54-05</when>
        <when>2010-05-01T13:02:59-05</when>
        <when>2010-05-01T13:03:04-05</when>
        <when>2010-05-01T13:03:08-05</when>
        <when>2010-05-01T13:03:13-05</when>
        <when>2010-05-01T13:03:18-05</when>
        <when>2010-05-01T13:03:22-05</when>
        <when>2010-05-01T13:03:27-05</when>
        <when>2010-05-01T13:03:31-05</when>
        <when>2010-05-01T13:03:36-05</when>
        <when>2010-05-01T13:03:41-05</when>
        <when>2010-05-01T13:03:45-05</when>
        <when>2010-05-01T13:03:50-05</when>
        <when>2010-05-01T13:03:55-05</when>
        <when>2010-05-01T13:03:59-05</when>
        <when>2010-05-01T13:04:04-05</when>
        <when>2010-05-01T13:04:09-05</when>
        <when>2010-05-01T13:04:13-05</when>
        <when>2010-05-01T13:04:18-05</when>
        <when>2010-05-01T13:04:23-05</when>
        <when>2010-05-01T13:04:28-05</when>
        <when>2010-05-01T13:04:32-05</when>
        <when>2010-05-01T13:04:37-05</when>
        <when>2010-05-01T13:04:42-05</when>
        <when>2010-05-01T13:04:46-05</when>
        <when>2010-05-01T13:04:51-05</when>
        <when>2010-05-01T13:04:56-05</when>
        <when>2010-05-01T13:05:00-06</when>

                <gx:coord>-93.2379571205595 44.872806349747    365</gx:coord>
                <gx:coord>-93.2370660925484 44.870006118743 396</gx:coord>
                <gx:coord>-93.236355767523 44.8669752777211 426</gx:coord>
                <gx:coord>-93.2354887209031 44.863712193489 487</gx:coord>
                <gx:coord>-93.2347087148419 44.8604536579846 548</gx:coord>
                <gx:coord>-93.2338531241111 44.8572464977323 609</gx:coord>
                <gx:coord>-93.2329069833652 44.8540674818656 670</gx:coord>
                <gx:coord>-93.2321075679892 44.8508271074111 731</gx:coord>
                <gx:coord>-93.2318979317232 44.8475791496379 792</gx:coord>
                <gx:coord>-93.2324245825346 44.8444239832126 884</gx:coord>
                <gx:coord>-93.2337414411031 44.8414077607553 945</gx:coord>
                <gx:coord>-93.2358704572033 44.8386783246771 1006</gx:coord>
                <gx:coord>-93.2388663703645 44.836365445841 1066</gx:coord>
                <gx:coord>-93.2426861295915 44.8345537010783 1127</gx:coord>
                <gx:coord>-93.2472528925157 44.8333824186694 1158</gx:coord>
                <gx:coord>-93.252467378877 44.8329692039001 1188</gx:coord>
                <gx:coord>-93.25805239674 44.8333893976675 1219</gx:coord>
                <gx:coord>-93.2638450577518 44.8346083411457 1219</gx:coord>
                <gx:coord>-93.2696754993405 44.83650914188 1219</gx:coord>
                <gx:coord>-93.2753673121587 44.8390951418887 1219</gx:coord>
                <gx:coord>-93.2808543977574 44.8421681587795 1219</gx:coord>
                <gx:coord>-93.2861853262416 44.8454128516506 1249</gx:coord>
                <gx:coord>-93.29145969331 44.8487370983379 1219</gx:coord>
                <gx:coord>-93.2967095159 44.8520389729185 1219</gx:coord>
                <gx:coord>-93.3019214165294 44.8553364257712 1219</gx:coord>
                <gx:coord>-93.3070477220233 44.8587223340278 1219</gx:coord>
                <gx:coord>-93.3121286565238 44.8620050415952 1219</gx:coord>
                <gx:coord>-93.3171626530446 44.8652559523285 1219</gx:coord>
                <gx:coord>-93.3221179929219 44.868582313462 1219</gx:coord>
                <gx:coord>-93.3270963865766 44.8718050975636 1219</gx:coord>

  </gx:Track>
 </Placemark>
 </Folder>
</Document>
 </kml>


text:
Q: Need java project example with Authentication and Authorization I am developing a new java project. I have written the code in my own way and felt that it is not a standard model and difficult to maintain.Now I want to convert it to a standard model.
I need the standard java project models with permission filter, authorization
hander, interface/implement models. I want to follow that model and implement my project.
Any simple architecture or github project will helps a lot.
P.S: I am using tomcat,postgres,redis,struts2.

A: Since you are using Struts2, I do recommend you to start with these two 30 minutes tutorials:

*

*https://www.programcreek.com/2010/03/struts-2-tutorials-sample-application-login-module

*https://www.concretepage.com/struts-2/struts-2-annotation-simple-login-example


text:
Q: make version dependency for using test I'm trying to use test in a make target, specifically to check for changes to certain files with git (I don't think that particular git diff-index HEAD -- command makes a difference here).
is_diff:
    if [[ -n `git diff-index HEAD --` ]]; exit 1; fi

This works fine as a bash script, but as a make target it seems to be dependent on which version of make is running, which limits its utility (and makes just pointing to a shell script version better).
Is there a change that would make this a little more make-version independent?

A:
Use [ -n "`git diff-index HEAD --`" ] instead of the bash-specific [[ -n ... ]]

was the correct answer from a comment by Renaud Pacalet.
Also as MadScientist notes, that the original question omitted then so
if [ -n "`git diff-index HEAD --`" ]; then exit 1; fi


text:
Q: Vuejs emit click from component to main vue instance I am trying to emit an click Event from my component to my main vue instance but I am able to solve it. Currently I get no message in my console so it does not Event go to that function so Code Looks like this so far:
// component LeftUserListTileComponent
<template>
    <v-list-tile @click="$emit('toggleLeftUserPanel')">
        <v-list-tile-action>
            <v-icon>exit_to_app</v-icon>
        </v-list-tile-action>
        <v-list-tile-content>
            <v-list-tile-title>User Settings</v-list-tile-title>
        </v-list-tile-content>
    </v-list-tile>
</template>

<script>
    export default {
        data () {
            return {
            }
        },
        methods:{
            toggleLeftUserPanel () {
                // what to do here?
            }
    };
</script>

Vue.component('left-user-list-tile', require('./components/LeftUserListTileComponent.vue'));
Vue.component('left-user-panel', require('./components/LeftUserPanelComponent.vue'));

const app = new Vue({
    el: '#app',

    props: {
      source: String
    },

    data: {
        leftUserPanel: null
    },

    toggleLeftUserPanel () {
        console.log("In toggleLeftUserPanel func");
        this.leftUserPanel != this.leftUserPanel;
    }

});

A: If you emit directly the event when clicking, in the first toggleLeftUserPanel () you should do nothing more.
In order to work, you should declare what you expect from parent element when receiving an toggleLeftUserPanel event from it's childrens, like:
<toggle-left-user-panel @toggleLeftUserPanel='togglePanel' />

And then in the parent define this method in methods:
methods(){
    togglePanel() {
         //your action here
    }
}

In this way, the parent-child communication is enabled and the parent should react to the children emit event.
Hope it helps!

A: If you want to emit an event you need to set this inside your component. If you only interested fetching a click when a user click on the title you should be able to use @click.native:
<v-list-tile @click.native="console.log('Title is clicked!')">
...


text:
Q: Join a RethinkDB Cluster using ReQL instead of command line argument I'm using Docker, and by default runs the RethinkDB process with only the --bind all argument.
To join the cluster requires the use of the --join argument, or a configuration file. To do this with Docker would now require a new Docker image to be made for this purpose.
How can I join a cluster using ReQL directly (thus eliminating the need to create a new Docker image). I could simply connect to the lone instance, add a row to a system table (like server_status), and the instance would connect to the newly entered external instance.
I could repeat this process for each node in the cluster. And makes things simpler for when nodes come up and go down, otherwise I would have to restart each RethinkDB process.

A: In Docker, we can override the CMD which invokes RethinkDB process with a custom command for customization the executing RethinkDB process. Instead of simply call docker run rethinkdb, we can pass an the rethinkdb command for joining to the first node.
Example using the official RethinkDB docker
docker run --rm -it -p 9080:8080 rethinkdb

Then we can inspect its IP address, assume it's 172.17.0.2, we can start second one:
docker run --rm -it -p 9081:8080 rethinkdb rethinkdb --join 172.17.0.2:29015 --bind all

Visit RethinkDB dashboard and you should see two nodes now.


text:
Q: How can I use Trading Economics python package? How to use the Trading Economics python package?
I have already installed the package. But using the guest:guest key I'm getting this error:
$ login("guest:guest")
bash: syntax error near unexpected token '"guest:guest"'

A: You are trying to run python commands in the bash. In order to make use of Trading Economics API, create a new python file (or use python command-line) and use the following code in order to login:
If you already have an API key:
import tradingeconomics as te
te.login('Your_Key:Your_Secret')

If you don't have an API key and want to try a demo of the API:
import tradingeconomics as te
te.login()


text:
Q: Module is optimised and debug difficult even on a Debug build with optimise option unchecked I have this web program that references several class libraries projects that we wrote within the same solution. But one of them is special: Breaking the execution during debug, I got Cannot evaluate expression because the code of the current method is optimized message when trying to watch some variables, and also some lines of code is skipped when stepping through. Every library else is debugging fine except for this one.
I used Debug->Windows->Modules and see that for this problematic DLL, module optimised column is a 'Yes'. I checked solution property, and confirmed active configuration is Debug for the solution level and also every project under it.
Also for the problematic project, I confirmed on the Build page that Define DEBUG constant is checked, and Optimize Code is unchecked. In Advanced page, Debugging information is Full - all same as other libraries.
Why would this one be optimised when every possible option I can find is set correctly?

A: Launch the Developer Command Prompt. Run ildasm. Open the problematic DLL and double click at Manifest. Found the following code:
  // --- The following custom attribute is added automatically, do not uncomment -------
  //  .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 02 00 00 00 00 00 )

Mind that 01 00 02 00 00 00 00 00. Open a normal debuggable DLL and find that value to be 01 00 07 01 00 00 00 00.
This finally points to a line in Assembly.cs under that Properties of the project.
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]

Turns out one of the developers lost his code before he could commit and decided to decompile a DLL - unfortunately a release version - to get his code back and then commit it to the repo. Delete this line and everything will be normal again.
For the record, according to Dave Black from another post:

If the DebuggableAttribute is not present, it is definitely an Optimized assembly

Inspired by https://dave-black.blogspot.com/2011/12/how-to-tell-if-assembly-is-debug-or.html


text:
Q: Angular - How to delete data from Firebase DB I am trying to delete specific values from my firebase DB.
I want to delete this entry from firebase:

What I tried so far is my button on how to trigger the delete button:

 Name: {{bfunc.Name}}

 Beschreibung:   {{bfunc.Descr}}

 Key:    {{bfunc.$key}}
<button type="button"  ng-click="deleteSth(bfunc.name)">Delete Item </button>

... and my delete-method:
deleteSth(name){
  firebase.database().ref('/BFunctions/').child(name).remove();
}

As I am also pretty new to Angular I don't really what the solution could be.
I appreciate your answers!

A: Try using the ref object

 Name: {{bfunc.Name}}

 Beschreibung:   {{bfunc.Descr}}

 Key:    {{bfunc.$key}}
<button type="button"  ng-click="deleteSth(bfunc.$key)">Delete Item
</button>

and
deleteSth(key){
    firebase.database().ref('/BFunctions/' + key).remove();
}

If that doesnt work check your console it could be related to permissions or something else

A: your button initialisation should look like this, becuase your bfunc.Key is not defined. As is see your bfunc.Name is your key in your database. If this is like that you can make your code as follow:
<button type="button"  ng-click="deleteSth(bfunc.$key=bfunc.Name)">Delete Item

than just use:
deleteSth(key){
    firebase.database().ref().child('/BFunctions/'+key+'/').remove();
}

:)


text:
Q: Error uploading file using S3FileTransformOperator in Apache Airflow I'm converting a XML file into Parquet.
This is the relevant code:
File s3_test.py:
with DAG("s3-dag", default_args=default_args, schedule_interval= '@once') as dag:
    t1 = BashOperator(
        task_id='bash_test',
        bash_command='echo 1',
        dag=dag
    )
    transformer = S3FileTransformOperator(
        task_id='S3_ETL_OP',
        source_s3_key='s3://<my bucket>/origin/105.xml',
        dest_s3_key='s3://<my bucket>/s3/105.parquet',
        replace=False,
        transform_script='/usr/local/airflow/dags/scripts/transform.py',
        source_aws_conn_id='s3_connection',
        dest_aws_conn_id='s3_connection'
    )
    t1.set_upstream(transformer)

File transform.py:
import sys
import os
from pyspark.sql import SparkSession
from pyspark.sql.types import *
from random import random
from operator import add

output=sys.argv[2]
input_file = sys.argv[1]

print("Starting data transformation...")
spark = SparkSession\
        .builder\
        .appName("XmlToParquet")\
        .getOrCreate()

df = spark.read.format("com.databricks.spark.xml") \
        .options(rowTag="PatientMatching") \
        .load(input_file)

print("Dataframe read")
df.repartition(1).write.mode('overwrite').parquet(output)
print("Completed data transformation!")

This code is reading my XML correctly and also creating the parquet file.
Apparently, it isn't uploading the file to S3 because it confuses the temp file with a folder.
[2020-10-26 18:22:13,819] {{s3_file_transform_operator.py:147}} INFO - Dataframe read
[2020-10-26 18:22:13,819] {{s3_file_transform_operator.py:147}} INFO - Completed data transformation!
[2020-10-26 18:22:14,667] {{s3_file_transform_operator.py:158}} INFO - Transform script successful. Output temporarily located at /tmp/tmpwma2zhp6
[2020-10-26 18:22:14,667] {{s3_file_transform_operator.py:161}} INFO - Uploading transformed file to S3
[2020-10-26 18:22:18,825] {{S3_hook.py:209}} INFO - Not Found
[2020-10-26 18:22:18,939] {{taskinstance.py:1150}} ERROR - [Errno 21] Is a directory: '/tmp/tmpwma2zhp6'
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/airflow/operators/s3_file_transform_operator.py", line 166, in execute
    replace=self.replace
  File "/usr/local/lib/python3.7/site-packages/airflow/hooks/S3_hook.py", line 373, in load_file
    client.upload_file(filename, bucket_name, key, ExtraArgs=extra_args)
  File "/usr/local/lib/python3.7/site-packages/boto3/s3/inject.py", line 131, in upload_file
    extra_args=ExtraArgs, callback=Callback)

I really don't want to patch Airflow code.
Any help?

A: I just ran a test with the following S3FileTransformOperator and it succeeded:
transformer = S3FileTransformOperator(
        task_id='S3_ETL_OP',
        source_s3_key='s3://<<bucket>>/tmp/test_input.csv',
        dest_s3_key='s3://<<bucket>>/tmp/test_output.csv',
        replace=False,
        transform_script='/bin/cp',
        source_aws_conn_id='s3-connection',
        dest_aws_conn_id='s3-connection'
    )

Using /bin/cp is the most simple script and really just copying between the two temporary locations and succeeded:
[2020-10-27 16:42:41,084] {s3_file_transform_operator.py:114} INFO - Downloading source S3 file s3://<<bucket>>/tmp/test_input.csv
[2020-10-27 16:42:41,650] {s3_file_transform_operator.py:123} INFO - Dumping S3 file s3://<<bucket>>/tmp/test_input.csv contents to local file /tmp/tmpbcogzsdk
[2020-10-27 16:42:41,847] {s3_file_transform_operator.py:144} INFO - Output:
[2020-10-27 16:42:41,851] {s3_file_transform_operator.py:157} INFO - Transform script successful. Output temporarily located at /tmp/tmp3cpn7gd_
[2020-10-27 16:42:41,851] {s3_file_transform_operator.py:160} INFO - Uploading transformed file to S3
[2020-10-27 16:42:42,070] {S3_hook.py:201} INFO - Not Found
[2020-10-27 16:42:43,025] {s3_file_transform_operator.py:167} INFO - Upload successful

I would recommend to try this approach as well. Otherwise it would be great to know which Airflow Version you are running and which boto/boto3 package version.


text:
Q: ArrayList return size() zero mNewList return size() zero but it contains data that it show in ListView, mListData.getContacts(); returns ArrayList fetched from server via internet but its not a problem as i written before it shows data in ListView.
ArrayList<String> mNewList = new ArrayList<String>();
mNewList = mListData.getContacts();
Log.i("ShowingListSize", ":" +mNewList.size());

adapter = new ArrayAdapter<String>(MainActivity.this,
                                   android.R.layout.simple_list_item_1,
                                   mNewList);
mList.setAdapter(adapter);

ListData Class

public ArrayList<String> getContacts() {

// Fetch list data from the database
    task = new LoadList();
    calendar = Calendar.getInstance();
    month = calendar.get(Calendar.MONTH);
    year = calendar.get(Calendar.YEAR);
    day = calendar.get(Calendar.DAY_OF_MONTH);
    hour = calendar.get(Calendar.HOUR_OF_DAY);
    minute = calendar.get(Calendar.MINUTE);
    task.execute(new String[]{Integer.toString(day),
                              Integer.toString(month),
                              Integer.toString(year),
                              Integer.toString(hour),
                              Integer.toString(minute)});
    try {
        task.get(); // wait for task to finish
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return mContacts;
}

protected void onPostExecute(String response) {
            try {
                if(response.equals("error")) {
                    return;
                }

                json = new JSONObject(response);
                jsonArray = json.getJSONArray("result");
                String number, id;

                try{
                    for(int i=0; i<jsonArray.length(); i++) {
                        JSONObject arrayItems = jsonArray.getJSONObject(i);
                        number = arrayItems.getString("number");
                        id = arrayItems.getString("id");
                        mContacts.add("hello" +number);
                        mContacts.add("hello" +id);
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

A: Your getContacts AsyncTask runs in another thread (asynchronously as the etymology suggests). Your list is updated after that thread finishes, but your Logging happens in parallel with the AsyncTask so at the time you log the size, the list does contain nothing. Later when the AsyncTask finishes that's when you see things displayed in the list.
Heres a visualization
Thread: UI ----------------------------------------------------------- ASYNCTASK
............... | .. ArrayList mNewList = new ...;
............... | .. mNewList = mListData.getContacts();
............... | .. AsyncTask::onBeforeExecute()
............... | .............................................................................. | .. AsyncTask::doInBackground starts
............... | .. Log.i(mNewList.size()); .................................... | .. ( still working )
............... | .............................................................................. | .. AsyncTask::doInBackground returns
............... | .. AsyncTask::onPostExecute
............... | .. mContacts.add(...) ...
............... | ...