Q: iOS certificate pinning with Swift and NSURLSession Howto add certificate pinning to a NSURLSession in Swift?
The OWASP website contains only an example for Objective-C and NSURLConnection.

A: Save the certificate (as .cer file) of your website in the main bundle. Then use this URLSessionDelegate method:
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    guard
        challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
        let serverTrust = challenge.protectionSpace.serverTrust,
        SecTrustEvaluate(serverTrust, nil) == errSecSuccess,
        let serverCert = SecTrustGetCertificateAtIndex(serverTrust, 0) else {

            reject(with: completionHandler)
            return
    }

    let serverCertData = SecCertificateCopyData(serverCert) as Data

    guard
        let localCertPath = Bundle.main.path(forResource: "shop.rewe.de", ofType: "cer"),
        let localCertData = NSData(contentsOfFile: localCertPath) as Data?,

        localCertData == serverCertData else {

            reject(with: completionHandler)
            return
    }

    accept(with: serverTrust, completionHandler)

}

...
func reject(with completionHandler: ((URLSession.AuthChallengeDisposition, URLCredential?) -> Void)) {
    completionHandler(.cancelAuthenticationChallenge, nil)
}

func accept(with serverTrust: SecTrust, _ completionHandler: ((URLSession.AuthChallengeDisposition, URLCredential?) -> Void)) {
    completionHandler(.useCredential, URLCredential(trust: serverTrust))
}

A: Just a heads up, SecTrustEvaluate is deprecated and should be replaced with SecTrustEvaluateWithError.
So this:
var secresult = SecTrustResultType.invalid
let status = SecTrustEvaluate(serverTrust, &secresult)

if errSecSuccess == status {
   // Proceed with evaluation
   switch result {
   case .unspecified, .proceed:    return true
   default:                        return false
   }
}

The reason i wrote the // Proceed with evaluation section is because you should validate the secresult as well as this could imply that the certificate is actually invalid. You have the option to override this and add any raised issues as exceptions, preferably after prompting the user for a decision.
Should be this:
if SecTrustEvaluateWithError(server, nil) {
   // Certificate is valid, proceed.
}

The second param will capture any error, but if you are not interested in the specifics, you can just pass nil.

A: Swift 3+ Update:
Just define a delegate class for NSURLSessionDelegate and implement the didReceiveChallenge function (this code is adapted from the objective-c OWASP example):
class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {

        // Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS

        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
            if let serverTrust = challenge.protectionSpace.serverTrust {
                let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)

                if(isServerTrusted) {
                    if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
                        let serverCertificateData = SecCertificateCopyData(serverCertificate)
                        let data = CFDataGetBytePtr(serverCertificateData);
                        let size = CFDataGetLength(serverCertificateData);
                        let cert1 = NSData(bytes: data, length: size)
                        let file_der = Bundle.main.path(forResource: "certificateFile", ofType: "der")

                        if let file = file_der {
                            if let cert2 = NSData(contentsOfFile: file) {
                                if cert1.isEqual(to: cert2 as Data) {
                                    completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust))
                                    return
                                }
                            }
                        }
                    }
                }
            }
        }

        // Pinning failed
        completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
    }

}

(you can find a Gist for Swift 2 here - from the initial answer)
Then create the .der file for your website using openssl
openssl s_client -connect my-https-website.com:443 -showcerts < /dev/null | openssl x509 -outform DER > my-https-website.der

and add it to the xcode project. Double check that it's present in the Build phases tab, inside the Copy Bundle Resources list. Otherwise drag and drop it inside this list.
Finally use it in your code to make URL requests:
if let url = NSURL(string: "https://my-https-website.com") {

    let session = URLSession(
            configuration: URLSessionConfiguration.ephemeral,
            delegate: NSURLSessionPinningDelegate(),
            delegateQueue: nil)

    let task = session.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in
        if error != nil {
            print("error: \(error!.localizedDescription): \(error!)")
        } else if data != nil {
            if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
                print("Received data:\n\(str)")
            } else {
                print("Unable to convert data to text")
            }
        }
    })

    task.resume()
} else {
    print("Unable to create NSURL")
}

A: Thanks to the example found in this site: https://www.bugsee.com/blog/ssl-certificate-pinning-in-mobile-applications/ I built a version that pins the public key and not the entire certificate (more convenient if you renew your certificate periodically).
Update: Removed the forced unwrapping and replaced SecTrustEvaluate.
import Foundation
import CommonCrypto

class SessionDelegate : NSObject, URLSessionDelegate {

private static let rsa2048Asn1Header:[UInt8] = [
    0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
    0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00
];

private static let google_com_pubkey = ["4xVxzbEegwDBoyoGoJlKcwGM7hyquoFg4l+9um5oPOI="];
private static let google_com_full = ["KjLxfxajzmBH0fTH1/oujb6R5fqBiLxl0zrl2xyFT2E="];

func urlSession(_ session: URLSession,
                didReceive challenge: URLAuthenticationChallenge,
                completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    guard let serverTrust = challenge.protectionSpace.serverTrust else {
        completionHandler(.cancelAuthenticationChallenge, nil);
        return;
    }

    // Set SSL policies for domain name check
    let policies = NSMutableArray();
    policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString)));
    SecTrustSetPolicies(serverTrust, policies);

    var isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil);

    if(isServerTrusted && challenge.protectionSpace.host == "www.google.com") {
        let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
        //Compare public key
        if #available(iOS 10.0, *) {
            let policy = SecPolicyCreateBasicX509();
            let cfCertificates = [certificate] as CFArray;

            var trust: SecTrust?
            SecTrustCreateWithCertificates(cfCertificates, policy, &trust);

            guard trust != nil, let pubKey = SecTrustCopyPublicKey(trust!) else {
                completionHandler(.cancelAuthenticationChallenge, nil);
                return;
            }

            var error:Unmanaged<CFError>?
            if let pubKeyData = SecKeyCopyExternalRepresentation(pubKey, &error) {
                var keyWithHeader = Data(bytes: SessionDelegate.rsa2048Asn1Header);
                keyWithHeader.append(pubKeyData as Data);
                let sha256Key = sha256(keyWithHeader);
                if(!SessionDelegate.google_com_pubkey.contains(sha256Key)) {
                    isServerTrusted = false;
                }
            } else {
                isServerTrusted = false;
            }
        } else { //Compare full certificate
            let remoteCertificateData = SecCertificateCopyData(certificate!) as Data;
            let sha256Data = sha256(remoteCertificateData);
            if(!SessionDelegate.google_com_full.contains(sha256Data)) {
                isServerTrusted = false;
            }
        }
    }

    if(isServerTrusted) {
        let credential = URLCredential(trust: serverTrust);
        completionHandler(.useCredential, credential);
    } else {
        completionHandler(.cancelAuthenticationChallenge, nil);
    }

}

func sha256(_ data : Data) -> String {
    var hash = [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))
    data.withUnsafeBytes {
        _ = CC_SHA256($0, CC_LONG(data.count), &hash)
    }
    return Data(bytes: hash).base64EncodedString();
}

}

A: Here's an updated version for Swift 3
import Foundation
import Security

class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {

        // Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS

        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
            if let serverTrust = challenge.protectionSpace.serverTrust {
                var secresult = SecTrustResultType.invalid
                let status = SecTrustEvaluate(serverTrust, &secresult)

                if(errSecSuccess == status) {
                    if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
                        let serverCertificateData = SecCertificateCopyData(serverCertificate)
                        let data = CFDataGetBytePtr(serverCertificateData);
                        let size = CFDataGetLength(serverCertificateData);
                        let cert1 = NSData(bytes: data, length: size)
                        let file_der = Bundle.main.path(forResource: "name-of-cert-file", ofType: "cer")

                        if let file = file_der {
                            if let cert2 = NSData(contentsOfFile: file) {
                                if cert1.isEqual(to: cert2 as Data) {
                                    completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust))
                                    return
                                }
                            }
                        }
                    }
                }
            }
        }

        // Pinning failed
        completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
    }

}

A: The openssl command in @lifeisfoo's answer will give an error in OS X  for certain SSL certificates that use newer ciphers like ECDSA.
If you're getting the following error when you run the openssl command in @lifeisfoo's answer:
    write:errno=54
    unable to load certificate
    1769:error:0906D06C:PEM routines:PEM_read_bio:no start
    line:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL09
    8-59.60.1/src/crypto/pem/pem_lib.c:648:Expecting: TRUSTED CERTIFICATE

You're website's SSL certificate probably is using an algorithm that isn't supported in OS X's default openssl version (v0.9.X, which does NOT support ECDSA, among others).
Here's the fix:
To get the proper .der file, you'll have to first brew install openssl, and then replace the openssl command from @lifeisfoo's answer with:
/usr/local/Cellar/openssl/1.0.2h_1/bin/openssl [rest of the above command]
Homebrew install command:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

hope that helps.

A: You can try this.
import Foundation
import Security

class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {

      let certFileName = "name-of-cert-file"
      let certFileType = "cer"

      func urlSession(_ session: URLSession,
                  didReceive challenge: URLAuthenticationChallenge,
                  completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {

    if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
        if let serverTrust = challenge.protectionSpace.serverTrust {
            var secresult = SecTrustResultType.invalid
            let status = SecTrustEvaluate(serverTrust, &secresult)

            if(errSecSuccess == status) {
                if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
                    let serverCertificateData = SecCertificateCopyData(serverCertificate)
                    let data = CFDataGetBytePtr(serverCertificateData);
                    let size = CFDataGetLength(serverCertificateData);
                    let certificateOne = NSData(bytes: data, length: size)
                    let filePath = Bundle.main.path(forResource: self.certFileName,
                                                         ofType: self.certFileType)

                    if let file = filePath {
                        if let certificateTwo = NSData(contentsOfFile: file) {
                            if certificateOne.isEqual(to: certificateTwo as Data) {
                                completionHandler(URLSession.AuthChallengeDisposition.useCredential,
                                                  URLCredential(trust:serverTrust))
                                return
                            }
                        }
                    }
                }
            }
        }
    }

    // Pinning failed
    completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
}

Source: https://www.steveclarkapps.com/using-certificate-pinning-xcode/


Q: ViewPager with classes instead of layouts? Basically what I'm trying to do is I want to have a ViewPager.
But it should swipe between classes instead of layouts so that every page of the ViewPager has its own class where it also has its own stuff.
If you take instagram for instance. It has a BottomNavigationView where every item has its own acticity which handles its own methods and functions.
What I want to achieve is a BottomNavigationView like instagram which starts a new activity but with a slide animation to the left/right like with a ViewPager.


Q: How to add duplicate key elements in JavaScript Object? I want to make the following newArray using by following testArray.
newArray↓
    let newArray = [
        {section:"business",name:["Bob","John"]},
        {section:"H&R",name:["Jen","Bobby"]},
    ]

testArray↓
let test = [
    {section:"business",name:"Bob"},
    {section:"business",name:"John"},
    {section:"H&R",name:"Jen"},
    {section:"H&R",name:"Bobby"},
]

First of all, I tried to find some key elements using by filter method like below.
let newArray = test.filter((x:any,i,self)=>
                  self.indexOf(x.section)===i
             )

but this code output is [].
So, how do I make code to get my expected output?
Does anyone help me?

A: Use Array.reduce():

let test=[{section:"business",name:"Bob"},{section:"business",name:"John"},{section:"H&R",name:"Jen"},{section:"H&R",name:"Bobby"}];

let newArray = test.reduce((acc,cur) => {
  if(acc.some(el => el.section === cur.section)){
    acc.forEach((el,idx) => {
      if(el.section === cur.section){
        acc[idx].name.push(cur.name)
      }
    })
  }else{
    cur.name = [cur.name]
    acc.push(cur)
  }
  return acc
},[])

console.log(newArray)

A: you can try this

const test = [{
    section: "business",
    name: "Bob"
  },
  {
    section: "business",
    name: "John"
  },
  {
    section: "H&R",
    name: "Jen"
  },
  {
    section: "H&R",
    name: "Bobby"
  },
];

// gather sections
const sections = {};
test.forEach(t => {
  sections[t.section] = sections[t.section] || [];
  sections[t.section].push(t.name);
});

// convert sessions to array
const newArray = Object.keys(sections).map(k => {
  return {
    section: k,
    name: sections[k]
  };
});

console.log(newArray);


Q: How to resume multiple download using PersistableTransfer manager in amazon s3 in android I am downloading a list of objects using following function:
TransferManager transferManager = new TransferManager(s3client);
        try {

            GetObjectRequest getRequest = new GetObjectRequest(bucketName, entity.getName());
            download = transferManager.download(getRequest, f, new S3ProgressListener() {

                @Override
                public void onPersistableTransfer(PersistableTransfer arg0) {
                    // TODO Auto-generated method stub

                    saveTransferState(arg0,  Environment.getExternalStorageDirectory()+"/"+entity.getName());
                }
                @Override
                public void progressChanged(
                        com.amazonaws.event.ProgressEvent arg0) {

                    long transferred = arg0.getBytesTransferred();
                    Log.d("AWS3", "" + transferred);
                }
            });

Now when my internet connection stops while downloads were in progress i pause this download and resume it when internet connection again available using following code:
TransferManager transferManager = new TransferManager(S3Getter.s3client);
             String bucket = "Short_Films";
            String key = entity.getName();
            String[] parts = key.split("/");
            String fileName = parts[parts.length - 1];

            final String full_path = Environment.getExternalStorageDirectory()+"/"+entity.getName();
            File file = new File(full_path);
            FileInputStream fis = null;
            if(file.exists()) {
                try {
                    fis = new FileInputStream(file);
                    PersistableDownload persistableUpload = PersistableTransfer.deserializeFrom(fis);
                    S3Getter.download = transferManager.resumeDownload(persistableUpload);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }

Now the problem is this code works fine to resume single object. But when there are multiple objects to resume it resume only last resumed object.
I am stuck at this point.
Please some body help me.....


Q: Python: How to replace missing values column wise by median I have a dataframe as follows
df = pd.DataFrame({'A': [1, 2, 3], 'B': [1.45, 2.33, np.nan], 'C': [4, 5, 6], 'D': [4.55, 7.36, np.nan]})

I want to replace the missing values i.e. np.nan in generic way. For this I have created a function as follows
def treat_mis_value_nu(df):
    df_nu = df.select_dtypes(include=['number'])
    lst_null_col = df_nu.columns[df_nu.isnull().any()].tolist()
        if len(lst_null_col)>0:
            for i in lst_null_col:
                if df_nu[i].isnull().sum()/len(df_nu[i])>0.10:
                    df_final_nu = df_nu.drop([i],axis=1)
                else:
                    df_final_nu = df_nu[i].fillna(df_nu[i].median(),inplace=True)
    return df_final_nu

When I apply this function as follows
df_final = treat_mis_value_nu(df)

I am getting a dataframe as follows
    A    B  C
 0  1  1.0  4
 1  2  2.0  5
 2  3  NaN  6

So it has actually removed column D correctly, but failed to remove column B.
I know in past there have been discussion on this topic (here). Still I might be missing something?

A: Use:
df = pd.DataFrame({'A': [1, 2, 3,5,7], 'B': [1.45, 2.33, np.nan, np.nan, np.nan],
                   'C': [4, 5, 6,8,7], 'D': [4.55, 7.36, np.nan,9,10],
                   'E':list('abcde')})
print (df)
   A     B  C      D  E
0  1  1.45  4   4.55  a
1  2  2.33  5   7.36  b
2  3   NaN  6    NaN  c
3  5   NaN  8   9.00  d
4  7   NaN  7  10.00  e

def treat_mis_value_nu(df):
    #get only numeric columns to dataframe
    df_nu = df.select_dtypes(include=['number'])
    #get only columns with NaNs
    df_nu = df_nu.loc[:, df_nu.isnull().any()]
    #get columns for remove with mean instead sum/len, it is same
    cols_to_drop = df_nu.columns[df_nu.isnull().mean() <= 0.30]
    #replace missing values of original columns and remove above thresh
    return df.fillna(df_nu.median()).drop(cols_to_drop, axis=1)

print (treat_mis_value_nu(df))
   A  C      D  E
0  1  4   4.55  a
1  2  5   7.36  b
2  3  6   8.18  c
3  5  8   9.00  d
4  7  7  10.00  e

A: I would recommend looking at the sklearn Imputer transformer. I don't think it it can drop columns but it can definetly fill them in a 'generic way' - for example, filling in missing values with the median of the relevant column.
You could use it as such:
from sklearn.preprocessing import Imputer

imputer = Imputer(strategy='median')

num_df = df.values
names = df.columns.values

df_final = pd.DataFrame(imputer.transform(num_df), columns=names)

If you have additional transformations you would like to make you could consider making a transformation Pipeline or could even make your own transformers to do bespoke tasks.


Q: Overlap in labels of point data in rasterVis I have a raster r, one polygon shapefile regions and a point shapefile cities. I need to plot all three into one map layout. In addition to this I need to label point file with names of cities (cities$city$Town.Name) and their temperature and precipitation value (assigned as cities$labels). So I have used the following code with packages 'raster' and 'rasterVis'.
p1<-levelplot(regions.r,par.settings=mytheme,scales=list(draw=FALSE),xlab="",ylab="",margin=F)+
  layer(sp.polygons(regions))+
          layer(sp.points(cities,pch=20,cex=1.5,col="black"))
p1+
  layer(sp.text(coordinates(cities), txt = cities$city$Town.Name, pos = 3,col="black",font=list(face="bold"),cex=0.8))+
  layer(sp.text(coordinates(cities),txt = cities$label,
                pos = 1,cex=0.6,col="black"))#Add shapefile labels

This works fine when area has scattered cities distribution (see figure below).

However, if the cities are concentrated in one part I experience overlap of labels (see figure below). Is there a way to avoid the label overlap?


Q: How do I create an in-memory class and then include it in Perl? So I am toying with some black magic in Perl (eventually we all do :-) and I am a little confused as to exactly how I am supposed to be doing all of this.  Here is what I'm starting with:
use strict;
use warnings;
use feature ':5.10';
my $classname = 'Frew';
my $foo = bless({ foo => 'bar' }, $classname);
no strict;
*{"$classname\::INC"} = sub {
      use strict;
      my $data =  qq[
         package $classname
         warn 'test';
         sub foo {
            print "test?";
         }
      ];
      open my $fh, '<', \$data;
      return $fh;
   };
use strict;
unshift @INC, $foo;
require $foo;
use Data::Dumper;
warn Dumper(\@INC);
$classname->foo;

I get the following errors (depending on whether my require line is commented out):
With require:
Recursive call to Perl_load_module in PerlIO_find_layer at crazy.pl line 16.
BEGIN failed--compilation aborted.

without:
$VAR1 = [
      bless( {
               'foo' => 'bar'
             }, 'Frew' ),
      'C:/usr/site/lib',
      'C:/usr/lib',
      '.'
    ];
Can't locate object method "foo" via package "Frew" at crazy.pl line 24.

Any wizards who know some of this black magic already: please answer!  I'd love to learn more of this arcana :-)
Also note:  I know that I can do this kind of stuff with Moose and other lighter helper modules, I am mostly trying to learn, so recommendations to use such-and-such a module will not get my votes :-)
Update:  Ok, I guess I wasn't quite clear originally with my question.  I basically want to generate a Perl class with a string (that I will manipulate and do interpolation into) based on an external data structure.  I imagine that going from what I have here (once it works) to that shouldn't be too hard.

A: I do this:
use MooseX::Declare;

my $class = class {
    has 'foo' => (is => 'ro', isa => 'Str', required => 1);
    method bar() {
        say "Hello, world; foo is ", $self->foo;
    }
};

Then you can use $class like any other metaclass:
my $instance = $class->name->new( foo => 'foo bar' );
$instance->foo; # foo-bar
$instance->bar; # Hello, world; foo is foo-bar

etc.
If you want to dynamically generate classes at runtime, you need to create the proper metaclass, instantiate it, and then use the metaclass instance to generate instances.  Basic OO. Class::MOP handles all the details for you:
my $class = Class::MOP::Class->create_anon_class;
$class->add_method( foo => sub { say "Hello from foo" } );
my $instance = $class->new_object;
...

If you want to do it yourself so that you can waste your time debugging something, perhaps try:
sub generate_class_name {
    state $i = 0;
    return '__ANON__::'. $i++;
}

my $classname = generate_class_name();
eval qq{
    package $classname;
    sub new { my \$class = shift; bless {} => \$class }
    ...
};

my $instance = $classname->new;

A: Here is a version which works:
#!/usr/bin/perl

use strict;
use warnings;

my $class = 'Frew';

{
    no strict 'refs';
    *{ "${class}::INC" } = sub {
        my ($self, $req) = @_;
        return unless $req eq  $class;
        my $data = qq{
            package $class;
            sub foo { print "test!\n" };
            1;
        };
        open my $fh, '<', \$data;
        return $fh;
    };
}

my $foo = bless { }, $class;
unshift @INC, $foo;

require $class;
$class->foo;

The @INC hook gets the name of the file (or string passed to require) as the second argument, and it gets called every time there is a require or use. So you have to check to make sure we're trying to load $classname and ignore all other cases, in which case perl continues down along @INC. Alternatively, you can put the hook at the end of @INC. This was the cause of your recursion errors.
ETA: IMHO, a much better way to achieve this would be to simply build the symbol table dynamically, rather than generating code as a string. For example:
no strict 'refs';
*{ "${class}::foo" } = sub { print "test!\n" };
*{ "${class}::new" } = sub { return bless { }, $class };

my $foo = $class->new;
$foo->foo;

No use or require is necessary, nor messing with evil @INC hooks.

A: For a simple example of how to do this, read the source of Class::Struct.
However, if I needed the ability to dynamically build classes for some production code, I'd look at MooseX::Declare, as suggested by jrockway.

A: A Perl class is little more than a data structure (usually a hashref)
that has been blessed into a package in which one or more class
methods are defined.
It is certainly possible to define multiple package namespaces in one
file; I don't see why this wouldn't be possible in an eval construct
that is compiled at run-time (see perlfunc for the two different
eval forms).
#!/usr/bin/perl

use 5.010;
use strict;
use warnings;
use Data::Dumper;

eval q[
    package Foo;
    sub new {
        my ( $class, %args ) = @_;
        my $self = bless { %args }, $class;
        return $self;
    }
    1;
];
die $@ if $@;

my $foo = Foo->new(bar => 1, baz => 2) or die;

say Dumper $foo;


Q: What is the name of this q/kdb+ feature? Does any flavor of LISP implement it? How? The q programming language has a feature (which this tutorial calls "function projection") where a function of two or more parameters can be called with fewer parameters than it requires, but the result is an intermediate object, and the function will not be executed until all remaining parameters are passed; one way to see it is that functions behave like multi-dimensional arrays, so that (f[x])[y] is equivalent to f[x;y]. For example ...
q)add:{x+y}
q)add[42;]
{x+y}[42;]
q)add[42;][3]
45
q)g:add[42;]
q)g[3]
45

Since q does not have lexical scoping, this features become very useful in obtaining lexical scoping behavior by passing the necessary variables to an inner function as a partial list of parameters; e.g. a print parameter decorator can be constructed using this feature:
q)printParameterDecorator:{[f] {[f;x] -1 "Input: ",string x; f x}f};
q)f: printParameterDecorator (2+);
q)f 3
Input: 3
5

My questions:

*

*Is the term "function projection" a standard term? Or does this feature carry a different name in the functional programming literature?

*Does any variety of LISP implement this feature? Which ones?

*Could you provide some example LISP code please?

A:
Is the term "function projection" a standard term? Or does this feature carry a different name in the functional programming literature?

No, you usually call it partial application.

Does any variety of LISP implement this feature? Which ones?

Practically all Lisp allow you to partially apply a function, but usually you need to write a closure explicitly. For example in Common Lisp:
(defun add (x y)
  (+ x y))

The utility function curry from alexandria can be used to create a closure:
USER> (alexandria:curry #'add 42)
#<CLOSURE (LAMBDA (&REST ALEXANDRIA.1.0.0::MORE) :IN CURRY) {1019FE178B}>

USER> (funcall * 3)  ;; asterisk (*) is the previous value, the closure
45

The resulting closure is equivalent to the following one:
(lambda (y) (add 42 y))

Some functional languages like OCaml only allow functions to have a single parameter, but syntactically you can define functions of multiple parameters:
(fun x y -> x + y)

The above is equivalent to:
(function x -> (function y -> x + y))

See also What is the difference between currying and partial application?

Nb. in fact the q documentation refers to it as partial application:

Notationally, projection is a partial application in which some arguments are supplied and the others are omitted

A: I think another way doing this :
q)f:2+
q)g:{"result: ",string x}
q)'[g;f]3
"result: 5"

It is composite function, passing 3 to f, then the result from f will be passed to g.
I'm not sure if it is LISP, but it could achieve the same result.


Q: Graphics and Graphics 2D in java I am having a problem changing the color of the diamond I had created when I am using methods in java. I don't know how to inherit or to correct it by using methods. I just want it to become object oriented I don't know how to properly do it. Please help me.
package Trial;

import javax.swing.*;
import java.awt.*;

public class ColorRed extends JApplet {
    public GradientPaint gradientPaint;
    public void paint(Graphics g){
        super.paint(g);
        Graphics2D g2 = (Graphics2D)g;
        GradientPaint black = new GradientPaint(50,20,Color.BLACK,50,50,Color.BLACK);
        blackDiamond(g2,black);
        GradientPaint yellowOrange = new GradientPaint(50,20,Color.YELLOW,50,50,Color.RED);
        redDiamond(g2,yellowOrange);

    }

    public void blackDiamond(Graphics2D g2,GradientPaint gradientPaint){
        int a [] = {100,50,100,150,100};
        int b [] = {10,60,110,60,10};
        setGradientPaint(gradientPaint);
        g2.setPaint(getGradientPaint());
        fillPolygon(a,b,5,g2);
    }
    public void redDiamond(Graphics2D g2,GradientPaint gradientPaint){
        int a2 [] = {100,60,100,140,100};
        int b2 [] = {20,60,100,60,20};
        setGradientPaint(gradientPaint);
        g2.setPaint(getGradientPaint());
        fillPolygon(a2,b2,5,g2);
    }

    public void fillPolygon(int a [], int b [] ,int c,Graphics2D g2){

        getGraphics().fillPolygon(a,b,c);
    }

    public GradientPaint getGradientPaint() {
        return gradientPaint;
    }

    public void setGradientPaint(GradientPaint gradientPaint) {
        this.gradientPaint = gradientPaint;
    }
}

This is the code that I try to create object-oriented but it doesn't inherit the color of gradient paint.
enter image description here
That is the result of my code
This the code that not yet create multiple methods
import javax.swing.*;
import java.awt.*;

public class ColorRed extends JApplet {
    public GradientPaint gradientPaint;
    public void paint(Graphics g){
        super.paint(g);
        Graphics2D g2 = (Graphics2D)g;
        int a [] = {100,50,100,150,100};
        int b [] = {10,60,110,60,10};
        g.fillPolygon(a,b,5);
        GradientPaint red = new GradientPaint(50,10,Color.RED,10,70,Color.ORANGE);
        g2.setPaint(red);
        int a2 [] = {100,60,100,140,100};
        int b2 [] = {20,60,100,60,20};
        g.fillPolygon(a2,b2,5);

    }
}

This is the result that I want:
enter image description here
I just want to correct it to organize so that I wont declare all the local variables in paint method I just want to seperate it in different methods the problem is that the Color doesn't change. Please help me thanks a lot. :)

A: Maybe organize it like this, so that the color is easily changed:
package Trial;

import javax.swing.*;
import java.awt.*;

public class ColorRed extends JApplet {
    private GradientPaint black;
    private GradientPaint yellowOrange;

    public void init() {
        setBlack(new GradientPaint(50,20,Color.BLACK,50,50,Color.BLACK));
        setYellowOrange(GradientPaint(50,20,Color.YELLOW,50,50,Color.RED));
    }

    public setBlack(GradientPaint black) {
        this.black = black;
    }

    public setYellowOrange(GradientPaint yellowOrange) {
        this.yellowOrange = yellowOrange;
    }

    public void paint(Graphics g){
        super.paint(g);
        Graphics2D g2 = (Graphics2D)g;
        blackDiamond(g2,black);
        redDiamond(g2,yellowOrange);
    }

    public void blackDiamond(Graphics2D g2,GradientPaint gradientPaint){
        int a [] = {100,50,100,150,100};
        int b [] = {10,60,110,60,10};
        g2.setPaint(gradientPaint);
        fillPolygon(a,b,5,g2);
    }
    public void redDiamond(Graphics2D g2,GradientPaint gradientPaint){
        int a2 [] = {100,60,100,140,100};
        int b2 [] = {20,60,100,60,20};
        g2.setPaint(gradientPaint);
        fillPolygon(a2,b2,5,g2);
    }

    public void fillPolygon(int a [], int b [] ,int c,Graphics2D g2){

        g2.fillPolygon(a,b,c);
    }
}

Unfortunately I didn't locate an online swing runner to test it.

A: I modified Adder's answer (which worked as advertised) so it would work without using JApplet (which is also tagged as deprecated).  I added some comments where different.

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;

    public class ColorRed extends JPanel {
       private GradientPaint black;
       private GradientPaint yellowOrange;

       JFrame                frame = new JFrame();

       public static void main(String[] args) {
          SwingUtilities.invokeLater(() -> new ColorRed().init());
       }

       public void init() {

          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

          // set the panel size
          setPreferredSize(new Dimension(500, 500));
          // add panel to frame.
          frame.add(this);
          // adjust frame and subcomponents
          frame.pack();
          // center on screen
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
          setBlack(new GradientPaint(50, 20, Color.BLACK, 50, 50, Color.BLACK));
          setYellowOrange(new GradientPaint(50, 20, Color.YELLOW, 50, 50, Color.RED));
       }

       public void setBlack(GradientPaint black) {
          this.black = black;
       }

       public void setYellowOrange(GradientPaint yellowOrange) {
          this.yellowOrange = yellowOrange;
       }
       // use paintComponent(g) and not  paint(g)
       public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          blackDiamond(g2, black);
          redDiamond(g2, yellowOrange);
       }

       public void blackDiamond(Graphics2D g2, GradientPaint gradientPaint) {
          int a[] = { 100, 50, 100, 150, 100
          };
          int b[] = { 10, 60, 110, 60, 10
          };
          g2.setPaint(gradientPaint);
          fillPolygon(a, b, 5, g2);
       }
       public void redDiamond(Graphics2D g2, GradientPaint gradientPaint) {
          int a2[] = { 100, 60, 100, 140, 100
          };
          int b2[] = { 20, 60, 100, 60, 20
          };
          g2.setPaint(gradientPaint);
          fillPolygon(a2, b2, 5, g2);
       }

       public void fillPolygon(int a[], int b[], int c, Graphics2D g2) {

          g2.fillPolygon(a, b, c);
       }
    }


Q: jquery remove everything after and including certain character I have a location - Pearl River, NY (10965) that I want displayed as Pearl River, NY (so it must delete (10965) -- including the space before ( -- I'm not looking to make a big deal of this and do anything server side. jQuery would work fine. I know this is probably simple as hell, I just don't use JS much.
Thanks!

A: location_string = location_string.replace(/ \([^)]*\)/, '');

On a side note, please stop thinking that jQuery is necessary for anything at all, especially not a string manipulation task like this. It really isn't, and jQuery is overhyped.

A: I'm not sure how you're given "Peal River NY..." (variable? innerHTML?), but you need to use a regular expression to match the (numbers), and the replace method to substitute the match for nothing "".
"Peal River, NY (10965)".replace(/ \([0-9]+\)/, "");

This doesn't use jQuery!
See the String.replace method.
As mentioned by @James in the comments, this snippet will leave "Peal River, NY ()" as "Peal River, NY ()", rather than removing the brackets. If this is a case you need to consider, change the + to *:
"Peal River, NY (10965)".replace(/ \([0-9]*\)/, "");

A: Use a regex:
var s = "Pearl River, NY (10965)";
alert(s.replace(/ \([\d]*\)/,''));

See it at this JSFiddle
Of course, here I am assuming you'll be wanting to replace only numbers in the brackets. For letter and underscore, use \w in place of \d
You might also want to make it a requirement that the item occurs at the end. In which case, the following will suffice:
alert(s.replace(/ \([\d]*\)$/,''));

You'll note that none of the above references jQuery. This is something that can be achieved with pure JavaScript.


Q: How to style a dashboard with CSS in dash and python? I don’t know much about CSS and I need help aligning these 4 smaller graphs under this larger graph. This is the closest I’ve come to being aligned.
I need the 4 smaller graphs to be aligned under the larger graph, but covering the whole page, how to do that?

my code:
fig_pick = px.pie(map_pick, values='Total', names='Map', title='Mapas com mais Picks no Valorant Champions 2022')
fig_pick.update_layout(margin=dict(l=40, r=25, t=45, b=20), height=300,  width=340 , template='darkly')

fig_ban = px.pie(map_ban, values='Total', names='Map', title='Mapas com mais Bans no Valorant Champions 2022')
fig_ban.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300,  width=340 , template='darkly')

fig_atk = px.bar(map_side, x='Map', y='Atk Wins', color='Map', title='Taxa de Vitórias nos mapas no lado de ataque pelo Valorant Champions em %:',
            labels={
    'Atk Wins': 'Vitórias no lado de Ataque em %',
    'Map': 'Mapa'        }, text='Atk Wins')

fig_atk.update_traces(textposition='inside',texttemplate='%{text:.3s}')
fig_atk.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300,  width=360 , template='darkly')

fig_def = px.bar(map_side, x='Map', y='Def Wins', color='Map', title='Taxa de Vitórias nos mapas no lado de defesa pelo Valorant Champions em %:',
            labels={
    'Def Wins': 'Vitórias no lado de Defesa em %',
    'Map': 'Mapa'        }, text='Def Wins')

fig_def.update_traces(textposition='inside',texttemplate='%{text:.3s}')
fig_def.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300,  width=360 , template='darkly')

app.layout = html.Div(children=[

        dbc.Row([

                dbc.Col([

                        dbc.Card([

                                 html.H5('Opcões'),
                                 dcc.Dropdown(opcoes, value = 'ACS' , id='check_opcao', style={'width': '100%'}),

                        ],style={'height': '94vh', 'margin': '20px', 'padding': '20px', 'width': '300px'})

                ], sm=2),

                dbc.Col([

                        dbc.Row([dcc.Graph( id='grafico_gc_players', style={ 'width': '1100px'})], style={ 'margin': '20px', 'margin-right': '70px'}),
                        dbc.Row([
                                dbc.Col([dcc.Graph(id='map_pick', figure=fig_pick)], sm=3),
                                dbc.Col([dcc.Graph(id='map_ban', figure=fig_ban)], sm=3),
                                dbc.Col([dcc.Graph(id='map_side_atk', figure=fig_atk )], sm=3),
                                dbc.Col([dcc.Graph(id='map_side_def', figure=fig_def )], sm=3)
                        ])

                ],sm=10)
        ])


Q: how to convert webp image to jpeg or png by using intervention image laravel I am developing an app in Laravel Framework (PHP). I want to upload image which have webp format and then convert it to jpeg or png image format. After converting the image i also want to upload it to s3 bucket.

A: Firstly we can use Intervention Image library. We must have php 7 and gd library installed. I am writing the commands to install gd library and webp library below (for ubuntu) :
sudo apt-get update
sudo apt-get install webp
sudo apt-get install php7.0-gd (check php version and then install accordingly)

now check file extension and if extension is webp, select your output file extension
$extension = $this->file->extension();

if($this->file->getMimeType() == 'image/webp'){
    $extension = 'png';
}
// Generate a random filename
$fileName = time() . '_' . strtolower(uniqid()) . '.' . $extension;

Now encode the image to desired format
if($this->file->getMimeType() == 'image/webp'){
    $image = $image->encode($extension);
}
$image = $image->stream();

Now upload the image to s3 bucket
Storage::disk('s3')->put($folderName . '/' . $fileName, $imageNormal->__toString());


Q: Intellij SBT project: How to change the content roots? This is the current content root configuration in my project:

However, I want the "scala" directory to be the actual test content root, and not the directory named "test". If I modify it, I get the warning that "Module is imported from Sbt. Any changes in its configuration will may be lost after re-importing." (and, indeed, they are).

Unfortunately, I couldn't find where in my Build.scala file (or any other file) this configuration is declared. What I can do to once and for all convince IntelliJ that "scala" is the correct test content root?
This is my Build.scala file (this is a Play 2.5.4 project if it matters):
import play.routes.compiler.StaticRoutesGenerator
import play.sbt.PlayScala
import play.sbt.routes.RoutesKeys._
import sbt.Keys._
import sbt._

object Build extends Build {
  val main = Project("Mp3Streamer", file(".")).enablePlugins(PlayScala).settings(
    scalaVersion := "2.11.8",
    version := "1.0-SNAPSHOT",
    addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full),
    libraryDependencies ++= Seq(
      // a bunch of dependencies
    ),

    resolvers += Resolver.mavenLocal,
    javaOptions ++= Seq("-Xmx4000M", "-Xms2024M", "-XX:MaxPermSize=2000M"),
    routesGenerator := StaticRoutesGenerator
  )
}

A: By adding scalaSource in Test := baseDirectory.value / "test" "/scala", to my Build.scala file, I've been able to make the "scala" folder a test source, but the parent "test" folder was still also a test source:

As far as I could tell, this is a setting inherited from Play, since if I removed the .enablePlugins(PlayScala) code, the "test" folder stops being a test source. Following the instructions in https://www.playframework.com/documentation/2.5.x/Anatomy#Default-SBT-layout, I disabled the play layout, and then manually added the source and resource directories, which I copied from https://github.com/playframework/playframework/blob/master/framework/src/sbt-plugin/src/main/scala/play/sbt/PlayLayoutPlugin.scala#L9, only modifying the test source, and adding my own resource folders. My modified Build.scala file is now:
val main = Project("Mp3Streamer", file("."))
      .enablePlugins(PlayScala)
      .disablePlugins(PlayLayoutPlugin)
      .settings(
           target := baseDirectory.value / "target",

           sourceDirectory in Compile := baseDirectory.value / "app",
           // My change
           sourceDirectory in Test := baseDirectory.value / "test" / "scala",

           resourceDirectory in Compile := baseDirectory.value / "conf",

           scalaSource in Compile := baseDirectory.value / "app",
           // My change
           scalaSource in Test := baseDirectory.value / "test" / "scala",
           // I've added this resource
           resourceDirectory in Test := baseDirectory.value / "test" / "resources",

           javaSource in Compile := baseDirectory.value / "app",

           sourceDirectories in(Compile, TwirlKeys.compileTemplates) := Seq((sourceDirectory in Compile).value),
           sourceDirectories in(Test, TwirlKeys.compileTemplates) := Seq((sourceDirectory in Test).value),

           // sbt-web
           sourceDirectory in Assets := (sourceDirectory in Compile).value / "assets",
           sourceDirectory in TestAssets := (sourceDirectory in Test).value / "assets",

           resourceDirectory in Assets := baseDirectory.value / "public",

           // Native packager
           sourceDirectory in Universal := baseDirectory.value / "dist",

           // Everything else is the same as the original Build.scala file

Honestly, this feels so hacky that I'll probably end up modifying my directory structure to match Play's default... But it's the principle that counts!


Q: Why did I lose data when I change the orientation of camera doing crop image? I'm doing an app that takes an image from camera and crop it after, but some how i'm losing the objects of my activity and when it comes back i get NullPointerExeception, on OnCreate method of it. But when i choose an image from gallery it works fine, because it does not close the activity.
public void onClick(DialogInterface dialog, int item) {
    if (items[item].equals("Camera")) {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, Constants.PICK_FROM_CAMERA);
    } else if (items[item].equals("Galeria")) {

        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        // ******** code for crop image
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("max-height", 800);
        intent.putExtra("max-width", 800);
        intent.putExtra("return-data", true);
        intent.putExtra("scaleType", "centerCrop");
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        try {
             startActivityForResult(Intent.createChooser(intent,
             "Complete action using"), Constants.PICK_FROM_GALLERY);
        } catch (ActivityNotFoundException e) {
        }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Bitmap tempImage;
    OutputStream fOut = null;

    File root = new File(Environment.getExternalStorageDirectory()
            + File.separator);

    try {
        File sdImageMainDirectory = new File(root, "foto.jpg");
        fOut = new FileOutputStream(sdImageMainDirectory);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (requestCode == Constants.PICK_FROM_CAMERA) {
        root = new File(Environment.getExternalStorageDirectory()
                + File.separator + "foto.jpg");
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        saveBitmap(photo, Environment.getExternalStorageDirectory()
                + File.separator + "foto.jpg");
        try{
            cropCapturedImage(Uri.fromFile(root));
        }catch(ActivityNotFoundException aNFE){
            //display an error message if user device doesn't support
            String errorMessage = "Desculpe, seu dispositivo não suporta Crop!";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }
    }
    if (requestCode == Constants.PICK_FROM_GALLERY && data != null) {
        Bundle extras2 = data.getExtras();
        if (extras2 != null) {
            Bitmap photo = extras2.getParcelable("data");
            this.photo.setImageBitmap(photo);

            this.photo.buildDrawingCache();
            tempImage = this.photo.getDrawingCache();

            try {
                tempImage.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                fOut.flush();
                fOut.close();
                BasicUserPerson.getInstance().setPhotoPath(
                        Environment.getExternalStorageDirectory()
                        + File.separator + "foto.jpg");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //user is returning from cropping the image
    else if(requestCode == Constants.PIC_CROP && data != null){
        //get the returned data
        Bundle extras = data.getExtras();
        if (extras != null){

            Bitmap thePic = (Bitmap) data.getExtras().get("data");
            saveBitmap(thePic, Environment.getExternalStorageDirectory()
                    + File.separator + "foto.jpg");

            photo.setImageBitmap(thePic);
            BasicUserPerson.getInstance().setPhotoPath(
                    Environment.getExternalStorageDirectory()
                    + File.separator + "foto.jpg");
        }
    }
}

public void saveBitmap(Bitmap photo, String path) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    File f = new File(path);
    try {
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void cropCapturedImage(Uri picUri){
    Intent cropIntent = new Intent("com.android.camera.action.CROP");
    cropIntent.setDataAndType(picUri, "image/*");
    cropIntent.putExtra("crop", "true");
    cropIntent.putExtra("aspectX", 1);
    cropIntent.putExtra("aspectY", 1);
    cropIntent.putExtra("outputX", 256);
    cropIntent.putExtra("outputY", 256);
    cropIntent.putExtra("return-data", true);
    cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    startActivityForResult(cropIntent, Constants.PIC_CROP);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.dados_pessoais);

    fullName = (EditText) findViewById(R.id.edtFullName);
    cpf = (EditText) findViewById(R.id.edtCpf);
    email = (EditText) findViewById(R.id.edtDadEmail);
    ddd = (EditText) findViewById(R.id.edtDadDDD);
    telefone = (EditText) findViewById(R.id.edtDadTele);
    ddd2 = (EditText) findViewById(R.id.edtDadDDD2);
    celular = (EditText) findViewById(R.id.edtDadTel);
    btSalvar = (ImageView) findViewById(R.id.imgSalvar);
    head = (ImageView) findViewById(R.id.imgDadosHead);
    sexo = (Spinner) findViewById(R.id.spnSex);
    birthday = (EditText) findViewById(R.id.edtBrithday);
    civil = (Spinner) findViewById(R.id.spnCivil);
    loadingCity = (ImageView) findViewById(R.id.imgLoadingCity);
    escolaridade = (Spinner) findViewById(R.id.spnEscolaridade);
    cep = (EditText) findViewById(R.id.edtCep);
    state = (Spinner) findViewById(R.id.spnState);
    city = (Spinner) findViewById(R.id.spnCity);
    endereco = (EditText) findViewById(R.id.edtEndereco);
    bairro = (EditText) findViewById(R.id.edtBairro);
    num = (EditText) findViewById(R.id.edtNum);
    comp = (EditText) findViewById(R.id.edtComp);
    photo = (ImageView) findViewById(R.id.imgPhoto);

    btSalvar.setOnClickListener(this);
    photo.setOnClickListener(this);

    //Line of error
    if (!User.getInstance().getFullName().equals("null") && !User.getInstance().getFullName().equals("")){
        fullName.setText(User.getInstance().getFullName());
    }
    if (!BasicUserPerson.getInstance().getPersonRegistration().equals("null") && !BasicUserPerson.getInstance().getPersonRegistration().equals("")){
        cpf.setText(BasicUserPerson.getInstance().getPersonRegistration());
    }
    if (!User.getInstance().getEmail().equals("null") && !User.getInstance().getEmail().equals("null")){
        email.setText(User.getInstance().getEmail());
    }
    email.setKeyListener(null);
    if (!BasicUserPerson.getInstance().getMobilePhone().equals("null") && !BasicUserPerson.getInstance().getMobilePhone().equals("")){
        String tel = BasicUserPerson.getInstance().getMobilePhone().replace("(", "").replace(")", "").replace(" ", "");
        ddd.setText(tel.subSequence(0, 2));
        celular.setText(tel.substring(2));
    }
    if (!BasicUserPerson.getInstance().getPhone().equals("null") && !BasicUserPerson.getInstance().getPhone().equals("")){
        String tel = BasicUserPerson.getInstance().getPhone().replace("(", "").replace(")", "").replace(" ", "");
        ddd2.setText(tel.subSequence(0, 2));
        telefone.setText(tel.substring(2));
    }
    if (!BasicUserPerson.getInstance().getBirthday().equals("null") && !BasicUserPerson.getInstance().getBirthday().equals("")){
        birthday.setText(BasicUserPerson.getInstance().getBirthday());
    }
    if (!BasicUser.getInstance().locationObj.getZipCode().equals("null") && !BasicUser.getInstance().locationObj.getZipCode().equals("")){
        cep.setText(BasicUser.getInstance().locationObj.getZipCode());
    }
    if (!BasicUser.getInstance().locationObj.getAddress().equals("null") && !BasicUser.getInstance().locationObj.getAddress().equals("")){
        endereco.setText(BasicUser.getInstance().locationObj.getAddress());
    }
    if (!BasicUser.getInstance().locationObj.getNeighborhood().equals("null") && !BasicUser.getInstance().locationObj.getNeighborhood().equals("")){
        bairro.setText(BasicUser.getInstance().locationObj.getNeighborhood());
    }

}

And it outputs:
  12-15 21:22:55.002: E/AndroidRuntime(2263): FATAL EXCEPTION: main
    12-15 21:22:55.002: E/AndroidRuntime(2263): Process: br.com.inradar, PID: 2263
    12-15 21:22:55.002: E/AndroidRuntime(2263): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.inradar/br.com.inradar.activities.DadosPessoais}: java.lang.NullPointerException
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.access$800(ActivityThread.java:139)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.os.Handler.dispatchMessage(Handler.java:102)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.os.Looper.loop(Looper.java:136)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.main(ActivityThread.java:5103)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at java.lang.reflect.Method.invokeNative(Native Method)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at java.lang.reflect.Method.invoke(Method.java:515)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at dalvik.system.NativeStart.main(Native Method)
    12-15 21:22:55.002: E/AndroidRuntime(2263): Caused by: java.lang.NullPointerException
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at br.com.inradar.activities.DadosPessoais.onCreate(DadosPessoais.java:176)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.Activity.performCreate(Activity.java:5275)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     ... 11 more

A: Are you using in this way
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
    if(resultCode == RESULT_OK) {
          // stub here
          }
        }
       }


Q: geofacet package in R adding labels to bar graphs in geofacets I recently discovered the geofacet package in R. Amazing.  I have 5 years worth of data for each state.  I have horizontal bars in each facet.  I am trying to figure out how to add a simple label that shows the value of each bar in each graph such that it sits off to the right of the bar or right side of the facet. I have tried geom_text and a number of code lines but nothing seems to add the labels for each bar in each facet.
Below is my code to make the geofacet of the US.  Not sure where to add the label code either.
Any help is greatly appreciated.  This is my last step to complete this awesome map.
ggplot(Alabamatest, aes(YEAR, SALES, fill = YEAR)) +
  geom_bar(alpha=1, width = .75,
    aes(color =TYPE, fill=TYPE),
    stat = "identity", position = position_stack(reverse = TRUE)
  ) +
  scale_color_manual(values = c("firebrick1", "cornflowerblue"))+
  scale_fill_manual(values = c("firebrick1", "cornflowerblue"))+
  ylim(0,9
  )+
  coord_flip() +
  theme_bw()+
  facet_geo(~ state, grid= "us_state_grid4", label ="SALES")+
  scale_y_continuous(expand = c(0, 0)) +
  labs(title = "2019 State Average Sales",
       caption = "Data Source: Year End Data",
       x = NULL,
       y = "Percentage of Voters") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        strip.text.x = element_text(size = 6))

I am adding some test data to run with the code.  I am not sure how to add a simple data frame so I have typed it out here.  I am brand new to Stackoverflow.   Apologies if this is not the correct way to present data
state    name    YEAR    SALES    TYPE
AL     ALABAMA    2019     2       POS
AL     ALABAMA    2018     1.5     POS
AL     ALABAMA    2017     1.4     NEG
AL     ALABAMA    2016     1.7     NEG
AZ     ARIZONA    2019     3       POS
AZ     ARIZONA    2018     3       POS
AZ     ARIZONA    2017     2       POS
AZ     ARIZONA    2016     3.4     POS
AZ     ARIZONA    2015     5       POS

The two states create bar graphs.   I want to be able to add the sales label to the right side of the bar graph for each year.


Q: How much does minifying reduce file size? In a React app, is it possible to find out how much Webpack's minification reduces the project's size excluding all the dependencies and packages not written by the project's developer?
My build/static/ directory is currently bigger than my src directory and I believe it is because code from the dependencies is also minified with the files of interest. Where could I find something to approximately compare my src directory size to?

A: I built the project with npm run build to find out how large the output is with minimization enabled.
Then I edited node_modules/react-scripts/config/webpack.config.js and changed line 189 (the line with the minimize property) from:
...
    optimization: {
      minimize: isEnvProduction,
      minimizer: [
...

to:
...
    optimization: {
      minimize: false,
      minimizer: [
...

to disable minimization.
Then built the project again to find out its size without minimization.
You can compare the built file sizes manually to find out their difference, but you will also get a nice output to the terminal when building the second time:
File sizes after gzip:

  613.36 KB (+504.48 KB)  build\static\js\2.0ddf8239.chunk.js
  60.24 KB (+20.01 KB)    build\static\js\main.8e9dd59c.chunk.js
  4.73 KB (+457 B)        build\static\css\main.aaaa4d7d.chunk.css
  1.66 KB (+933 B)        build\static\js\runtime~main.7f8cc4df.js

Notice the differences stated in parantheses.


Q: Memory issue when create a diagonal numpy array I have created a diagonal numpy array:
a = numpy.float32(numpy.random.rand(10))
a = numpy.diagonal(a)

However, I face MemoryError since my matrix is extremely large. Is there anyway to save the memory?

A: The best way to handle this case is to create a sparse matrix using scipy.sparse.diags as follows:
a = numpy.float32(numpy.random.rand(10))
a = sparse.diags(a)

If the shape of your diagonal numpy array is n*n, utilizing sparse.diags would result in a matrix n times smaller. Almost all matrix operations are supported for sparse matrices.


Q: When is the appropriate moment in rotation to change the Layout parameters of a UICollectionView Hopefully a simple question for a relatively new UIKit control
I have a UICollectionView that has a viewLayout with a single row of cells that are the exact height of the UICollectionView bounds in Portrait mode
Therefore, when the iPad is flipped to Landscape mode, that row becomes taller than the screen itself, at which point the layout (almost) silently fails and complains that the row is taller than the bounds.
What is the ideal way to manipulate the characteristics of the viewLayout, particularly as it relates to responding to rotation in a ViewController?

A: I'm working on a similar problem.
Currently, my UICollectionViewController has two instance variables of UICollectionViewFlowLayout, each with the appropriate insets for portait or landscape.
On rotation, I do this:
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                               duration:(NSTimeInterval)duration{

    if (UIDeviceOrientationIsPortrait(toInterfaceOrientation)) {
        [_itemCollection setCollectionViewLayout:_portraitLayout];
        [_itemCollection reloadData];
    } else {
        [_itemCollection setCollectionViewLayout:_landscapeLayout];
        [_itemCollection reloadData];
    }
}

The only problem that I'm having is that it randomly crashes with exc_bad_access on setCollectionViewLayout randomly.
Something like the above might work for you. I'm not sure if this is the right way to do things. I have only recently started using UICollectionViews.


Q: Python PyAutoGUI (automatic mouse macro) I want to display the (x.y) coordinates of the mouse found using "pyautogui.position()" on the window. What command should I use in this case?

A: If you want to print out the x,y mouse positions, you can use .position() like so:
print(pyautogui.position())

It will output something like (346, 653) (the numbers will be different, and this is just an example) where the first value is the x coordinate of the cursor, and the second value being the y coordinate.


Q: React Router v4 - How to dynamically use layouts To start, I'm both new to React and React-Router. I know the basics of each. Here is my scenario...
I want to have a separate login page with NO layouts at route (/login). When the user logs in, I want to route them to /home. This home page and every other page (beside login) will reuse a layout that contains a navbar and a sidebar.
How do I hide the reusable layout when the user visits the /login route? Do I use a conditional or is there a specific React-Router 'WAY'? I couldn't find examples in the documentation that fit my scenario.
Thanks a bunches!

A: If you are asking how could I render navbar and sidebar to all components except login, then you can check the browser url.
There are many ways of doing this, but one of which is like following:
<Route path="*" render={props => <Layout {...props} />} />

This will appear for all your routes now. Then inside Layout, you can check the route, and only render something if the route does not equal to login.
render(){
  if(this.props.location === "login"){return null}
  ...
}

While typing this, you can do it directly in React Router, maybe excluding certain route.


Q: Google Maps API-Key in gmaps4rails Why don't I have to supply my own gmaps-api-key in gmaps4rails?

A: Actually, you don't need the API key because, Google Maps Javascript API V3 is used there.
Only Google maps Javascript V2 requires an api-key, and it's deprecated now.


Q: Java regex for word with dot I need to a regex to validate a string like "foo.com". A word which contains a dot. I have tried several but could not get it work.
The patterns I have tried:

*

*(\\w+\\.)

*(\\w+.)

*(\\w.)

*(\\W+\\.)
Can some one please help me one this.
Thanks,

A: Use regex with character class
([\\w.]+)

If you just want to contain single . then use
(\\w+\\.\\w+)

In case you want multiple . which is not adjacent then use
(\\w+(?:\\.\\w+)+)

A: To validate a string that contains exactly one dot and at least two letters around use match for
\w+\.\w+

which in Java is denoted as
\\w+\\.\\w+

A: This regex works:
[\w\[.\]\\]+
Tested for following combinations:
foo.com
foo.co.in
foo...
..foo

A: I understand your question like, you need a regex to match a word which has a single dot in-between the word (not first or last).
Then below regex will satisfy your need.
^\\w+\\.\\w+$


Q: Restricting one view on Flask-Admin? I have a single file for a Flask application, views.py.
Inside views.py, I have the setup for Flask-Admin and the corresponding sqlalchemy database here:
db = SQLAlchemy(flaskapp)

def build_db():

import random
import datetime

db.drop_all()
db.create_all()

# Create sample Users
testuser = []
testgroup = []
testlevel = []

user_list = []
for i in range(len(testuser)):
    user = User()
    user.testuser = testuser[i]
    user.testlevel = testlevel[i]
    user.testgroup = testgroup[i]

    user_list.append(user)
    db.session.add(user)

for user in user_list:
    entry = random.choice(sample_text)  # select text at random
    post = Post()
    post.user = user
    post.title = entry['title']
    post.text = entry['content']
    tmp = int(1000*random.random())  # random number between 0 and 1000:
    post.date = datetime.datetime.now() - datetime.timedelta(days=tmp)
    post.tags = random.sample(tag_list, 2)  # select a couple of tags at random
    db.session.add(post)

db.session.commit()
return

# Create models
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    testuser = db.Column(db.String(100))
    testgroup = db.Column(db.String(100))
    testlevel = db.Column(db.String(100))

# Required for administrative interface. For python 3 please use __str__ instead.
def __repr__(self):
    return self.testuser

class UserInfo(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    key = db.Column(db.String(64), nullable=False)
    value = db.Column(db.String(64))

    user_id = db.Column(db.Integer(), db.ForeignKey(User.id))
    user = db.relationship(User, backref='info')

def __repr__(self):
    return '%s - %s' % (self.key, self.value)

### Attempt at doing something...
class MyView(ModelView):
    @expose('/admin/userview', methods=('GET', 'POST'))
    def adminview():
        return "yes"
##ADMIN
admin = Admin(flaskapp, name="Test Aptly")
admin.add_view(MyView(User, db.session))

The Question.
How do I block access to the "/admin/userview" page depending on what level the user is (defined with the database "testlevel")? Users have 3 qualities, An example for two users would be:
testuser          testgroup        testlevel

joe               it               admin

john              dev              basic

How would I restrict the admin page to only let people with testlevel="admin"?
Do I use Flask-Security? Flask-Principal? If so, how? I've been tinkering with both for a little bit and I haven't gotten anything working so far.
Here's an example "/admin/userview" looks like: example Flask-Admin

First of all, you can use various class-level properties to configure
  what should be displayed and how. For example, column_list can be used
  to show some of the column or include extra columns from related
  models.
For example:

class UserView(ModelView):
    # Show only name and email columns in list view
    column_list = ('name', 'email')

    # Enable search functionality - it will search for terms in
    # name and email fields
    column_searchable_list = ('name', 'email')

    # Add filters for name and email columns
    column_filters = ('name', 'email')

Alternatively, you can override some of the ModelView methods and
  implement your custom logic.
For example, if you need to contribute additional field to the
  generated form, you can do something like this:

class UserView(ModelView):
    def scaffold_form(self):
        form_class = super(UserView, self).scaffold_form()
        form_class.extra = wtf.TextField('Extra')
        return form_class

Check flask.ext.admin.contrib.sqlamodel documentation for list of
  configuration properties and methods. Thanks!

A: I'll assume that you subclassed BaseView to create your admin view and that you are using Flask-login.
Then override the is_accessible method in your view class, to check the current user's quality:
from flask.ext.admin.base import BaseView
from flask.ext.login import current_user

class MyView(BaseView):
    def is_accessible(self):
        return current_user.testlevel == 'admin'

Hope this helps!


Q: The method in the type is not applicable for the arguments (even though they are?!) I'm trying to call a method using parameters that definitely match my args, yet I get this error...

The method getAdministratablePaging(Long, ContentFilter, int, int, Integer, Integer) in the type ContentService is not applicable for the arguments (Long, ContentFilter, int, int, Integer, Integer)

The code is...
ResultPage knowledgeCenters = _kcs.getAdministratablePaging(ContentConstants.KNOWLEDGE_ROOT, filter, 0, Constants.COUNT_ALL, ContentConstants.COLUMN_SIZE, Constants.SORT_ORDER_ASCENDING);

I'm working in Eclipse and have tried Clean and rebooting the IDE. Suggestions much appreciated!

A: Just putting my comment as an answer in case it can help somebody seeing this question in the future.
When you see a message like this, then the only possibility is that there are multiple types of one of the parameter objects. In this case, @nscoppin had two different definitions for ContentFilter. Either import the correct one, or use the fully qualified name in the method call, ie
someMethod(com.packageA.subPackage.ContentFilter);


Q: what is the dpdk0's effect in ovs-dpdk? today i get other guy's confiuration about ovs-dpdk,the config file is below:
dpdk-devbind –s
dpdk-devbind --force --bind=ixgbe 0000:81:00.0
dpdk-devbind --force --bind=ixgbe 0000:81:00.1
dpdk-devbind --force --bind=igb_uio 0000:81:00.0
dpdk-devbind --force --bind=igb_uio 0000:81:00.1
ovs-vsctl del-port br-eth6 eth6
ovs-vsctl del-port br-eth9 eth9
ovs-vsctl  -- set Interface dpdk0 type=dpdk options:dpdk-devargs= 0000:06:00.0,n_rxq=1
ovs-vsctl  -- set Interface eth6 type=dpdk options:dpdk-devargs= 0000:81:00.0,n_rxq=1
ovs-vsctl  -- set Interface eth7 type=dpdk options:dpdk-devargs= 0000:81:00.1,n_rxq=1

the config file describe about take eth6 and eth9 ethernet interface to ovs bridge br-eth6 and br-eth9 but i wonder to know why set interface dpdk0's type to dpdk ? Does the port dpdk0 is a specific port or something else?
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.

A: Based on the comments discussion, the problem turned out to be the configuration file sequence. Recommend approach of removing the Kernel Ports, then binding with dpdk compatible driver works
ovs-vsctl del-port br-eth6 eth6
ovs-vsctl del-port br-eth9 eth9
dpdk-devbind –s
dpdk-devbind --force --bind=ixgbe 0000:81:00.0
dpdk-devbind --force --bind=ixgbe 0000:81:00.1
dpdk-devbind --force --bind=igb_uio 0000:81:00.0
dpdk-devbind --force --bind=igb_uio 0000:81:00.1
ovs-vsctl  -- set Interface dpdk0 type=dpdk options:dpdk-devargs= 0000:06:00.0,n_rxq=1
ovs-vsctl  -- set Interface eth6 type=dpdk options:dpdk-devargs= 0000:81:00.0,n_rxq=1
ovs-vsctl  -- set Interface eth7 type=dpdk options:dpdk-devargs= 0000:81:00.1,n_rxq=1


Q: GreG nested templates We need to nest templates in the main template. The nested template should be able to display fields that the customer can fill. For example, there are two attachments to this message. The file 1.jpg: In this picture you can see how it displays a button with the plus sign. It has a red arrow. When I press the button it shows a nested template. In this template I can fill the event type and a path field, and nothing else. In our case we need to display fields that the user can fill, and the option of add more templates nested within the nested template. In the picture 2.jpg you can see the result that we need. This image 2 shows a red arrow that point to a green button. If you press the green button it displays another nested template. In this template you can fill in more fields. In addition you have another green button to nest another template.
Summarizing we need to create complex templates, that is, templates included in a main template.

A: If you mean RXT nesting by nested templates, WSO2 Governance Registry does not support nested RXTs as of now.


Q: PHP preg_match: exclude whitespaces I'm working on some code block that validates a config file containing PHP variable. I want to detect variables left empty using preg_match.
If the file contains the following lines:
$db_host = "blablah";
  $db_host   ='blablah';
$db_host='';
    $db_host=" ";
  $db_host="";

I'd like to match only lines 3-4-5, lines 1 and 2 being valid (no empty value). The following preg_match works well but matches all lines, not handling the whitespaces or empty values; how could I match only empty/whitespaced values?
preg_match( '#\$db_host(\ +)?\=(\ +)?(\'|\")(.*?)(\'|\");#i', $string );

Note: I'd rather not included the files to validate to check their validity. There might be a lot of them and I can't assume I'll always have control on their content. I'd rather not include unknown, third party code into my own.

A: How should your regex check something like this?:
$a = '';
$b = $a;
$c = preg_replace('/.*/', $a);

You should use PHP to check the variables and not a regex:
include 'config.php';

foreach(array(
    'db_host', 'db_pass', ...
) as $varname) {
    $value = trim($$varname);
    if(empty($value)) {
        die($varname . ' must not be empty');
    }
}

Also you should use trim() to avoid variables containing just whitespace content. (thanks @SamuelCook)

A: Why use preg_match when you can use trim() & empty() to check if it's empty or not.
Take the following examples:
<?php
$str[0] = ' ';
$str[1] = "\t";
$str[2] = "\r\n";

foreach($str as $k=>$val){
    $val = trim($val);
    if(empty($val)){
        echo $k.' is empty<br>';
    }
}

They will all return empty.

A: You can use this pattern:
$pattern = '~\$db_host\s*=\s*(["\'])\s*\1\s*;~';

\s* means "any white character zero or more times". White characters are spaces, tabs, carriage returns and newlines, but if you want, you can replace \s by \h that matches only horizontal white characters (i.e. tabs and spaces).
I put the type of quote in a capturing group with (["\']) and then I use a backreference to this group with \1 (1 because it is the first capturing group of the pattern).


Q: PHP 7.1 on hosted server not recognizing session.save_path I am pulling my hair out over this issue.  It seems simple enough, but the following simple script is not working for me.  I want to keep my session files in the directory as indicated.  I have the 'musanizer_session_tmp' folder in the same root with this php script:
if (!isset($_REQUEST['testit'])) {
    ini_set ('session.auto_start' , '1' );
    ini_set('session.save_path', '../musanizer_session_tmp');
    $_SESSION['tester'] = 'Testing Session Save Path! ';
    echo '<script language="Javascript">';
    echo 'window.location.href="sesstest.php?testit=YES"';
    echo '</script>';
}
else
{
    echo "===>>> ". $_SESSION['tester'].date('H:i:s');
}

Isn't that fairly straightforward and correct?


Q: Is "undefined" in Javascript an error or just a notice? Is the undefined message in the pop up or console log (e.g. when calling a variable that doesn't exist) an ERROR message or just a NOTICE message?
In PHP there is a difference, so, looking for your explanation on this subject.

A: Neither, it is a value (or a stringification of a value in the case of an alert)
Whether or not you can ignore the fact that a variable/property/whatever is undefined depends on the needs of the program you are writing. If a message displays "undefined" when it should display "sweet cuppin' cakes", then that would be a logic error; conversely, if a message displays undefined when it is merely intended to reflect an internal state that can legitimately be undefined, it would not be an error.

A: It sounds to me like an incomplete error message; like when a developer prints "This should never appear!11" Undefined is nothing more than a value, so seeing it on its own does not assign any meaning or importance to the message.

A: 'undefined' means exactly what it says - you have referenced a variable name that is not defined.
Some languages, like Python, are stricter about this kind of thing, and will throw an error if you try to do this.
Javascript assumes you know what you are doing, and so doesn't complain.

A: undefined is a special data type. For example, a common case is a missing parameter in a function call:
var foobar = function(val)
{
    alert(typeof val); // alerts 'undefined'
    alert(foobar.length); // throws an error
}

foobar();

The author of this example function should have checked for the type of val before trying to access the length property.

A: Undefined is, what its name says, a sign for something beeing not defined, like
var a=new Array(10);

It is an array: Array.isArray(a)is true, a.length is 10; but all it contains are undefined values: e.g. a[5] is undefined. So it is no error.

ERROR message or just a NOTICE message?

Neither nor.


Q: How do i remove or merge duplicated values in my JSON List? My Json looks like this,
[
    {
        "MatchNumber": 1,
        "RoundNumber": 1,
        "HomeTeam": "Crystal Palace",
        "AwayTeam": "Liverpool",
        "Group": null,
        "HomeTeamScore": 0,
        "AwayTeamScore": 2
    },
    {
        "MatchNumber": 16,
        "RoundNumber": 2,
        "HomeTeam": "Fulham",
        "AwayTeam": "Liverpool",
        "Group": null,
        "HomeTeamScore": 2,
        "AwayTeamScore": 2
    },
    {
        "MatchNumber": 11,
        "RoundNumber": 2,
        "HomeTeam": "Arsenal",
        "AwayTeam": "Leicester",
        "Group": null,
        "HomeTeamScore": 4,
        "AwayTeamScore": 2
    },
    {
        "MatchNumber": 191,
        "RoundNumber": 20,
        "HomeTeam": "Arsenal",
        "AwayTeam": "Leeds",
        "Group": null,
        "HomeTeamScore": null,
        "AwayTeamScore": null
    }
]

for this Json example, using this list will produce 2 Arsenal in the HomeTeam and 2 Liverpool AwayTeam in the dropdown list.
here's my controller code so far, i tried set but it only reordered the list, didn't remove duplicated teams.
@Controller
public class CCController {
private static final String MAIN_PAGE = "main";
private static final String JSON_URL = "https://randomfootball.com/json/epl-2022";
  @GetMapping("/")
    public String main(Model model, @ModelAttribute Team team){
       List<Team> teams = (List<Team>) parsingService.parse(JSON_URL);
       Set<Team> targetSet = new HashSet<>(teams);
       model.addAttribute("teamList", targetSet);
        return MAIN_PAGE;
    }
}

here is my Team model, added as per request.
thanks for any guidance
public class Team{

    public Team() {
    }

    Set<String> HomeTeam;

    public Set<String> getHomeTeam() {
        return HomeTeam;
    }

    public void setHomeTeam(Set<String> homeTeam) {
        HomeTeam = homeTeam;
    }

    public static Set<String> keySet() {
        return null;
    }
}

I finally got a list that doesn't duplicate.
I did it by getting the object from the array of Json. Build that into JsonArray, then use set. That requires a dependency, jakarta.json.


Q: Do I have to do a dispatch again or why is my code not running? I am trying to make it so when I do an ajax request my preload shows up when a request finishes(success or not) it goes away.
I am using Axios and they have interceptors for request and response. I am trying to do request right now.
import axios from "axios";
import {setPreLoader}  from './PreLoaderActions.js';

export const axiosInstant = axios.create({
    baseURL: 'http://localhost:54690/api',
    timeout: 2000,
});

export const config = axiosInstant.interceptors.request.use( config => {
    // Do something before request is sent
    console.log('afaf');
    setPreLoader(true);
    return config;
  }, function (error) {
    // Do something with request error
   // this.setPreLoader(false);
    return Promise.reject(error);
  });

import {actions}  from './Actions.js';

export function setPreLoader(show) {
     return function (dispatch) {
        dispatch({ type: actions.SHOW_PRE_LOADER, payload: { showPreLoader: show }  });
    };
}

when my setPreloader(true) gets hit nothing happens. Nothing is dispatched. Not sure if I need to do something else as I only ever done this in a react component so redux/reactjs might be doing something for me behind the scenes.

A: The setPreLoader function doesn't do anything itself beside returning another anonymous function. Therefore, just calling setPreLoader(true) does nothing because the anonymous function is not called.
You have to call the result of setPreLoader(true) with appropriate function:
setPreLoader(true)(someFunction)


Q: Write the content of an object into a file in C++ I'm using OpenCV, and I am computing the histogram of some images, which is contained inside a class named CvHist. I have a CvHist object, but I want to store it to use it later on in another file. How can I do that?
Thank you

A: Actually, in OpenCV there is a specific way to do that. You can write an object in an XML file as follow:
 CvFileStorage* storage = cvOpenFileStorage("globalHistogram.xml", 0, CV_STORAGE_WRITE);
 cvWrite(storage, "histogram", global_histogram);

and read is as such:
  CvHistogram* global_histogram;
  CvFileStorage* storage = cvOpenFileStorage("globalHistogram.xml", 0, CV_STORAGE_READ);
  global_histogram = (CvHistogram *)cvReadByName(storage, 0, "histogram" ,0);

A: The Boost Serialization library is pretty nice.  It may do what you want. http://www.boost.org/doc/libs/1_49_0/libs/serialization/doc/index.html

A: 1) Decide on a file format, plan it at the byte level (If an existing format is suitable, prefer it).
2) Write out the data in the file format you decided on.

A: You can add a method to the class called Serialise, something along the lines of the following:
CvHist::Serialise( std::string fName, bool read )
{
    if ( read )
    {
        std::ifstream fStream( fName );
        // Read in values from file, eg:
        fStream >> this->param1;
        fStream >> this->param2;
        // ...etc
    }
    else
    {
        std::ofstream fStream( fName, ios::trunc ); // (ios::trunc clears file)
        // Read out values into file, eg:
        fStream << this->param1;
        fStream << this->param2;
        // ...etc
    }
}

Note, the order is important - the order that you read the various parameters from the file must match the order you write parameters to the file. Also remember to #include <fstream>
Now, to create a CvHist object populated with data from a file data.txt you can simply write this:
CvHist object;
object.Serialise( "data.txt", true );

If you've populated an object and want to store it in a file, this time, say, bob.dat, write this:
// (object has been populated with data previously)
object.Serialise( "bob.dat", false );


Q: Opendiff and online file I'd like to make a diff between to file, one is local and the other is online using for example
opendiff http://www.tex.ac.uk/ctan/web/lua2dox/Doxyfile Doxyfile

But it throw the following error :

2014-02-12 15:23:43.579 opendiff[72650:1007] /Users/Dev/Joker/http:/www.tex.ac.uk/ctan/web/lua2dox/Doxyfile does not exist

So how can I use a online file the same way as a local one ?

A: Since this is a programming Q&A site, we may as well write a program to do this for us :-)
You can create a script called (for example) odw for OpenDiffWeb which will detect whether you're trying to access web-based files and first download them to a temporary location.
Examine the following script, it's pretty rudimentary but it shows the approach that can be taken.
#!/bin/bash

# Ensure two parameters.

if [[ $# -ne 2 ]] ; then
    echo Usage: $0 '<file/url-1> <file/url-2>'
    exit 1
fi

# Download first file if web-based.

fspec1=$1
if [[ $fspec1 =~ http:// ]] ; then
    wget --output-document=/tmp/odw.$$.1 $fspec1
    fspec1=/tmp/odw.$$.1
fi

# Download second file if web-based.

fspec2=$2
if [[ $fspec2 =~ http:// ]] ; then
    wget --output-document=/tmp/odw.$$.2 $fspec2
    fspec2=/tmp/odw.$$.2
fi

# Show difference of two files.

diff $fspec1 $fspec2

# Delete them if they were web-based.

if [[ $fspec1 =~ /tmp/odw. ]] ; then
    rm -f $fspec1
fi

if [[ $fspec2 =~ /tmp/odw. ]] ; then
    rm -f $fspec2
fi

In this case, we detect a web-based file as one starting with http://. If it is, we simply use wget to bring it down to a temporary location. Both files are checked this way.
Once both files are on the local disk (either because they were brought down or because thet were already there), you can run the diff - I've used the standard diff but you can substitute your own.
Then, the temporary files are cleaned up.
As a test, I downloaded the page http://www.example.com and made a very minor change to it then compared the page to my modified local copy:
pax> odw http://www.example.com example.txt
--2014-09-25 16:40:02--  http://www.example.com/
Resolving www.example.com (www.example.com)... 93.184.216.119,
    2606:2800:220:6d:26bf:1447:1097:aa7
Connecting to www.example.com (www.example.com)|93.184.216.119|:80...
    connected.
HTTP request sent, awaiting response... 200 OK
Length: 1270 (1.2K) [text/html]
Saving to: `/tmp/odw.6569.1'

100%[=================================>] 1,270       --.-K/s   in 0s

2014-09-25 16:40:02 (165 MB/s) - `/tmp/odw.6569.1' saved [1270/1270]

4c4
<     <title>Example Domain</title>
---
>     <title>Example Domain (slightly modified)</title>

Now there's all sorts of added stuff that could go into that script, the ability to pass flags to the diff and wget programs, the ability to handle other URL types, deletion of temporary files on signals and so on.
But it should hopefully be enough to get you started.


Q: Hand-create images in javascript and draw with respect to the alpha channel? I'm currently trying to create a page with dynamically generated images, which are not shapes, drawn into a canvas to create an animation.
The first thing I tried was the following:
//create plenty of those:
var imageArray = ctx.createImageData(0,0,16,8);
//fill them with RGBA values...
//then draw them
ctx.putImageData(imageArray,x,y);

The problem is that the images are overlapping and that putImageData simply... puts the data in the context, with no respect to the alpha channel as specified in the w3c:

pixels in the canvas are replaced wholesale, with no composition, alpha blending, no shadows, etc.

So I thought, well how can I use Images and not ImageDatas?
I tried to find a way to actually put the ImageData object back into an image but it appears it can only be put in a canvas context. So, as a last resort, I tried to use the toDataURL() method of a 16x8 canvas(the size of my images) and to stick the result as src of my ~600 images.
The result was beautiful, but was eating up 100% of my CPU...(which it did not with putImageData, ~5% cpu) My guess is that for some unknown reason the  image is re-loaded from the image/png data URI each time it is drawn... but that would be plain weird... no? It also seems to take a lot more RAM than my previous technique.
So, as a result, I have no idea how to achieve my goal.
How can I dynamically create alpha-channelled images in javascript and then draw them at an appreciable speed on a canvas?
Is the only real alternative using a Java applet?
Thanks for your time.

A: Not knowing, what you really want to accomplish:
Did you have a look at the drawImage-method of the rendering-context?
Basically, it does the composition (as specified by the globalCompositeOperation-property) for you -- and it allows you to pass in a canvas element as the source.
So could probably do something along the lines of:
var offScreenContext = document.getCSSCanvasContext( "2d", "synthImage", width, height);
var pixelBuffer = offScreenContext.createImageData( tileWidth, tileHeight );
// do your image synthesis and put the updated buffer back into the context:
offScreenContext.putImageData( pixelBuffer, 0, 0, tileOriginX, tileOriginY, tileWidth, tileHeight );
// assuming 'ctx' is the context of the canvas that actually gets drawn on screen
ctx.drawImage(
  offScreenContext.canvas,                          // => the synthesized image
  tileOriginX, tileOriginY, tileWidth, tileHeight,  // => frame of offScreenContext that get's drawn
  originX, originY, tileWidth, tileHeight           // => frame of ctx to draw in
);

Assuming that you have an animation you want to loop over, this has the added benefit of only having to generate the frames once into some kind of sprite-map so that in subsequent iterations you'll only ever need to call ctx.drawImage() -- at the expense of an increased memory footprint of course...

A: Why don't you use SVG?
If you have to use canvas, maybe you could implement drawing an image on a canvas yourself?
var red = oldred*(1-alpha)+imagered*alpha

...and so on...

A: getCSSCanvasContext seems to be WebKit only, but you could also create an offscreen canvas like this:
var canvas = document.createElement('canvas')
canvas.setAttribute('width',300);//use whatever you like for width and height
canvas.setAttribute('height',200);

Which you can then draw to and draw onto another canvas with the drawImage method.


Q: implement array.prototype.reduce() on string I have some confusion regarding how reduce operation takes place on a string .First a new Str instance is created and sends desired string as a parameter.
Then using split method it  splits into an array of string.A reduceIt method takes the array and execute a reduce operation which returns the array element which has height length.
It works fine with a two element array.But if there is more than two elements it returns NAN.
Why it returns NAN for array having more than two elements??
function Str(text){
   this.text=text.split('\n');
}
Str.prototype.reduceIt = function() {
  return this.text.reduce(function(first,last,index,arr) {
          return Math.max(first.length,last.length);

  });
};

var t=new Str('i am a boy\n she loves cats\n a goat ate my flower garden ');
console.log(t.reduceIt());

A: The first time the callback is called first is a string (the first element in the array), and your function makes sense when first and last are both strings, so it works when the callback is only called once (the array has at most 2 elements).
The second time it is called it is the result of the previous call, a number. When you call first.length on a number you get undefined and when you call Math.max on that you get NaN.
If you want to find the length of the longest string in your array, you could use:
Math.max.apply(Math, this.text.map(function (str) { return str.length; }));

A: Some good answers already. :-)
The simple way to fix your problem is to supply an initial value of 0, then compare the returned value with the length of the new string, so:
Str.prototype.reduceIt = function() {
  return this.text.reduce(function(first,last,index,arr) {

          // Compare current value (first) with length of string
          return Math.max(first,last.length);

  }, 0); // supply 0 as the initial value
};

It might make things clearer to rename first to maxSoFar and last to currentString.

A:
Why it returns NAN for array having more than two elements??

Because number.length is undefined, let's name your function foo and follow how it's invoked

*

*foo(0, "i am a boy") gives NaN

*foo(NaN, " she loves cats") gives NaN

*foo(NaN, " a goat ate my flower garden ") gives NaN
Giving a final result of NaN.
This happens because number.length is undefined and Math.max(undefined, x) is NaN
It looks like you wanted to write a function which only takes the length of the second arg
function foo(a, b) {
    return Math.max(a, b.length);
}

In this case, you'll get

*

*foo(0, "i am a boy") gives 10

*foo(10, " she loves cats") gives 15

*foo(15, " a goat ate my flower garden ") gives 29
Giving a final result of 29.


Q: How to add partition in presto? In hive I can do it by:

ALTER TABLE xxx ADD PARTITION
  (datehour='yy')  LOCATION
  'zz';

How can I do it in presto?

A: Currently, Presto Hive connector does not provide means for creating new partitions at arbitrary locations. If your partition location is under table location, you can use Presto Hive connector procedures:

*

*system.create_empty_partition -- creates a new empty partition with specified values for partition keys

*system.sync_partition_metadata -- synchronizes partition list in Metastore with the partitions on the storage

If you want to create/declare partitions somewhere else than under table's location, please file an issue.


Q: Error when retrieving office 2007 files from sql server 2005 blob I have a simple document storage database that allows people to upload various types of documents and then do a full-text search on them.
It works just fine for all documents except office 2007 documents. My retrevial code uses content type "application/octet-stream", the server has the MIMETypes registered as does my computer. I can open the file just fine on my system, but uploading it and then redownloading it gives an error:
"This error can be caused by some of the following conditions:

*

*Your hard drive or floppy drive has a
corrupt section (damaged track or
sector).

*A temporary operating system
or network failure has occurred.

*Your
network is unavailable, slow, or is
corrupting data packets (failure of a
router, network card, or noise on the
network transmission line).

If the network is experiencing problems, it is usually a temporary condition and if you wait a short period of time and try again, you can usually save the file. If the problem persists, consult your network administrator"

A: It would be tough for others to have debugged this, but when I created a byteStream, I used length, instead of length - 1. For some reason in almost all documents this is no problem, but office 2007 threw a fit.