Programs & Examples On #In app purchase

In-app purchase (IAP) usually refers to the acquisition of a feature for an application from within the application itself or the buying of digital goods from within an application. Use this tag for questions about writing code for the buying process. Questions about app-store policies or about specific transactions are off-topic on Stack Overflow and should not be posted.

How do you add an in-app purchase to an iOS application?

Just translate Jojodmo code to Swift:

class InAppPurchaseManager: NSObject , SKProductsRequestDelegate, SKPaymentTransactionObserver{





//If you have more than one in-app purchase, you can define both of
//of them here. So, for example, you could define both kRemoveAdsProductIdentifier
//and kBuyCurrencyProductIdentifier with their respective product ids
//
//for this example, we will only use one product

let kRemoveAdsProductIdentifier = "put your product id (the one that we just made in iTunesConnect) in here"

@IBAction func tapsRemoveAds() {

    NSLog("User requests to remove ads")

    if SKPaymentQueue.canMakePayments() {
        NSLog("User can make payments")

        //If you have more than one in-app purchase, and would like
        //to have the user purchase a different product, simply define
        //another function and replace kRemoveAdsProductIdentifier with
        //the identifier for the other product
        let set : Set<String> = [kRemoveAdsProductIdentifier]
        let productsRequest = SKProductsRequest(productIdentifiers: set)
        productsRequest.delegate = self
        productsRequest.start()

    }
    else {
        NSLog("User cannot make payments due to parental controls")
        //this is called the user cannot make payments, most likely due to parental controls
    }
}


func purchase(product : SKProduct) {

    let payment = SKPayment(product: product)
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
    SKPaymentQueue.defaultQueue().addPayment(payment)
}

func restore() {
    //this is called when the user restores purchases, you should hook this up to a button
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
    SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}


func doRemoveAds() {
    //TODO: implement
}

/////////////////////////////////////////////////
//////////////// store delegate /////////////////
/////////////////////////////////////////////////
// MARK: - store delegate -


func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {

    if let validProduct = response.products.first {
        NSLog("Products Available!")
        self.purchase(validProduct)
    }
    else {
        NSLog("No products available")
        //this is called if your product id is not valid, this shouldn't be called unless that happens.
    }
}

func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {


    NSLog("received restored transactions: \(queue.transactions.count)")
    for transaction in queue.transactions {
        if transaction.transactionState == .Restored {
            //called when the user successfully restores a purchase
            NSLog("Transaction state -> Restored")

            //if you have more than one in-app purchase product,
            //you restore the correct product for the identifier.
            //For example, you could use
            //if(productID == kRemoveAdsProductIdentifier)
            //to get the product identifier for the
            //restored purchases, you can use
            //
            //NSString *productID = transaction.payment.productIdentifier;
            self.doRemoveAds()
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
            break;
        }
    }
}


func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {

    for transaction in transactions {
        switch transaction.transactionState {
        case .Purchasing: NSLog("Transaction state -> Purchasing")
            //called when the user is in the process of purchasing, do not add any of your own code here.
        case .Purchased:
            //this is called when the user has successfully purchased the package (Cha-Ching!)
            self.doRemoveAds() //you can add your code for what you want to happen when the user buys the purchase here, for this tutorial we use removing ads
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
            NSLog("Transaction state -> Purchased")
        case .Restored:
            NSLog("Transaction state -> Restored")
            //add the same code as you did from SKPaymentTransactionStatePurchased here
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
        case .Failed:
            //called when the transaction does not finish
            if transaction.error?.code == SKErrorPaymentCancelled {
                NSLog("Transaction state -> Cancelled")
                //the user cancelled the payment ;(
            }
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
        case .Deferred:
            // The transaction is in the queue, but its final status is pending external action.
            NSLog("Transaction state -> Deferred")

        }


    }
}
} 

What does "restore purchases" in In-App purchases mean?

You typically restore purchases with this code:

[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];

It will reinvoke -paymentQueue:updatedTransactions on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.

Not all types of In-App purchases can be restored.

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

I've been having this problem too and I'm not sure why. Some people suggest removing your Google account and re-adding it and/or deleting the Play Store cache. I'm looking for more solutions, but it happens for all apps free, paid, whatever.

EDIT: just found this http://www.droid-life.com/2012/11/14/after-4-2-update-is-your-nexus-7-having-troubles-updating-apps-in-google-play/

Why does background-color have no effect on this DIV?

Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.

Convert a List<T> into an ObservableCollection<T>

The Observable Collection constructor will take an IList or an IEnumerable.

If you find that you are going to do this a lot you can make a simple extension method:

    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable)
    {
        return new ObservableCollection<T>(enumerable);
    }

Getting View's coordinates relative to the root layout

The Android API already provides a method to achieve that. Try this:

Rect offsetViewBounds = new Rect();
//returns the visible bounds
childView.getDrawingRect(offsetViewBounds);
// calculates the relative coordinates to the parent
parentViewGroup.offsetDescendantRectToMyCoords(childView, offsetViewBounds); 

int relativeTop = offsetViewBounds.top;
int relativeLeft = offsetViewBounds.left;

Here is the doc

Remove last character from C++ string

For a non-mutating version:

st = myString.substr(0, myString.size()-1);

What is thread Safe in java?

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.

What is the difference between linear regression and logistic regression?

In short: Linear Regression gives continuous output. i.e. any value between a range of values. Logistic Regression gives discrete output. i.e. Yes/No, 0/1 kind of outputs.

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

If anyone is still experiencing this issue, I found that it related to a difference in Oracle Client versions.

I have posted my full experience and solution here: https://stackoverflow.com/a/43806765/923177

Getting the name / key of a JToken with JSON.net

JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>(); 

foreach (JToken attribute in attributes)
{   
    JProperty jProperty = attribute.ToObject<JProperty>();
    string propertyName = jProperty.Name;
}

is it possible to update UIButton title/text programmatically?

Make sure you're on the main thread.

If not, it will still save the button text. It will be there when you inspect the object in the debugger. But it won't actually update the view.

How can I specify the schema to run an sql file against in the Postgresql command line

The PGOPTIONS environment variable may be used to achieve this in a flexible way.

In an Unix shell:

PGOPTIONS="--search_path=my_schema_01" psql -d myDataBase -a -f myInsertFile.sql

If there are several invocations in the script or sub-shells that need the same options, it's simpler to set PGOPTIONS only once and export it.

PGOPTIONS="--search_path=my_schema_01"
export PGOPTIONS

psql -d somebase
psql -d someotherbase
...

or invoke the top-level shell script with PGOPTIONS set from the outside

PGOPTIONS="--search_path=my_schema_01"  ./my-upgrade-script.sh

In Windows CMD environment, set PGOPTIONS=value should work the same.

Mac install and open mysql using terminal

open terminal and type

sudo sh -c 'echo /usr/local/mysql/bin > /etc/paths.d/mysql'

then close terminal and open a new terminal and type

mysql -u root -p

hit enter, and it will ask you for password

I have found this solution on https://teamtreehouse.com/community/says-mysql-command-not-found

now to set new password type

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

Amazon Linux: apt-get: command not found

I faced the same issue regarding apt-get: command not found here are the steps how I resolved it on ubuntu xenial

  • Search the appropriate version of apt from here (apt_1.4_amd64.deb for ubuntu xenial)

  • Download the apt.deb

    wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.4_amd64.deb

  • Install the apt.deb package

    sudo dpkg -i apt_1.4_amd64.deb

Now we can easily run

sudo apt-get install htop

Is there an exponent operator in C#?

For what it's worth I do miss the ^ operator when raising a power of 2 to define a binary constant. Can't use Math.Pow() there, but shifting an unsigned int of 1 to the left by the exponent's value works. When I needed to define a constant of (2^24)-1:

public static int Phase_count = 24;
public static uint PatternDecimal_Max = ((uint)1 << Phase_count) - 1;

Remember the types must be (uint) << (int).

Generate table relationship diagram from existing schema (SQL Server)

For SQL statements you can try reverse snowflakes. You can join at sourceforge or the demo site at http://snowflakejoins.com/.

Difference between socket and websocket?

You'd have to use WebSockets (or some similar protocol module e.g. as supported by the Flash plugin) because a normal browser application simply can't open a pure TCP socket.

The Socket.IO module available for node.js can help a lot, but note that it is not a pure WebSocket module in its own right.

It's actually a more generic communications module that can run on top of various other network protocols, including WebSockets, and Flash sockets.

Hence if you want to use Socket.IO on the server end you must also use their client code and objects. You can't easily make raw WebSocket connections to a socket.io server as you'd have to emulate their message protocol.

Right way to split an std::string into a vector<string>

For space separated strings, then you can do this:

std::string s = "What is the right way to split a string into a vector of strings";
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

Output:

What
is
the
right
way
to
split
a
string
into
a
vector
of
strings

string that have both comma and space

struct tokens: std::ctype<char> 
{
    tokens(): std::ctype<char>(get_table()) {}
 
    static std::ctype_base::mask const* get_table()
    {
        typedef std::ctype<char> cctype;
        static const cctype::mask *const_rc= cctype::classic_table();
 
        static cctype::mask rc[cctype::table_size];
        std::memcpy(rc, const_rc, cctype::table_size * sizeof(cctype::mask));
 
        rc[','] = std::ctype_base::space; 
        rc[' '] = std::ctype_base::space; 
        return &rc[0];
    }
};
 
std::string s = "right way, wrong way, correct way";
std::stringstream ss(s);
ss.imbue(std::locale(std::locale(), new tokens()));
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

Output:

right
way
wrong
way
correct
way

Sockets: Discover port availability using Java

This is the implementation coming from the Apache camel project:

/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 */
public static boolean available(int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

    return false;
}

They are checking the DatagramSocket as well to check if the port is avaliable in UDP and TCP.

Hope this helps.

Why do we need to install gulp globally and locally?

I'm not sure if our problem was directly related with installing gulp only locally. But we had to install a bunch of dependencies ourself. This lead to a "huge" package.json and we are not sure if it is really a great idea to install gulp only locally. We had to do so because of our build environment. But I wouldn't recommend installing gulp not globally if it isn't absolutely necessary. We faced similar problems as described in the following blog-post

None of these problems arise for any of our developers on their local machines because they all installed gulp globally. On the build system we had the described problems. If someone is interested I could dive deeper into this issue. But right now I just wanted to mention that it isn't an easy path to install gulp only locally.

"The public type <<classname>> must be defined in its own file" error in Eclipse

Save this class in the file StaticDemo.java. Also you cant have more than one public classes in one file.

Bootstrap 3 Navbar Collapse

The big difference between Bootstrap 2 and Bootstrap 3 is that Bootstrap 3 is "mobile first".

That means the default styles are designed for mobile devices and in the case of Navbars, that means it's "collapsed" by default and "expands" when it reaches a certain minimum size.

Bootstrap 3's site actually has a "hint" as to what to do: http://getbootstrap.com/components/#navbar

Customize the collapsing point

Depending on the content in your navbar, you might need to change the point at which your navbar switches between collapsed and horizontal mode. Customize the @grid-float-breakpoint variable or add your own media query.

If you're going to re-compile your LESS, you'll find the noted LESS variable in the variables.less file. It's currently set to "expand" @media (min-width: 768px) which is a "small screen" (ie. a tablet) by Bootstrap 3 terms.

@grid-float-breakpoint: @screen-tablet;

If you want to keep the collapsed a little longer you can adjust it like such:

@grid-float-breakpoint: @screen-desktop; (992px break-point)

or expand sooner

@grid-float-breakpoint: @screen-phone (480px break-point)

If you want to have it expand later, and not deal with re-compiling the LESS, you'll have to overwrite the styles that get applied at the 768px media query and have them return to the previous value. Then re-add them at the appropriate time.

I'm not sure if there's a better way to do it. Recompiling the Bootstrap LESS to your needs is the best (easiest) way. Otherwise, you'll have to find all the CSS media queries that affect your Navbar, overwrite them to default styles @ the 768px width and then revert them back at a higher min-width.

Recompiling the LESS will do all that magic for you just by changing the variable. Which is pretty much the point of LESS/SASS pre-compilers. =)

(note, I did look them all up, it's about 100 lines of code, which is annoy enough for me to drop the idea and just re-compile Bootstrap for a given project and avoid messing something up by accident)

I hope that helps!

Cheers!

What causes signal 'SIGILL'?

Make sure that all functions with non-void return type have a return statement.

While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.

PYODBC--Data source name not found and no default driver specified

I'm using

Django 2.2

and got the same error while connecting to sql-server 2012. Spent lot of time to solve this issue and finally this worked.

I changed

'driver': 'ODBC Driver 13 for SQL Server'

to

'driver': 'SQL Server Native Client 11.0'

and it worked.

Indexes of all occurrences of character in a string

This can be done in a functional way with Java 9 using regular expression:

Pattern.compile(Pattern.quote(guess)) // sanitize input and create pattern
            .matcher(word) // create matcher
            .results()     // get the MatchResults, Java 9 method
            .map(MatchResult::start) // get the first index
            .collect(Collectors.toList()) // collect found indices into a list
    );

Here's the Kotlin Solution to add this logic as a new a new methods into CharSequence API using extension method:

 // Extension method
fun CharSequence.indicesOf(input: String): List<Int> =
    Regex(Pattern.quote(input)) // build regex
        .findAll(this)          // get the matches
        .map { it.range.first } // get the index
        .toCollection(mutableListOf()) // collect the result as list

// call the methods as
"Banana".indicesOf("a") // [1, 3, 5]

Fixed width buttons with Bootstrap

Just came upon the same need and was not satified with defining fixed width.

So did it with jquery:

_x000D_
_x000D_
    var max = Math.max ($("#share_cancel").width (), $("#share_commit").width ());_x000D_
    $("#share_cancel").width (max);_x000D_
    $("#share_commit").width (max); 
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
    <button type="button" class="btn btn-secondary" id="share_cancel">SHORT</button>_x000D_
    <button type="button" class="btn btn-success" id="share_commit">LOOOOOOOOONG</button>
_x000D_
_x000D_
_x000D_

How to get the <html> tag HTML with JavaScript / jQuery?

This is how to get the html DOM element purely with JS:

var htmlElement = document.getElementsByTagName("html")[0];

or

var htmlElement = document.querySelector("html");

And if you want to use jQuery to get attributes from it...

$(htmlElement).attr(INSERT-ATTRIBUTE-NAME);

Java, How to get number of messages in a topic in apache kafka

To get all the messages stored for the topic you can seek the consumer to the beginning and end of the stream for each partition and sum the results

List<TopicPartition> partitions = consumer.partitionsFor(topic).stream()
        .map(p -> new TopicPartition(topic, p.partition()))
        .collect(Collectors.toList());
    consumer.assign(partitions); 
    consumer.seekToEnd(Collections.emptySet());
Map<TopicPartition, Long> endPartitions = partitions.stream()
        .collect(Collectors.toMap(Function.identity(), consumer::position));
    consumer.seekToBeginning(Collections.emptySet());
System.out.println(partitions.stream().mapToLong(p -> endPartitions.get(p) - consumer.position(p)).sum());

Could not obtain information about Windows NT group user

Just solved this problem. In my case it was domain controller is not accessible, because both dns servers was google dns.

I just add to checklist for this problem:

  • check domain controller is accessible

How to get the fields in an Object via reflection?

Here's a quick and dirty method that does what you want in a generic way. You'll need to add exception handling and you'll probably want to cache the BeanInfo types in a weakhashmap.

public Map<String, Object> getNonNullProperties(final Object thingy) {
    final Map<String, Object> nonNullProperties = new TreeMap<String, Object>();
    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(thingy
                .getClass());
        for (final PropertyDescriptor descriptor : beanInfo
                .getPropertyDescriptors()) {
            try {
                final Object propertyValue = descriptor.getReadMethod()
                        .invoke(thingy);
                if (propertyValue != null) {
                    nonNullProperties.put(descriptor.getName(),
                            propertyValue);
                }
            } catch (final IllegalArgumentException e) {
                // handle this please
            } catch (final IllegalAccessException e) {
                // and this also
            } catch (final InvocationTargetException e) {
                // and this, too
            }
        }
    } catch (final IntrospectionException e) {
        // do something sensible here
    }
    return nonNullProperties;
}

See these references:

How do I integrate Ajax with Django applications?

I have tried to use AjaxableResponseMixin in my project, but had ended up with the following error message:

ImproperlyConfigured: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.

That is because the CreateView will return a redirect response instead of returning a HttpResponse when you to send JSON request to the browser. So I have made some changes to the AjaxableResponseMixin. If the request is an ajax request, it will not call the super.form_valid method, just call the form.save() directly.

from django.http import JsonResponse
from django import forms
from django.db import models

class AjaxableResponseMixin(object):
    success_return_code = 1
    error_return_code = 0
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            form.errors.update({'result': self.error_return_code})
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        if self.request.is_ajax():
            self.object = form.save()
            data = {
                'result': self.success_return_code
            }
            return JsonResponse(data)
        else:
            response = super(AjaxableResponseMixin, self).form_valid(form)
            return response

class Product(models.Model):
    name = models.CharField('product name', max_length=255)

class ProductAddForm(forms.ModelForm):
    '''
    Product add form
    '''
    class Meta:
        model = Product
        exclude = ['id']


class PriceUnitAddView(AjaxableResponseMixin, CreateView):
    '''
    Product add view
    '''
    model = Product
    form_class = ProductAddForm

How do I download a file from the internet to my linux server with Bash

Using wget

wget -O /tmp/myfile 'http://www.google.com/logo.jpg'

or curl:

curl -o /tmp/myfile 'http://www.google.com/logo.jpg'

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.

Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.

Try something like this:

var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

EOFError: EOF when reading a line

convert your inputs to ints:

width = int(input())
height = int(input())

How to write a cursor inside a stored procedure in SQL Server 2008

What's wrong with just simply using a single, simple UPDATE statement??

UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)

That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.

how to generate a unique token which expires after 24 hours?

There are two possible approaches; either you create a unique value and store somewhere along with the creation time, for example in a database, or you put the creation time inside the token so that you can decode it later and see when it was created.

To create a unique token:

string token = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

Basic example of creating a unique token containing a time stamp:

byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());

To decode the token to get the creation time:

byte[] data = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
if (when < DateTime.UtcNow.AddHours(-24)) {
  // too old
}

Note: If you need the token with the time stamp to be secure, you need to encrypt it. Otherwise a user could figure out what it contains and create a false token.

Open multiple Eclipse workspaces on the Mac

Based on a previous answer that helped me, but different directory:

cd /Applications/Eclipse.app/Contents/MacOS
./eclipse &

Thanks

Why does visual studio 2012 not find my tests?

This one just bit me. I added a test to my project, but could not get it to show up in Test Explorer. My old tests all showed up. Finally, I realized I was only viewing a specific playlist, and I had not added the new test to the playlist. If you are using playlists, select "All Tests" and see if VS finds your tests and displays them in Test Explorer. Then you can add them to the desired playlist, too.

Show just the current branch in Git

$ git rev-parse --abbrev-ref HEAD
master

This should work with Git 1.6.3 or newer.

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

The particular case of RubyGems (the command line tool) is that it requires to bundle inside of its code the trust certificates, which allow RubyGems to establish a connection with the servers even when base operating system is unable to verify the identity of them.

Up until a few months ago, this certificate was provided by one CA, but newer certificate is provided by a different one.

Because of this, existing installations of RubyGems would have to been updated before the switch of the certificate and give enough time for the change to spread (and people to update)

Anyone can find his solution by following the simple steps given in the link below

https://gist.github.com/luislavena/f064211759ee0f806c88

Firebase (FCM) how to get token

The team behind Firebase Android SDK change API a little bit. I've implemented "Token to Server" logic like this:

In my instance of FirebaseMessagingService:

public class FirebaseCloudMessagingService extends FirebaseMessagingService {

    ...

    @Override
    public void onNewToken(String token) {
        // sending token to server here
    }

    ...

}

Keep in mind that token is per device, and it can be updated by Firebase regardless of your login logic. So, if you have Login and Logout functionality, you have to consider extra cases:

  1. When a new user logs in, you need to bind token to the new user (send it to the server). Because token might be updated during the session of old user and server doesn't know token of the new user.
  2. When the user logs out, you need to unbind token. Because user should not receive notifications/messages anymore.

Using new API, you can get token like this:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            String token = instanceIdResult.getToken();
            // send it to server
        }
    });

Good luck!

Character reading from file in Python

Leaving aside the fact that your text file is broken (U+2018 is a left quotation mark, not an apostrophe): iconv can be used to transliterate unicode characters to ascii.

You'll have to google for "iconvcodec", since the module seems not to be supported anymore and I can't find a canonical home page for it.

>>> import iconvcodec
>>> from locale import setlocale, LC_ALL
>>> setlocale(LC_ALL, '')
>>> u'\u2018'.encode('ascii//translit')
"'"

Alternatively you can use the iconv command line utility to clean up your file:

$ xxd foo
0000000: e280 980a                                ....
$ iconv -t 'ascii//translit' foo | xxd
0000000: 270a                                     '.

Java unsupported major minor version 52.0

You have to compile with Java 1.7. But if you have *.jsp files, you should also completely remove Java 1.8 from the system. If you use Mac, here is how you can do it.

Copy Image from Remote Server Over HTTP

For those who need to preserve the original filename and extension

$origin = 'http://example.com/image.jpg';

$filename = pathinfo($origin, PATHINFO_FILENAME);
$ext = pathinfo($origin, PATHINFO_EXTENSION);

$dest = 'myfolder/' . $filename . '.' . $ext;

copy($origin, $dest);

Postgresql: error "must be owner of relation" when changing a owner object

Thanks to Mike's comment, I've re-read the doc and I've realised that my current user (i.e. userA that already has the create privilege) wasn't a direct/indirect member of the new owning role...

So the solution was quite simple - I've just done this grant:

grant userB to userA;

That's all folks ;-)


Update:

Another requirement is that the object has to be owned by user userA before altering it...

Android: How to open a specific folder via Intent and show its content in a file browser?

Intent chooser = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getDownloadCacheDirectory().getPath().toString());
chooser.addCategory(Intent.CATEGORY_OPENABLE);
chooser.setDataAndType(uri, "*/*");
// startActivity(chooser);
try {
startActivityForResult(chooser, SELECT_FILE);
}
catch (android.content.ActivityNotFoundException ex)
{
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}

In code above, if setDataAndType is "*/*" a builtin file browser is opened to pick any file, if I set "text/plain" Dropbox is opened. I have Dropbox, Google Drive installed. If I uninstall Dropbox only "*/*" works to open file browser. This is Android 4.4.2. I can download contents from Dropbox and for Google Drive, by getContentResolver().openInputStream(data.getData()).

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

matching query does not exist Error in Django

In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:

user = UniversityDetails.objects.get(email=email)

is email a str, or a None? or an int?

Jinja2 template variable if None Object set a default value

According to docs you can just do:

{{ p|default('', true) }}

Cause None casts to False in boolean context.


Update: As lindes mentioned, it works only for simple data types.

Use CASE statement to check if column exists in table - SQL Server

select case
         when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
         then 0
         else 1
       end

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

Install tether via npm like below

npm install tether --save-dev

then add tether to your html above bootstrap like below

<script src="node_modules/tether/dist/js/tether.min.js"></script>
<script src="jspm_packages/github/twbs/[email protected]/js/bootstrap.js"></script>

Font size relative to the user's screen resolution?

<script>
function getFontsByScreenWidth(actuallFontSize, maxScreenWidth){
     return (actualFontSize / maxScreenWidth) * window.innerWidth;
}

// Example:
fontSize = 18;
maxScreenWidth = 1080;
fontSize = getFontsByScreenWidth(fontSize, maxScreenWidth)

</script>

I hope this will help. I am using this formula for my Phase game.

DateTime group by date and hour

In my case... with MySQL:

SELECT ... GROUP BY TIMESTAMPADD(HOUR, HOUR(columName), DATE(columName))

Django CharField vs TextField

In some cases it is tied to how the field is used. In some DB engines the field differences determine how (and if) you search for text in the field. CharFields are typically used for things that are searchable, like if you want to search for "one" in the string "one plus two". Since the strings are shorter they are less time consuming for the engine to search through. TextFields are typically not meant to be searched through (like maybe the body of a blog) but are meant to hold large chunks of text. Now most of this depends on the DB Engine and like in Postgres it does not matter.

Even if it does not matter, if you use ModelForms you get a different type of editing field in the form. The ModelForm will generate an HTML form the size of one line of text for a CharField and multiline for a TextField.

Getting input values from text box

you have multiple elements with the same id. That is a big no-no. Make sure your inputs have unique ids.

<td id="pass"><label>Password</label></td>
<tr>
   <td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>

see, both the td and the input share the id value pass.

How do you iterate through every file/directory recursively in standard C++?

File tree walk ftw is a recursive way to wall the whole directory tree in the path. More details are here.

NOTE : You can also use fts that can skip hidden files like . or .. or .bashrc

#include <ftw.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>

 
int list(const char *name, const struct stat *status, int type)
{
     if (type == FTW_NS)
     {
         return 0;
     }

     if (type == FTW_F)
     {
         printf("0%3o\t%s\n", status->st_mode&0777, name);
     }

     if (type == FTW_D && strcmp(".", name) != 0)
     {
         printf("0%3o\t%s/\n", status->st_mode&0777, name);
     }
     return 0;
}

int main(int argc, char *argv[])
{
     if(argc == 1)
     {
         ftw(".", list, 1);
     }
     else
     {
         ftw(argv[1], list, 1);
     }

     return 0;
}

output looks like following:

0755    ./Shivaji/
0644    ./Shivaji/20200516_204454.png
0644    ./Shivaji/20200527_160408.png
0644    ./Shivaji/20200527_160352.png
0644    ./Shivaji/20200520_174754.png
0644    ./Shivaji/20200520_180103.png
0755    ./Saif/
0644    ./Saif/Snapchat-1751229005.jpg
0644    ./Saif/Snapchat-1356123194.jpg
0644    ./Saif/Snapchat-613911286.jpg
0644    ./Saif/Snapchat-107742096.jpg
0755    ./Milind/
0644    ./Milind/IMG_1828.JPG
0644    ./Milind/IMG_1839.JPG
0644    ./Milind/IMG_1825.JPG
0644    ./Milind/IMG_1831.JPG
0644    ./Milind/IMG_1840.JPG

Let us say if you want to match a filename (example: searching for all the *.jpg, *.jpeg, *.png files.) for a specific needs, use fnmatch.

 #include <ftw.h>
 #include <stdio.h>
 #include <sys/stat.h>
 #include <iostream>
 #include <fnmatch.h>

 static const char *filters[] = {
     "*.jpg", "*.jpeg", "*.png"
 };

 int list(const char *name, const struct stat *status, int type)
 {
     if (type == FTW_NS)
     {
         return 0;
     }

     if (type == FTW_F)
     {
         int i;
         for (i = 0; i < sizeof(filters) / sizeof(filters[0]); i++) {
             /* if the filename matches the filter, */
             if (fnmatch(filters[i], name, FNM_CASEFOLD) == 0) {
                 printf("0%3o\t%s\n", status->st_mode&0777, name);
                 break;
             }
         }
     }

     if (type == FTW_D && strcmp(".", name) != 0)
     {
         //printf("0%3o\t%s/\n", status->st_mode&0777, name);
     }
     return 0;
 }

 int main(int argc, char *argv[])
 {
     if(argc == 1)
     {
         ftw(".", list, 1);
     }
     else
     {
         ftw(argv[1], list, 1);
     }

     return 0;
 }

"Unable to acquire application service" error while launching Eclipse

delete processcenter.ini at location similar to: C:\IBM\IntegrationDesigner\v8.5\iid and then once IDE comes up, go to windows preference and put in the correct URL.

Multipart File upload Spring Boot

@RequestMapping(value="/add/image", method=RequestMethod.POST)
public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
{   
    try {
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
        Iterator<String> it=multipartRequest.getFileNames();
        MultipartFile multipart=multipartRequest.getFile(it.next());
        String fileName=id+".png";
        String imageName = fileName;

        byte[] bytes=multipart.getBytes();
        BufferedOutputStream stream= new BufferedOutputStream(new FileOutputStream("src/main/resources/static/image/book/"+fileName));;

        stream.write(bytes);
        stream.close();
        return new ResponseEntity("upload success", HttpStatus.OK);

    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity("Upload fialed", HttpStatus.BAD_REQUEST);
    }   
}

How do you do natural logs (e.g. "ln()") with numpy in Python?

I usually do like this:

from numpy import log as ln

Perhaps this can make you more comfortable.

Remove all files in a directory

To Removing all the files in folder.

import os
import glob

files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
    os.remove(file)

Get JavaScript object from array of objects by value of property

var jsObjects = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}];

to access the third object, use: jsObjects[2];
to access the third object b value, use: jsObjects[2].b;

How to output only captured groups with sed?

Give up and use Perl

Since sed does not cut it, let's just throw the towel and use Perl, at least it is LSB while grep GNU extensions are not :-)

  • Print the entire matching part, no matching groups or lookbehind needed:

    cat <<EOS | perl -lane 'print m/\d+/g'
    a1 b2
    a34 b56
    EOS
    

    Output:

    12
    3456
    
  • Single match per line, often structured data fields:

    cat <<EOS | perl -lape 's/.*?a(\d+).*/$1/g'
    a1 b2
    a34 b56
    EOS
    

    Output:

    1
    34
    

    With lookbehind:

    cat <<EOS | perl -lane 'print m/(?<=a)(\d+)/'
    a1 b2
    a34 b56
    EOS
    
  • Multiple fields:

    cat <<EOS | perl -lape 's/.*?a(\d+).*?b(\d+).*/$1 $2/g'
    a1 c0 b2 c0
    a34 c0 b56 c0
    EOS
    

    Output:

    1 2
    34 56
    
  • Multiple matches per line, often unstructured data:

    cat <<EOS | perl -lape 's/.*?a(\d+)|.*/$1 /g'
    a1 b2
    a34 b56 a78 b90
    EOS
    

    Output:

    1 
    34 78
    

    With lookbehind:

    cat EOS<< | perl -lane 'print m/(?<=a)(\d+)/g'
    a1 b2
    a34 b56 a78 b90
    EOS
    

    Output:

    1
    3478
    

Read whole ASCII file into C++ std::string

You may not find this in any book or site but I found out that it works pretty well:

ifstream ifs ("filename.txt");
string s;
getline (ifs, s, (char) ifs.eof());

How to reset all checkboxes using jQuery or pure JS?

The above answer did not work for me -

The following worked

$('input[type=checkbox]').each(function() 
{ 
        this.checked = false; 
}); 

This makes sure all the checkboxes are unchecked.

How to maintain page scroll position after a jquery event is carried out?

What you want to do is prevent the default action of the click event. To do this, you will need to modify your script like this:

$(document).ready(function() {
  $('.galleryicon').live("click", function(e) {

    $('#mainImage').hide();
    $('#cakebox').css('background-image', "url('ajax-loader.gif')");
    var i = $('<img />').attr('src',this.href).load(function() {
        $('#mainImage').attr('src', i.attr('src'));
        $('#cakebox').css('background-image', 'none');
        $('#mainImage').fadeIn();
    });
    return false; 
    e.preventDefault();
   });
 });

So, you're adding an "e" that represents the event in the line $('.galleryicon').live("click", function(e) { and you're adding the line e.preventDefault();

Dynamically add data to a javascript map

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

How to detect Adblock on my website?

This is what worked for me:

function isAdBlocked() {
     return (typeof(window.google_jobrunner) === "undefined") ? true : false;
}

$(document).ready(function(){
    if(isAdBlocked()) {
       alert('Y U NO LIKE ADS?');
    }
});

How can I view an old version of a file with Git?

Doing this by date looks like this if the commit happened within the last 90 days:

git show HEAD@{2013-02-25}:./fileInCurrentDirectory.txt

Note that HEAD@{2013-02-25} means "where HEAD was on 2013-02-25" in this repository (using the reflog), not "the last commit before 2013-02-25 in this branch in history".

This is important! It means that, by default, this method only works for history within the last 90 days. Otherwise, you need to do this:

git show $(git rev-list -1 --before="2013-02-26" HEAD):./fileInCurrentDirectory.txt

Array vs. Object efficiency in JavaScript

It's not really a performance question at all, since arrays and objects work very differently (or are supposed to, at least). Arrays have a continuous index 0..n, while objects map arbitrary keys to arbitrary values. If you want to supply specific keys, the only choice is an object. If you don't care about the keys, an array it is.

If you try to set arbitrary (numeric) keys on an array, you really have a performance loss, since behaviourally the array will fill in all indexes in-between:

> foo = [];
  []
> foo[100] = 'a';
  "a"
> foo
  [undefined, undefined, undefined, ..., "a"]

(Note that the array does not actually contain 99 undefined values, but it will behave this way since you're [supposed to be] iterating the array at some point.)

The literals for both options should make it very clear how they can be used:

var arr = ['foo', 'bar', 'baz'];     // no keys, not even the option for it
var obj = { foo : 'bar', baz : 42 }; // associative by its very nature

How to select all instances of a variable and edit variable name in Sublime

  1. Put the cursor in the variable.

    Note: the key is to start with an empty selection. Don't highlight; just put your cursor there.

text cursor on variable

  1. Press ?D as needed. Not on a Mac? Use CtrlD.

more instances of variable highlighted

Didn't work? Try again, making sure to start with nothing selected.

More commands:

Find All: Ctrl?G selects all occurences at once. Not on a Mac? AltF3

Undo Selection: ?U steps backwards. Not on a Mac? CtrlU

Quick Skip Next: ?K?D skips the next occurence. Not on a Mac? CtrlKCtrlD

Sublime Docs

MySQL "WITH" clause

Have you ever tried Temporary Table? This solved my convern:

create temporary table abc (
column1 varchar(255)
column2 decimal
);
insert into abc
select ...
or otherwise
insert into abc
values ('text', 5.5), ('text2', 0815.8);

Then you can use this table in every select in this session:

select * from abc inner join users on ...;

Convert blob to base64

 var reader = new FileReader();
 reader.readAsDataURL(blob); 
 reader.onloadend = function() {
     var base64data = reader.result;                
     console.log(base64data);
 }

Form the docs readAsDataURL encodes to base64

Classes vs. Modules in VB.NET

Modules are VB counterparts to C# static classes. When your class is designed solely for helper functions and extension methods and you don't want to allow inheritance and instantiation, you use a Module.

By the way, using Module is not really subjective and it's not deprecated. Indeed you must use a Module when it's appropriate. .NET Framework itself does it many times (System.Linq.Enumerable, for instance). To declare an extension method, it's required to use Modules.

How to create and use resources in .NET

Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.

How to create a resource:

In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.

  • Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.
  • Click the "Resources" tab.
  • The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.
  • Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.
  • At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.

How to use a resource:

Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.

There is a static class called Properties.Resources that gives you access to all your resources, so my code ended up being as simple as:

paused = !paused;
if (paused)
    notifyIcon.Icon = Properties.Resources.RedIcon;
else
    notifyIcon.Icon = Properties.Resources.GreenIcon;

Done! Finished! Everything is simple when you know how, isn't it?

How to hide scrollbar in Firefox?

For webkit use following:

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}

For Mozilla Firefox use following code:

@-moz-document url-prefix() {
    html,body{overflow: hidden !important;}
}

and if scrolling does not work then add

element {overflow-y: scroll;}

to specific element

LINQ-to-SQL vs stored procedures?

Create PROCEDURE userInfoProcedure
    -- Add the parameters for the stored procedure here
    @FirstName varchar,
    @LastName varchar
AS
BEGIN

    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT FirstName  , LastName,Age from UserInfo where FirstName=@FirstName
    and LastName=@FirstName
END
GO

http://www.totaldotnet.com/Article/ShowArticle121_StoreProcBasic.aspx

Correct mime type for .mp4

According to RFC 4337 § 2, video/mp4 is indeed the correct Content-Type for MPEG-4 video.

Generally, you can find official MIME definitions by searching for the file extension and "IETF" or "RFC". The RFC (Request for Comments) articles published by the IETF (Internet Engineering Taskforce) define many Internet standards, including MIME types.

When is layoutSubviews called?

A rather obscure, yet potentially important case when layoutSubviews never gets called is:

import UIKit

class View: UIView {

    override class var layerClass: AnyClass { return Layer.self }

    class Layer: CALayer {
        override func layoutSublayers() {
            // if we don't call super.layoutSublayers()...
            print(type(of: self), #function)
        }
    }

    override func layoutSubviews() {
        // ... this method never gets called by the OS!
        print(type(of: self), #function)
    }
}

let view = View(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

size_t is 64 bit normally on 64 bit machine

Different class for the last element in ng-repeat

You can use $last variable within ng-repeat directive. Take a look at doc.

You can do it like this:

 <div ng-repeat="file in files" ng-class="computeCssClass($last)">
 {{file.name}}
 </div>

Where computeCssClass is function of controller which takes sole argument and returns 'last' or null.

Or

  <div ng-repeat="file in files" ng-class="{'last':$last}">
  {{file.name}}
  </div>

How to store Query Result in variable using mysql

Additionally, if you want to set multiple variables at once by one query, you can use the other syntax for setting variables which goes like this: SELECT @varname:=value.

A practical example:

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...

What does the 'u' symbol mean in front of string values?

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False

How to make circular background using css?

Here is a solution for doing it with a single div element with CSS properties, border-radius does the magic.

CSS:

.circle{
    width:100px;
    height:100px;
    border-radius:50px;
    font-size:20px;
    color:#fff;
    line-height:100px;
    text-align:center;
    background:#000
}

HTML:

<div class="circle">Hello</div>

Get battery level and state in Android

Since SDK 21 LOLLIPOP it is possible to use the following to get current battery level as a percentage:

BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

Read BatteryManager  |  Android Developers - BATTERY_PROPERTY_CAPACITY

How can I read input from the console using the Scanner class in Java?

A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in. It's really quite simple.

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

To retrieve a username I would probably use sc.nextLine().

System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);

You could also use next(String pattern) if you want more control over the input, or just validate the username variable.

You'll find more information on their implementation in the API Documentation for java.util.Scanner

JavaScript: Global variables after Ajax requests

The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after the request completes, like you are expecting.

What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,

var it_works = false;

$.ajax({
  url: 'some_file.php',
  async: false,  # makes request synchronous
  success: function() {
    it_works = true;
  }
});

alert(it_works);

Permission denied at hdfs

You are experiencing two separate problems here:


hduser@ubuntu:/usr/local/hadoop$ hadoop fs -put /usr/local/input-data/ /input put: /usr/local/input-data (Permission denied)

Here, the user hduser does not have access to the local directory /usr/local/input-data. That is, your local permissions are too restrictive. You should change it.


hduser@ubuntu:/usr/local/hadoop$ sudo bin/hadoop fs -put /usr/local/input-data/ /inwe put: org.apache.hadoop.security.AccessControlException: Permission denied: user=root, access=WRITE, inode="":hduser:supergroup:rwxr-xr-x

Here, the user root (since you are using sudo) does not have access to the HDFS directory /input. As you can see: hduser:supergroup:rwxr-xr-x says only hduser has write access. Hadoop doesn't really respect root as a special user.


To fix this, I suggest you change the permissions on the local data:

sudo chmod -R og+rx /usr/local/input-data/

Then, try the put command again as hduser.

Javascript array sort and unique

The fastest and simpleness way to do this task.

const N = Math.pow(8, 8)
let data = Array.from({length:  N}, () => Math.floor(Math.random() * N))
let newData = {}
let len = data.length

// the magic
while (len--) {
    newData[data[len]] = true
}

Differences between SP initiated SSO and IDP initiated SSO

SP Initiated SSO

Bill the user: "Hey Jimmy, show me that report"

Jimmy the SP: "Hey, I'm not sure who you are yet. We have a process here so you go get yourself verified with Bob the IdP first. I trust him."

Bob the IdP: "I see Jimmy sent you here. Please give me your credentials."

Bill the user: "Hi I'm Bill. Here are my credentials."

Bob the IdP: "Hi Bill. Looks like you check out."

Bob the IdP: "Hey Jimmy. This guy Bill checks out and here's some additional information about him. You do whatever you want from here."

Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."

IdP Initiated SSO

Bill the user: "Hey Bob. I want to go to Jimmy's place. Security is tight over there."

Bob the IdP: "Hey Jimmy. I trust Bill. He checks out and here's some additional information about him. You do whatever you want from here."

Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."


I go into more detail here, but still keeping things simple: https://jorgecolonconsulting.com/saml-sso-in-simple-terms/.

String parsing in Java with delimiter tab "\t" using split

You can use yourstring.split("\x09"); I tested it, and it works.

What is the `data-target` attribute in Bootstrap 3?

The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.

Clearing _POST array fully

Yes, that is fine. $_POST is just another variable, except it has (super)global scope.

$_POST = array();

...will be quite enough. The loop is useless. It's probably best to keep it as an array rather than unset it, in case other files are attempting to read it and assuming it is an array.

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

These are subplot grid parameters encoded as a single integer. For example, "111" means "1x1 grid, first subplot" and "234" means "2x3 grid, 4th subplot".

Alternative form for add_subplot(111) is add_subplot(1, 1, 1).

Remove specific commit

So it sounds like the bad commit was incorporated in a merge commit at some point. Has your merge commit been pulled yet? If yes, then you'll want to use git revert; you'll have to grit your teeth and work through the conflicts. If no, then you could conceivably either rebase or revert, but you can do so before the merge commit, then redo the merge.

There's not much help we can give you for the first case, really. After trying the revert, and finding that the automatic one failed, you have to examine the conflicts and fix them appropriately. This is exactly the same process as fixing merge conflicts; you can use git status to see where the conflicts are, edit the unmerged files, find the conflicted hunks, figure out how to resolve them, add the conflicted files, and finally commit. If you use git commit by itself (no -m <message>), the message that pops up in your editor should be the template message created by git revert; you can add a note about how you fixed the conflicts, then save and quit to commit.

For the second case, fixing the problem before your merge, there are two subcases, depending on whether you've done more work since the merge. If you haven't, you can simply git reset --hard HEAD^ to knock off the merge, do the revert, then redo the merge. But I'm guessing you have. So, you'll end up doing something like this:

  • create a temporary branch just before the merge, and check it out
  • do the revert (or use git rebase -i <something before the bad commit> <temporary branch> to remove the bad commit)
  • redo the merge
  • rebase your subsequent work back on: git rebase --onto <temporary branch> <old merge commit> <real branch>
  • remove the temporary branch

Put icon inside input element in a form

You Can Try this : Bootstrap-4 Beta
https://www.codeply.com/go/W25zyByhec

<div class="container">
            <form>
                <div class="row">
                    <div class="input-group mb-3 col-sm-6">
                      <input type="text" class="form-control border-right-0" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
                        <div class="input-group-prepend bg-white">
                            <span class="input-group-text border-left-0 rounded-right bg-white" id="basic-addon1"><i class="fas fa-search"></i></span>
                        </div>
                    </div>
                </div>
            </form>
        </div>

??

libaio.so.1: cannot open shared object file

Install the packages:

sudo apt-get install libaio1 libaio-dev

or

sudo yum install libaio

PHP reindex array?

array_values does the job :

$myArray  = array_values($myArray);

Also some other php function do not preserve the keys, i.e. reset the index.

PHP - Notice: Undefined index:

How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

It's too late but somewhat may useful to others

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

which Means you have Missed some Declarations or The Required Declarations Not Found in Your XML

In my case i forgot to add the follwoing

After Adding this the Problem Gone away

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

Unable to set data attribute using jQuery Data() API

As mentioned, the .data() method won't actually set the value of the data- attribute, nor will it read updated values if the data- attribute changes.

My solution was to extend jQuery with a .realData() method that actually corresponds to the current value of the attribute:

// Alternative to .data() that updates data- attributes, and reads their current value.
(function($){
  $.fn.realData = function(name,value) {
      if (value === undefined) {
        return $(this).attr('data-'+name);
      } else {
        $(this).attr('data-'+name,value);
      }
  };
})(jQuery);

NOTE: Sure you could just use .attr(), but from my experience, most developers (aka me) make the mistake of viewing .attr() and .data() as interchangeable, and often substitute one for the other without thinking. It might work most of the time, but it's a great way to introduce bugs, especially when dealing with any sort of dynamic data binding. So by using .realData(), I can be more explicit about the intended behavior.

Export tables to an excel spreadsheet in same directory

You can use VBA to export an Access database table as a Worksheet in an Excel Workbook.

To obtain the path of the Access database, use the CurrentProject.Path property.

To name the Excel Workbook file with the current date, use the Format(Date, "yyyyMMdd") method.

Finally, to export the table as a Worksheet, use the DoCmd.TransferSpreadsheet method.

Example:

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True

This will output both Table1 and Table2 into the same Workbook.

HTH

JUnit 4 compare Sets

A particularly interesting case is when you compare

   java.util.Arrays$ArrayList<[[name,value,type], [name1,value1,type1]]> 

and

   java.util.Collections$UnmodifiableCollection<[[name,value,type], [name1,value1,type1]]>

So far, the only solution I see is to change both of them into sets

assertEquals(new HashSet<CustomAttribute>(customAttributes), new HashSet<CustomAttribute>(result.getCustomAttributes()));

Or I could compare them element by element.

Command to escape a string in bash

In Bash:

printf "%q" "hello\world" | someprog

for example:

printf "%q" "hello\world"
hello\\world

This could be used through variables too:

printf -v var "%q\n" "hello\world"
echo "$var"
hello\\world

Create a day-of-week column in a Pandas dataframe using Python

Pandas 0.23+

Use pandas.Series.dt.day_name(), since pandas.Timestamp.weekday_name has been deprecated:

import pandas as pd


df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])

df['day_of_week'] = df['my_dates'].dt.day_name()

Output:

    my_dates  myvals day_of_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

Pandas 0.18.1+

As user jezrael points out below, dt.weekday_name was added in version 0.18.1 Pandas Docs

import pandas as pd

df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.weekday_name

Output:

    my_dates  myvals day_of_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

Original Answer:

Use this:

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.dayofweek.html

See this:

Get weekday/day-of-week for Datetime column of DataFrame

If you want a string instead of an integer do something like this:

import pandas as pd

df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.dayofweek

days = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'}

df['day_of_week'] = df['day_of_week'].apply(lambda x: days[x])

Output:

    my_dates  myvals day_of_week
0 2015-01-01       1       Thurs
1 2015-01-02       2         Fri
2 2015-01-01       3       Thurs

Convert javascript object or array to json for ajax data

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

console.log( JSON.stringify(display) );

This will print:

["none","block","none"]

This is how JSON actually serializes array. However what you want to see is something like:

{"0":"none","1":"block","2":"none"}

To get this format you want to serialize object, not array. So let's rewrite above code like this:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

console.log( JSON.stringify(display2) );

This will print in the format you want.

You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console

Are there benefits of passing by pointer over passing by reference in C++?

Not really. Internally, passing by reference is performed by essentially passing the address of the referenced object. So, there really aren't any efficiency gains to be had by passing a pointer.

Passing by reference does have one benefit, however. You are guaranteed to have an instance of whatever object/type that is being passed in. If you pass in a pointer, then you run the risk of receiving a NULL pointer. By using pass-by-reference, you are pushing an implicit NULL-check up one level to the caller of your function.

How to use mod operator in bash?

Try the following:

 for i in {1..600}; do echo wget http://example.com/search/link$(($i % 5)); done

The $(( )) syntax does an arithmetic evaluation of the contents.

What is the best way to get all the divisors of a number?

Given your factorGenerator function, here is a divisorGen that should work:

def divisorGen(n):
    factors = list(factorGenerator(n))
    nfactors = len(factors)
    f = [0] * nfactors
    while True:
        yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
        i = 0
        while True:
            f[i] += 1
            if f[i] <= factors[i][1]:
                break
            f[i] = 0
            i += 1
            if i >= nfactors:
                return

The overall efficiency of this algorithm will depend entirely on the efficiency of the factorGenerator.

How to filter empty or NULL names in a QuerySet?

You could do this:

Name.objects.exclude(alias__isnull=True)

If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:

Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')

Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias is either null or an empty string, so you get all Name objects that have a not-null, not-empty alias field. The generated SQL would look something like:

SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""

You can also pass multiple arguments to a single call to exclude, which would ensure that only objects that meet every condition get excluded:

Name.objects.exclude(some_field=True, other_field=True)

Here, rows in which some_field and other_field are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:

SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)

Alternatively, if your logic is more complex than that, you could use Django's Q objects:

from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))

For more info see this page and this page in the Django docs.

As an aside: My SQL examples are just an analogy--the actual generated SQL code will probably look different. You'll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.

store return json value in input hidden field

It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).

Anyway, if that is an array wrapper, you'll want something like this:

$('#my-hidden-field').val(theObject[0].id);

You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,

$MyNamespace = $MyNamespace || {};
$MyNamespace.myKey = theObject;

This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.

Is there an addHeaderView equivalent for RecyclerView?

You can just place your header and your RecyclerView in a NestedScrollView:

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

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

        <include
            layout="@layout/your_header"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/list_recylclerview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

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

In order for scrolling to work correctly, you need to disable nested scrolling on your RecyclerView:

myRecyclerView.setNestedScrollingEnabled(false);

jQuery select child element by class with unknown path

This should do the trick:

$('#thisElement').find('.classToSelect')

Python re.sub replace with matched content

Use \1 instead of $1.

\number Matches the contents of the group of the same number.

http://docs.python.org/library/re.html#regular-expression-syntax

Confusing "duplicate identifier" Typescript error message

Closing the solution completely and rerunning the project solved my issue.

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

When and why to 'return false' in JavaScript?

Er ... how about in a boolean function to indicate 'not true'?

Why does AngularJS include an empty option in select?

Something similar was happening to me too and was caused by an upgrade to angular 1.5.ng-init seems to be being parsed for type in newer versions of Angular. In older Angular ng-init="myModelName=600" would map to an option with value "600" i.e. <option value="600">First</option> but in Angular 1.5 it won't find this as it seems to be expecting to find an option with value 600 i.e <option value=600>First</option>. Angular would then insert a random first item:

<option value="? number:600 ?"></option>

Angular < 1.2.x

<select ng-model="myModelName" ng-init="myModelName=600">
  <option value="600">First</option>
  <option value="700">Second</option>
</select>

Angular > 1.2

<select ng-model="myModelName" ng-init="myModelName='600'">
  <option value="600">First</option>
  <option value="700">Second</option>
</select>

How to select only date from a DATETIME field in MySQL?

Simply You can do

SELECT DATE(date_field) AS date_field FROM table_name

python ignore certificate validation urllib2

urllib2 does not verify server certificate by default. Check this documentation.

Edit: As pointed out in below comment, this is not true anymore for newer versions (seems like >= 2.7.9) of Python. Refer the below ANSWER

Github "Updates were rejected because the remote contains work that you do not have locally."

The supplied answers didn't work for me.

I had an empty repo on GitHub with only the LICENSE file and a single commit locally. What worked was:

$ git fetch
$ git merge --allow-unrelated-histories
Merge made by the 'recursive' strategy.
 LICENSE | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
 create mode 100644 LICENSE

Also before merge you may want to:

$ git branch --set-upstream-to origin/master
Branch 'master' set up to track remote branch 'master' from 'origin'.

How do I get extra data from intent on Android?

First, get the intent which has started your activity using the getIntent() method:

Intent intent = getIntent();

If your extra data is represented as strings, then you can use intent.getStringExtra(String name) method. In your case:

String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");

iPhone system font

If you're doing programatic customisation, don't hard code the system font. Use UIFont systemFontOfSize:, UIFont boldSystemFontOfSize: and UIFont italicSystemFontOfSize (Apple documentation).

This has become especially relevant since iOS 7, which changed the system font to Helvetica Neue.

This has become super especially relevant since iOS 9, which changed the system font again to San Francisco.

Node.js: How to read a stream into a buffer?

in ts, [].push(bufferPart) is not compatible;

so:

getBufferFromStream(stream: Part | null): Promise<Buffer> {
    if (!stream) {
        throw 'FILE_STREAM_EMPTY';
    }
    return new Promise(
        (r, j) => {
            let buffer = Buffer.from([]);
            stream.on('data', buf => {
               buffer = Buffer.concat([buffer, buf]);
            });
            stream.on('end', () => r(buffer));
            stream.on('error', j);
        }
    );
}

How do I break a string across more than one line of code in JavaScript?

No need of any manual break in code. Just add \n where you want to break.

alert ("Please Select file \n to delete");

This will show the alert like

Please select file 
to delete.

How to select the first row of each group?

Window functions:

Something like this should do the trick:

import org.apache.spark.sql.functions.{row_number, max, broadcast}
import org.apache.spark.sql.expressions.Window

val df = sc.parallelize(Seq(
  (0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
  (1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
  (2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
  (3,"cat8",35.6))).toDF("Hour", "Category", "TotalValue")

val w = Window.partitionBy($"hour").orderBy($"TotalValue".desc)

val dfTop = df.withColumn("rn", row_number.over(w)).where($"rn" === 1).drop("rn")

dfTop.show
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

This method will be inefficient in case of significant data skew.

Plain SQL aggregation followed by join:

Alternatively you can join with aggregated data frame:

val dfMax = df.groupBy($"hour".as("max_hour")).agg(max($"TotalValue").as("max_value"))

val dfTopByJoin = df.join(broadcast(dfMax),
    ($"hour" === $"max_hour") && ($"TotalValue" === $"max_value"))
  .drop("max_hour")
  .drop("max_value")

dfTopByJoin.show

// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

It will keep duplicate values (if there is more than one category per hour with the same total value). You can remove these as follows:

dfTopByJoin
  .groupBy($"hour")
  .agg(
    first("category").alias("category"),
    first("TotalValue").alias("TotalValue"))

Using ordering over structs:

Neat, although not very well tested, trick which doesn't require joins or window functions:

val dfTop = df.select($"Hour", struct($"TotalValue", $"Category").alias("vs"))
  .groupBy($"hour")
  .agg(max("vs").alias("vs"))
  .select($"Hour", $"vs.Category", $"vs.TotalValue")

dfTop.show
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

With DataSet API (Spark 1.6+, 2.0+):

Spark 1.6:

case class Record(Hour: Integer, Category: String, TotalValue: Double)

df.as[Record]
  .groupBy($"hour")
  .reduce((x, y) => if (x.TotalValue > y.TotalValue) x else y)
  .show

// +---+--------------+
// | _1|            _2|
// +---+--------------+
// |[0]|[0,cat26,30.9]|
// |[1]|[1,cat67,28.5]|
// |[2]|[2,cat56,39.6]|
// |[3]| [3,cat8,35.6]|
// +---+--------------+

Spark 2.0 or later:

df.as[Record]
  .groupByKey(_.Hour)
  .reduceGroups((x, y) => if (x.TotalValue > y.TotalValue) x else y)

The last two methods can leverage map side combine and don't require full shuffle so most of the time should exhibit a better performance compared to window functions and joins. These cane be also used with Structured Streaming in completed output mode.

Don't use:

df.orderBy(...).groupBy(...).agg(first(...), ...)

It may seem to work (especially in the local mode) but it is unreliable (see SPARK-16207, credits to Tzach Zohar for linking relevant JIRA issue, and SPARK-30335).

The same note applies to

df.orderBy(...).dropDuplicates(...)

which internally uses equivalent execution plan.

Bootstrap modal in React.js

Solution using React functional components.

import React, { useState, useRef, useEffect } from 'react'

const Modal = ({ title, show, onButtonClick }) => {

    const dialog = useRef({})

    useEffect(() => { $(dialog.current).modal(show ? 'show' : 'hide') }, [show])
    useEffect(() => { $(dialog.current).on('hide.bs.modal', () =>
        onButtonClick('close')) }, [])

    return (
        <div className="modal fade" ref={dialog}
            id="modalDialog" tabIndex="-1" role="dialog"
            aria-labelledby="modalDialogLabel" aria-hidden="true"
        >
            <div className="modal-dialog" role="document">
                <div className="modal-content">
                    <div className="modal-header">
                        <h5 className="modal-title" id="modalDialogLabel">{title}</h5>
                        <button type="button" className="close" aria-label="Close"
                            onClick={() => onButtonClick('close')}
                        >
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div className="modal-body">
                        ...
                    </div>
                    <div className="modal-footer">
                        <button type="button" className="btn btn-secondary"
                            onClick={() => onButtonClick('close')}>Close</button>
                        <button type="button" className="btn btn-primary"
                            onClick={() => onButtonClick('save')}>Save</button>
                    </div>
                </div>
            </div>
        </div>
    )
}

const App = () => {

    const [ showDialog, setShowDialog ] = useState(false)

    return (
        <div className="container">
            <Modal
                title="Modal Title"
                show={showDialog}
                onButtonClick={button => {
                    if(button == 'close') setShowDialog(false)
                    if(button == 'save') console.log('save button clicked')
                }}
            />
            <button className="btn btn-primary" onClick={() => {
                setShowDialog(true)
            }}>Show Dialog</button>
        </div>
    )
}

How to zoom in/out an UIImage object when user pinches screen?

Another easy way to do this is to place your UIImageView within a UIScrollView. As I describe here, you need to set the scroll view's contentSize to be the same as your UIImageView's size. Set your controller instance to be the delegate of the scroll view and implement the viewForZoomingInScrollView: and scrollViewDidEndZooming:withView:atScale: methods to allow for pinch-zooming and image panning. This is effectively what Ben's solution does, only in a slightly more lightweight manner, as you don't have the overhead of a full web view.

One issue you may run into is that the scaling within the scroll view comes in the form of transforms applied to the image. This may lead to blurriness at high zoom factors. For something that can be redrawn, you can follow my suggestions here to provide a crisper display after the pinch gesture is finished. hniels' solution could be used at that point to rescale your image.

How to use 'find' to search for files created on a specific date?

@Max: is right about the creation time.

However, if you want to calculate the elapsed days argument for one of the -atime, -ctime, -mtime parameters, you can use the following expression

ELAPSED_DAYS=$(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))

Replace "2008-09-24" with whatever date you want and ELAPSED_DAYS will be set to the number of days between then and today. (Update: subtract one from the result to align with find's date rounding.)

So, to find any file modified on September 24th, 2008, the command would be:

find . -type f -mtime $(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))

This will work if your version of find doesn't support the -newerXY predicates mentioned in @Arve:'s answer.

Setting active profile and config location from command line in spring boot

We want to automatically pick property file based upon mentioned the profile name in spring.profiles.active and the path in -Dspring.config.location

application-dev.properties

If we are running jar in Unix OS then we have to use / at the end of -Dspring.config.location otherwise it will give below error.

Error :: java.lang.IllegalStateException: File extension of config file location 'file:/home/xyz/projectName/cfg' is not known to any PropertySourceLoader. If the location is meant to reference a directory, it must end in '/'

Example

java -Dspring.profiles.active=dev -Dspring.config.location=/home/xyz/projectName/cfg/ -jar /home/xyz/project/abc.jar

or

java -jar /home/xyz/project/abc.jar --spring.profiles.active=dev --spring.config.location=/home/xyz/projectName/cfg/

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

How do I print a list of "Build Settings" in Xcode project?

Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.

As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:

Target's Build Phases section w/ added Log Build Settings script phase

To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash and the command to export.  You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources.  Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.

The result is this incredibly helpful listing of current environment variables used for building:

Build Log output w/ export command's results

How to use Select2 with JSON via Ajax request?

My ajax never gets fired until I wrapped the whole thing in

setTimeout(function(){ .... }, 3000);

I was using it in mounted section of Vue. it needs more time.

Difference between document.addEventListener and window.addEventListener?

You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window and document both fit the bill (with just a few differences).

From mozilla dev network:

addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.

So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.

Redirecting from cshtml page

Would be safer to do this.

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

So the controller for that action runs as well, to populate any model the view needs.

Source
Redirect from a view to another view

Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.

SSL "Peer Not Authenticated" error with HttpClient 4.1

If the server's certificate is self-signed, then this is working as designed and you will have to import the server's certificate into your keystore.

Assuming the server certificate is signed by a well-known CA, this is happening because the set of CA certificates available to a modern browser is much larger than the limited set that is shipped with the JDK/JRE.

The EasySSL solution given in one of the posts you mention just buries the error, and you won't know if the server has a valid certificate.

You must import the proper Root CA into your keystore to validate the certificate. There's a reason you can't get around this with the stock SSL code, and that's to prevent you from writing programs that behave as if they are secure but are not.

Google Maps API OVER QUERY LIMIT per second limit

The geocoder has quota and rate limits. From experience, you can geocode ~10 locations without hitting the query limit (the actual number probably depends on server loading). The best solution is to delay when you get OVER_QUERY_LIMIT errors, then retry. See these similar posts:

PostgreSQL return result set as JSON array?

TL;DR

SELECT json_agg(t) FROM t

for a JSON array of objects, and

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )
FROM t

for a JSON object of arrays.

List of objects

This section describes how to generate a JSON array of objects, with each row being converted to a single object. The result looks like this:

[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a":3,"b":"value3"}]

9.3 and up

The json_agg function produces this result out of the box. It automatically figures out how to convert its input into JSON and aggregates it into an array.

SELECT json_agg(t) FROM t

There is no jsonb (introduced in 9.4) version of json_agg. You can either aggregate the rows into an array and then convert them:

SELECT to_jsonb(array_agg(t)) FROM t

or combine json_agg with a cast:

SELECT json_agg(t)::jsonb FROM t

My testing suggests that aggregating them into an array first is a little faster. I suspect that this is because the cast has to parse the entire JSON result.

9.2

9.2 does not have the json_agg or to_json functions, so you need to use the older array_to_json:

SELECT array_to_json(array_agg(t)) FROM t

You can optionally include a row_to_json call in the query:

SELECT array_to_json(array_agg(row_to_json(t))) FROM t

This converts each row to a JSON object, aggregates the JSON objects as an array, and then converts the array to a JSON array.

I wasn't able to discern any significant performance difference between the two.

Object of lists

This section describes how to generate a JSON object, with each key being a column in the table and each value being an array of the values of the column. It's the result that looks like this:

{"a":[1,2,3], "b":["value1","value2","value3"]}

9.5 and up

We can leverage the json_build_object function:

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )
FROM t

You can also aggregate the columns, creating a single row, and then convert that into an object:

SELECT to_json(r)
FROM (
    SELECT
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

Note that aliasing the arrays is absolutely required to ensure that the object has the desired names.

Which one is clearer is a matter of opinion. If using the json_build_object function, I highly recommend putting one key/value pair on a line to improve readability.

You could also use array_agg in place of json_agg, but my testing indicates that json_agg is slightly faster.

There is no jsonb version of the json_build_object function. You can aggregate into a single row and convert:

SELECT to_jsonb(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Unlike the other queries for this kind of result, array_agg seems to be a little faster when using to_jsonb. I suspect this is due to overhead parsing and validating the JSON result of json_agg.

Or you can use an explicit cast:

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )::jsonb
FROM t

The to_jsonb version allows you to avoid the cast and is faster, according to my testing; again, I suspect this is due to overhead of parsing and validating the result.

9.4 and 9.3

The json_build_object function was new to 9.5, so you have to aggregate and convert to an object in previous versions:

SELECT to_json(r)
FROM (
    SELECT
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

or

SELECT to_jsonb(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

depending on whether you want json or jsonb.

(9.3 does not have jsonb.)

9.2

In 9.2, not even to_json exists. You must use row_to_json:

SELECT row_to_json(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Documentation

Find the documentation for the JSON functions in JSON functions.

json_agg is on the aggregate functions page.

Design

If performance is important, ensure you benchmark your queries against your own schema and data, rather than trust my testing.

Whether it's a good design or not really depends on your specific application. In terms of maintainability, I don't see any particular problem. It simplifies your app code and means there's less to maintain in that portion of the app. If PG can give you exactly the result you need out of the box, the only reason I can think of to not use it would be performance considerations. Don't reinvent the wheel and all.

Nulls

Aggregate functions typically give back NULL when they operate over zero rows. If this is a possibility, you might want to use COALESCE to avoid them. A couple of examples:

SELECT COALESCE(json_agg(t), '[]'::json) FROM t

Or

SELECT to_jsonb(COALESCE(array_agg(t), ARRAY[]::t[])) FROM t

Credit to Hannes Landeholm for pointing this out

How to split data into 3 sets (train, validation and test)?

However, one approach to dividing the dataset into train, test, cv with 0.6, 0.2, 0.2 would be to use the train_test_split method twice.

from sklearn.model_selection import train_test_split

x, x_test, y, y_test = train_test_split(xtrain,labels,test_size=0.2,train_size=0.8)
x_train, x_cv, y_train, y_cv = train_test_split(x,y,test_size = 0.25,train_size =0.75)

Extract file basename without path and extension in bash

Pure bash, no basename, no variable juggling. Set a string and echo:

p=/the/path/foo.txt
echo "${p//+(*\/|.*)}"

Output:

foo

Note: the bash extglob option must be "on", (Ubuntu sets extglob "on" by default), if it's not, do:

shopt -s extglob

Walking through the ${p//+(*\/|.*)}:

  1. ${p -- start with $p.
  2. // substitute every instance of the pattern that follows.
  3. +( match one or more of the pattern list in parenthesis, (i.e. until item #7 below).
  4. 1st pattern: *\/ matches anything before a literal "/" char.
  5. pattern separator | which in this instance acts like a logical OR.
  6. 2nd pattern: .* matches anything after a literal "." -- that is, in bash the "." is just a period char, and not a regex dot.
  7. ) end pattern list.
  8. } end parameter expansion. With a string substitution, there's usually another / there, followed by a replacement string. But since there's no / there, the matched patterns are substituted with nothing; this deletes the matches.

Relevant man bash background:

  1. pattern substitution:
  ${parameter/pattern/string}
          Pattern substitution.  The pattern is expanded to produce a pat
          tern just as in pathname expansion.  Parameter is  expanded  and
          the  longest match of pattern against its value is replaced with
          string.  If pattern begins with /, all matches  of  pattern  are
          replaced   with  string.   Normally  only  the  first  match  is
          replaced.  If pattern begins with #, it must match at the begin-
          ning of the expanded value of parameter.  If pattern begins with
          %, it must match at the end of the expanded value of  parameter.
          If string is null, matches of pattern are deleted and the / fol
          lowing pattern may be omitted.  If parameter is @ or *, the sub
          stitution  operation  is applied to each positional parameter in
          turn, and the expansion is the resultant list.  If parameter  is
          an  array  variable  subscripted  with  @ or *, the substitution
          operation is applied to each member of the array  in  turn,  and
          the expansion is the resultant list.
  1. extended pattern matching:
  If the extglob shell option is enabled using the shopt builtin, several
   extended  pattern  matching operators are recognized.  In the following
   description, a pattern-list is a list of one or more patterns separated
   by a |.  Composite patterns may be formed using one or more of the fol
   lowing sub-patterns:

          ?(pattern-list)
                 Matches zero or one occurrence of the given patterns
          *(pattern-list)
                 Matches zero or more occurrences of the given patterns
          +(pattern-list)
                 Matches one or more occurrences of the given patterns
          @(pattern-list)
                 Matches one of the given patterns
          !(pattern-list)
                 Matches anything except one of the given patterns

How to test if a DataSet is empty?

You should loop through all tables and test if table.Rows.Count is 0

bool IsEmpty(DataSet dataSet)
{
    foreach(DataTable table in dataSet.Tables)
        if (table.Rows.Count != 0) return false;

    return true;
}

Update: Since a DataTable could contain deleted rows RowState = Deleted, depending on what you want to achive, it could be a good idea to check the DefaultView instead (which does not contain deleted rows).

bool IsEmpty(DataSet dataSet)
{
    return !dataSet.Tables.Cast<DataTable>().Any(x => x.DefaultView.Count > 0);
}

How to do a HTTP HEAD request from the windows command line?

If you cannot install aditional applications, then you can telnet (you will need to install this feature for your windows 7 by following this) the remote server:

TELNET server_name 80

followed by:

HEAD /virtual/directory/file.ext

or

GET /virtual/directory/file.ext

depending on if you want just the header (HEAD) or the full contents (GET)

HTML text input field with currency symbol

If you only need to support Safari, you can do it like this:

input.currency:before {
  content: attr(data-symbol);
  float: left;
  color: #aaa;
}

and an input field like

<input class="currency" data-symbol="€" type="number" value="12.9">

This way you don't need an extra tag and keep the symbol information in the markup.

fatal: does not appear to be a git repository

It is most likely that you got your repo's SSH URL wrong.

To confirm, go to your repository on Github and click the clone or download button. Then click the use SSH link.

ssh link

Now copy your official repo's SSH link. Mine looked like this - [email protected]:borenho/que-ay.git

You can now do git remote add origin [email protected]:borenho/que-ay.git if you didn't have origin yet.

If you had set origin before, change it by using git remote set-url origin [email protected]:borenho/que-ay.git

Now push with git push -u origin master

How do I create batch file to rename large number of files in a folder?

@ECHO off & SETLOCAL EnableDelayedExpansion

SET "_dir=" REM Must finish with '\'
SET "_ext=jpg"
SET "_toEdit=Vacation2010"
SET "_with=December"
FOR %%f IN ("%_dir%*.%_ext%") DO (
    CALL :modifyString "%_toEdit%" "%_with%" "%%~Nf" fileName 
    RENAME "%%f" "!fileName!%%~Xf"
)
GOTO end

:modifyString what with in toReturn
    SET "__in=%~3"
    SET "__in=!__in:%~1=%~2!"
    IF NOT "%~4" == "" (
        SET %~4=%__in%
    ) ELSE (
        ECHO %__in%
    )
    EXIT /B

:end

This script allows you to change the name of all the files that contain Vacation2010 with the same name, but with December instead of Vacation2010.

If you copy and paste the code, you have to save the .bat in the same folder of the photos. If you want to save the script in another directory [E.G. you have a favorite folder for the utilities] you have to change the value of _dir with the path of the photos.

If you have to do the same work for other photos [or others files changig _ext] you have to change the value of _toEdit with the string you want to change [or erase] and the value of _with with the string you want to put instead of _toEdit [SET "_with=" if you simply want to erase the string specified in _toEdit].

Running the new Intel emulator for Android

Using SDK Manager to download Intel HAX did not work.

Downloading and installing it from the Intel website did work. http://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager/

Top Tip: making the change in my BIOS to enable virtualization and then using "restart" did not enable virtualization. Doing a cold boot (i.e. shutdown and restart) suddenly made it appear.

The first step (on Windows) is to make sure that the Micrsoft Hardware-Assisted Virtualization Tool reports that "this computer is configured with hardware-assisted virtualization". http://www.microsoft.com/en-us/download/details.aspx?id=592

jquery datatables hide column

if anyone gets in here again this worked for me...

"aoColumnDefs": [{ "bVisible": false, "aTargets": [0] }]

Binding select element to object in Angular

You Can Select the Id using a Function

<option *ngFor="#c of countries" (change)="onchange(c.id)">{{c.name}}</option>

What is the difference between a var and val definition in Scala?

Thinking in terms of C++,

val x: T

is analogous to constant pointer to non-constant data

T* const x;

while

var x: T 

is analogous to non-constant pointer to non-constant data

T* x;

Favoring val over var increases immutability of the codebase which can facilitate its correctness, concurrency and understandability.

To understand the meaning of having a constant pointer to non-constant data consider the following Scala snippet:

val m = scala.collection.mutable.Map(1 -> "picard")
m // res0: scala.collection.mutable.Map[Int,String] = HashMap(1 -> picard)

Here the "pointer" val m is constant so we cannot re-assign it to point to something else like so

m = n // error: reassignment to val

however we can indeed change the non-constant data itself that m points to like so

m.put(2, "worf")
m // res1: scala.collection.mutable.Map[Int,String] = HashMap(1 -> picard, 2 -> worf)

Android - implementing startForeground for a service?

@mikebertiean solution almost did the trick, but I had this problem with additional twist -- I use Gingerbread system and I didn't want to add some extra package just to run notification. Finally I found: https://android.googlesource.com/platform/frameworks/support.git+/f9fd97499795cd47473f0344e00db9c9837eea36/v4/gingerbread/android/support/v4/app/NotificationCompatGingerbread.java

then I hit additional problem -- notification simply kills my app when it runs (how to solve this problem: Android: How to avoid that clicking on a Notification calls onCreate()), so in total my code in service looks like this (C#/Xamarin):

Intent notificationIntent = new Intent(this, typeof(MainActivity));
// make the changes to manifest as well
notificationIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(Resource.Drawable.Icon, "Starting service");
notification.SetLatestEventInfo(this, "MyApp", "Monitoring...", pendingIntent);
StartForeground(1337, notification);

What's the difference between unit tests and integration tests?

A unit test is done in (as far as possible) total isolation.

An integration test is done when the tested object or module is working like it should be, with other bits of code.

Running code after Spring Boot starts

Use a SmartInitializingSingleton bean in spring > 4.1

@Bean
public SmartInitializingSingleton importProcessor() {
    return () -> {
        doStuff();
    };

}

As alternative a CommandLineRunner bean can be implemented or annotating a bean method with @PostConstruct.

How to change Tkinter Button state from disabled to normal?

I think a quick way to change the options of a widget is using the configure method.

In your case, it would look like this:

self.x.configure(state=NORMAL)

Defining array with multiple types in TypeScript

Defining array with multiple types in TypeScript

Use a union type (string|number)[] demo:

const foo: (string|number)[] = [ 1, "message" ];

I have an array of the form: [ 1, "message" ].

If you are sure that there are always only two elements [number, string] then you can declare it as a tuple:

const foo: [number, string] = [ 1, "message" ];

How to print the contents of RDD?

You can convert your RDD to a DataFrame then show() it.

// For implicit conversion from RDD to DataFrame
import spark.implicits._

fruits = sc.parallelize([("apple", 1), ("banana", 2), ("orange", 17)])

// convert to DF then show it
fruits.toDF().show()

This will show the top 20 lines of your data, so the size of your data should not be an issue.

+------+---+                                                                    
|    _1| _2|
+------+---+
| apple|  1|
|banana|  2|
|orange| 17|
+------+---+

Convert SVG image to PNG with PHP

You can use Raphaël—JavaScript Library and achieve it easily. It will work in IE also.

Karma: Running a single test file from command line

First you need to start karma server with

karma start

Then, you can use grep to filter a specific test or describe block:

karma run -- --grep=testDescriptionFilter

Using 24 hour time in bootstrap timepicker

$('.time-picker').timepicker({
            showMeridian: false     
        });

This will work.

Fixed size div?

<div id="normal>text..</div>
<div id="small1" class="smallDiv"></div>
<div id="small2" class="smallDiv"></div>
<div id="small3" class="smallDiv"></div>

css:

.smallDiv { height: 150px; width: 150px; }

cannot open shared object file: No such file or directory

sudo ldconfig

ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib).

Generally package manager takes care of this while installing the new library, but not always (specially when you install library with cmake).

And if the output of this is empty

$ echo $LD_LIBRARY_PATH

Please set the default path

$ LD_LIBRARY_PATH=/usr/local/lib

How to display a JSON representation and not [Object Object] on the screen

There are 2 ways in which you can get the values:-

  1. Access the property of the object using dot notation (obj.property) .
  2. Access the property of the object by passing in key value for example obj["property"]

flutter remove back button on appbar

The AppBar widget has a property called automaticallyImplyLeading. By default it's value is true. If you don't want flutter automatically build the back button for you then just make the property false.

appBar: AppBar(
  title: Text("YOUR_APPBAR_TITLE"), 
  automaticallyImplyLeading: false,
),

To add your custom back button

appBar: AppBar(
  title: Text("YOUR_APPBAR_TITLE"), 
  automaticallyImplyLeading: false,
  leading: YOUR_CUSTOM_WIDGET(),
),

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

I've discovered similar problems with the openjdk-6-jre and openjdk-6-jre-headless packages in Ubuntu.

My problem was solved by purging the openjdk-6-jre and openjdk-6-jre-headless packages and re-installing. The alternatives are only updated on a fresh install of the openjdk-6-jre and openjdk-6-jre-headless packages.

Below is a sample of installing after purging:

aptitude purge openjdk-6-jre openjdk-6-jre-headless # to ensure no configuration exists
aptitude install --without-recommends openjdk-6-jre # Installing without some extras
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
  ca-certificates-java{a} java-common{a} libavahi-client3{a} libavahi-common-data{a} libavahi-common3{a} libcups2{a} libflac8{a} libgif4{a} libnspr4-0d{a} libnss3-1d{a} libogg0{a} libpulse0{a} libsndfile1{a} libvorbis0a{a} libvorbisenc2{a} libxi6{a} libxtst6{a}
  openjdk-6-jre openjdk-6-jre-headless{a} openjdk-6-jre-lib{a} tzdata-java{a}
The following packages are RECOMMENDED but will NOT be installed:
  icedtea-6-jre-cacao icedtea-netx ttf-dejavu-extra
0 packages upgraded, 21 newly installed, 0 to remove and 119 not upgraded.
Need to get 0B/34.5MB of archives. After unpacking 97.6MB will be used.
Do you want to continue? [Y/n/?]
Writing extended state information... Done
Selecting previously deselected package openjdk-6-jre-lib.
(Reading database ... 62267 files and directories currently installed.)
Unpacking openjdk-6-jre-lib (from .../openjdk-6-jre-lib_6b24-1.11.5-0ubuntu1~10.04.2_all.deb) ...
...
Processing triggers for man-db ...
Setting up tzdata-java (2012e-0ubuntu0.10.04) ...
...
Setting up openjdk-6-jre-headless (6b24-1.11.5-0ubuntu1~10.04.2) ...
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/java to provide /usr/bin/java (java) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/keytool to provide /usr/bin/keytool (keytool) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/pack200 to provide /usr/bin/pack200 (pack200) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/rmid to provide /usr/bin/rmid (rmid) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/rmiregistry to provide /usr/bin/rmiregistry (rmiregistry) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/unpack200 to provide /usr/bin/unpack200 (unpack200) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/orbd to provide /usr/bin/orbd (orbd) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/servertool to provide /usr/bin/servertool (servertool) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/tnameserv to provide /usr/bin/tnameserv (tnameserv) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/lib/jexec to provide /usr/bin/jexec (jexec) in auto mode.
Setting up openjdk-6-jre (6b24-1.11.5-0ubuntu1~10.04.2) ...
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/policytool to provide /usr/bin/policytool (policytool) in auto mode.
...

You can see above that update-alternatives is run to set up links for the various Java binaries.

After this install, there are also links in /usr/bin, links in /etc/alternatives, and files for each binary in /var/lib/dpkg/alternatives.

ls -l /usr/bin/java /etc/alternatives/java /var/lib/dpkg/alternatives/java
lrwxrwxrwx 1 root root  40 2013-01-16 14:44 /etc/alternatives/java -> /usr/lib/jvm/java-6-openjdk/jre/bin/java
lrwxrwxrwx 1 root root  22 2013-01-16 14:44 /usr/bin/java -> /etc/alternatives/java
-rw-r--r-- 1 root root 158 2013-01-16 14:44 /var/lib/dpkg/alternatives/java

Let's contast this with installing without purging.

aptitude remove openjdk-6-jre
aptitude install --without-recommends openjdk-6-jre
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
  ca-certificates-java{a} java-common{a} libavahi-client3{a} libavahi-common-data{a} libavahi-common3{a} libcups2{a} libflac8{a} libgif4{a} libnspr4-0d{a} libnss3-1d{a} libogg0{a} libpulse0{a} libsndfile1{a} libvorbis0a{a} libvorbisenc2{a} libxi6{a} libxtst6{a}
  openjdk-6-jre openjdk-6-jre-headless{a} openjdk-6-jre-lib{a} tzdata-java{a}
The following packages are RECOMMENDED but will NOT be installed:
  icedtea-6-jre-cacao icedtea-netx ttf-dejavu-extra
0 packages upgraded, 21 newly installed, 0 to remove and 119 not upgraded.
Need to get 0B/34.5MB of archives. After unpacking 97.6MB will be used.
Do you want to continue? [Y/n/?]
Writing extended state information... Done
Selecting previously deselected package openjdk-6-jre-lib.
(Reading database ... 62293 files and directories currently installed.)
Unpacking openjdk-6-jre-lib (from .../openjdk-6-jre-lib_6b24-1.11.5-0ubuntu1~10.04.2_all.deb) ...
...
Processing triggers for man-db ...
...
Setting up openjdk-6-jre-headless (6b24-1.11.5-0ubuntu1~10.04.2) ...

Setting up openjdk-6-jre (6b24-1.11.5-0ubuntu1~10.04.2) ...
...

As you see, update-alternatives is not triggered.

After this install, there are no files for the Java binaries in /var/lib/dpkg/alternatives, no links in /etc/alternatives, and no links in /usr/bin.

The removal of the files in /var/lib/dpkg/alternatives also breaks update-java-alternatives.

Removing nan values from an array

If you're using numpy

# first get the indices where the values are finite
ii = np.isfinite(x)

# second get the values
x = x[ii]

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

How to count number of records per day?

This one is like the answer above which uses the MySql DATE_FORMAT() function. I also selected just one specific week in Jan.

SELECT 
    DatePart(day, DateAdded) AS date, 
    COUNT(entryhash) AS count 
FROM Responses 
    where DateAdded > '2020-01-25' and DateAdded < '2020-02-01' 
GROUP BY 
    DatePart(day, DateAdded )

How to allow only numbers in textbox in mvc4 razor

can we do this using data annotations as I am using MVC4 razor ?

No, as I understand your question, unobtrusive validation will only show erorrs. The simplest way is use jquery plugin:

Masked Input Plugin

Get the generated SQL statement from a SqlCommand object?

Profiler is hands-down your best option.

You might need to copy a set of statements from profiler due to the prepare + execute steps involved.

Create Generic method constraining T to an Enum

I tried to improve the code a bit:

public T LoadEnum<T>(string value, T defaultValue = default(T)) where T : struct, IComparable, IFormattable, IConvertible
{
    if (Enum.IsDefined(typeof(T), value))
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }
    return defaultValue;
}

Replace text in HTML page with jQuery

Check out Padolsey's article on DOM find and replace, as well as the library to implement the described algorithm.

In this sample usage, I replace all text inside a <div id="content"> that looks like a US telephone number with a tel: scheme link:

findAndReplaceDOMText(document.getElementById('content'), {
    find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
    replace:function (portion) {
        var a = document.createElement('a');
        a.className = 'telephone';
        a.href = 'tel:' + portion.text.replace(/\D/g, '');
        a.textContent = portion.text;
        return a;
    }
});

Android - drawable with rounded corners at the top only

Try to do something like this:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:bottom="-20dp" android:left="-20dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />

            <corners android:radius="20dp" />
        </shape>
    </item>
</layer-list>

It seems does not suitable to set different corner radius of rectangle. So you can use this hack.

How to call gesture tap on UIView programmatically in swift

I worked out on Xcode 6.4 on swift. See below.

var view1: UIView!

func assignTapToView1() {          
  let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap"))
  //  tap.delegate = self
  view1.addGestureRecognizer(tap)
  self.view .addSubview(view1)

...
}

func handleTap() {
 print("tap working")
 view1.removeFromSuperview()
 // view1.alpha = 0.1
}

Show diff between commits

Accepted answer is good.

Just putting it again here, so its easy to understand & try in future

git diff c1...c2 > mypatch_1.patch  
git diff c1..c2  > mypatch_2.patch  
git diff c1^..c2 > mypatch_3.patch  

I got the same diff for all the above commands.

Above helps in
1. seeing difference of between commit c1 & another commit c2
2. also making a patch file that shows diff and can be used to apply changes to another branch

If it not showing difference correctly
then c1 & c2 may be taken wrong
so adjust them to a before commit like c1 to c0, or to one after like c2 to c3

Use gitk to see the commits SHAs, 1st 8 characters are enough to use them as c0, c1, c2 or c3. You can also see the commits ids from Gitlab > Repository > Commits, etc.

Hope that helps.

Redirect From Action Filter Attribute

Set filterContext.Result

With the route name:

filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues);

You can also do something like:

filterContext.Result = new ViewResult
{
    ViewName = SharedViews.SessionLost,
    ViewData = filterContext.Controller.ViewData
};

If you want to use RedirectToAction:

You could make a public RedirectToAction method on your controller (preferably on its base controller) that simply calls the protected RedirectToAction from System.Web.Mvc.Controller. Adding this method allows for a public call to your RedirectToAction from the filter.

public new RedirectToRouteResult RedirectToAction(string action, string controller)
{
    return base.RedirectToAction(action, controller);
}

Then your filter would look something like:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var controller = (SomeControllerBase) filterContext.Controller;
    filterContext.Result = controller.RedirectToAction("index", "home");
}

Display / print all rows of a tibble (tbl_df)

I prefer to turn the tibble to data.frame. It shows everything and you're done

df %>% data.frame 

How to use JavaScript to change div backgroundColor

var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
  this.style.backgroundColor = 'green';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
  this.style.backgroundColor = 'transparent';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'transparent';
};

How to check if a file contains a specific string using Bash

In case if you want to check whether file does not contain a specific string, you can do it as follows.

if ! grep -q SomeString "$File"; then
  Some Actions # SomeString was not found
fi

Getting the .Text value from a TextBox

if(sender is TextBox) {
 var text = (sender as TextBox).Text;
}

What is Model in ModelAndView from Spring MVC?

Here in this case, we are having 3 parameter's in the Method namely ModelandView.
According to this question, the first parameter is easily understood. It represents the View which will be displayed to the client.
The other two parameters are just like The Pointer and The Holder
Hence you can sum it up like this

ModelAndView(View, Pointer, Holder);

The Pointer just points the information in the The Holder

When the Controller binds the View with this information, then in the said process, you can use The Pointer in the JSP page to access the information stored in The Holder to display that respected information to the client.
Here is the visual depiction of the respected process.

return new ModelAndView("welcomePage", "WelcomeMessage", message);

enter image description here

How do I increase the capacity of the Eclipse output console?

Window > Preferences, go to the Run/Debug > Console section >> "Limit console output.>>Console buffer size(characters):" (This option can be seen in Eclipse Indigo ,but it limits buffer size at 1,000,000 )

Programmatically change the height and width of a UIImageView Xcode Swift

Using autoview

image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true

Append data to a POST NSURLRequest

 NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                    timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
 NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

Group by multiple field names in java 8

The groupingBy method has the first parameter is Function<T,K> where:

@param <T> the type of the input elements

@param <K> the type of the keys

If we replace lambda with the anonymous class in your code, we can see some kind of that:

people.stream().collect(Collectors.groupingBy(new Function<Person, int>() {
            @Override
            public int apply(Person person) {
                return person.getAge();
            }
        }));

Just now change output parameter<K>. In this case, for example, I used a pair class from org.apache.commons.lang3.tuple for grouping by name and age, but you may create your own class for filtering groups as you need.

people.stream().collect(Collectors.groupingBy(new Function<Person, Pair<Integer, String>>() {
                @Override
                public YourFilter apply(Person person) {
                    return Pair.of(person.getAge(), person.getName());
                }
            }));

Finally, after replacing with lambda back, code looks like that:

Map<Pair<Integer,String>, List<Person>> peopleByAgeAndName = people.collect(Collectors.groupingBy(p -> Pair.of(person.getAge(), person.getName()), Collectors.mapping((Person p) -> p, toList())));

Difference between @click and v-on:click Vuejs

There is no difference between the two, one is just a shorthand for the second.

The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.

<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>

Source: official documentation.

JNZ & CMP Assembly Instructions

I will make a little bit wider answer here.

There are generally speaking two types of conditional jumps in x86:

  1. Arithmetic jumps - like JZ (jump if zero), JC (jump if carry), JNC (jump if not carry), etc.

  2. Comparison jumps - JE (jump if equal), JB (jump if below), JAE (jump if above or equal), etc.

So, use the first type only after arithmetic or logical instructions:

sub  eax, ebx
jnz  .result_is_not_zero 

and  ecx, edx
jz   .the_bit_is_not_set

Use the second group only after CMP instructions:

cmp  eax, ebx
jne  .eax_is_not_equal_to_ebx

cmp  ecx, edx
ja   .ecx_is_above_than_edx

This way, the program becomes more readable and you will never be confused.

Note, that sometimes these instructions are actually synonyms. JZ == JE; JC == JB; JNC == JAE and so on. The full table is following. As you can see, there are only 16 conditional jump instructions, but 30 mnemonics - they are provided to allow creation of more readable source code:

Mnemonic        Condition tested  Description  

jo              OF = 1            overflow 
jno             OF = 0            not overflow 
jc, jb, jnae    CF = 1            carry / below / not above nor equal
jnc, jae, jnb   CF = 0            not carry / above or equal / not below
je, jz          ZF = 1            equal / zero
jne, jnz        ZF = 0            not equal / not zero
jbe, jna        CF or ZF = 1      below or equal / not above
ja, jnbe        CF and ZF = 0      above / not below or equal
js              SF = 1            sign 
jns             SF = 0            not sign 
jp, jpe         PF = 1            parity / parity even 
jnp, jpo        PF = 0            not parity / parity odd 
jl, jnge        SF xor OF = 1     less / not greater nor equal
jge, jnl        SF xor OF = 0     greater or equal / not less
jle, jng    (SF xor OF) or ZF = 1 less or equal / not greater
jg, jnle    (SF xor OF) or ZF = 0 greater / not less nor equal 

Difference between @Mock and @InjectMocks

@Mock creates a mock. @InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock (or @Spy) annotations into this instance.

Note you must use @RunWith(MockitoJUnitRunner.class) or Mockito.initMocks(this) to initialize these mocks and inject them (JUnit 4).

With JUnit 5, you must use @ExtendWith(MockitoExtension.class).

@RunWith(MockitoJUnitRunner.class) // JUnit 4
// @ExtendWith(MockitoExtension.class) for JUnit 5
public class SomeManagerTest {

    @InjectMocks
    private SomeManager someManager;

    @Mock
    private SomeDependency someDependency; // this will be injected into someManager
 
     // tests...

}

Adding value to input field with jQuery

You can do it as below.

$(this).prev('input').val("hello world");

Live Demo

PHP: Get the key from an array in a foreach loop

Use foreach with key and value.

Example:

foreach($samplearr as $key => $val) {
     print "<tr><td>" 
         . $key 
         . "</td><td>" 
         . $val['value1'] 
         . "</td><td>" 
         . $val['value2'] 
         . "</td></tr>";
}

How to display list items as columns?

You can do that using CSS3.

Here is the HTML code snippet:

_x000D_
_x000D_
<ul id="listitem_ascolun">_x000D_
 <li>1</li>_x000D_
 <li>2</li>_x000D_
 <li>3</li>_x000D_
 <li>4</li>    _x000D_
 <li>5</li>_x000D_
 <li>6</li>_x000D_
 <li>7</li>_x000D_
 <li>8</li>_x000D_
 <li>9</li>_x000D_
 <li>10</li>_x000D_
 <li>11</li>_x000D_
 <li>12</li>    _x000D_
</ul>
_x000D_
_x000D_
_x000D_

& Here is the CSS3 code snippet :

_x000D_
_x000D_
#listitem_ascolun ul{margin:0;padding:0;list-style:none;}_x000D_
_x000D_
#listitem_ascolun {_x000D_
    height: 500px;  _x000D_
    column-count: 4;_x000D_
 -webkit-column-count: 4;_x000D_
 -moz-column-count: 4;_x000D_
}_x000D_
_x000D_
#listitem_ascolun li {_x000D_
    display: inline-block;_x000D_
}
_x000D_
_x000D_
_x000D_

How to read data when some numbers contain commas as thousand separator?

If number is separated by "." and decimals by "," (1.200.000,00) in calling gsub you must set fixed=TRUE as.numeric(gsub(".","",y,fixed=TRUE))

Difference between List, List<?>, List<T>, List<E>, and List<Object>

Problem 2 is OK, because " System.out.println(set);" means "System.out.println(set.toString());" set is an instance of List, so complier will call List.toString();

public static void test(List<?> set){
set.add(new Long(2)); //--> Error  
set.add("2");    //--> Error
System.out.println(set);
} 
Element ? will not promise Long and String, so complier will  not accept Long and String Object

public static void test(List<String> set){
set.add(new Long(2)); //--> Error
set.add("2");    //--> Work
System.out.println(set);
}
Element String promise it a String, so complier will accept String Object

Problem 3: these symbols are same, but you can give them differet specification. For example:

public <T extends Integer,E extends String> void p(T t, E e) {}

Problem 4: Collection does not allow type parameter covariance. But array does allow covariance.

How to make a <div> always full screen?

This always works for me:

<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
        html, body {
            height: 100%;
            margin: 0;
        }

        #wrapper {
            min-height: 100%; 
        }
    </style>
    <!--[if lte IE 6]>
    <style type="text/css">
        #container {
            height: 100%;
        }
    </style>
    <![endif]-->
</head>

<body>
    <div id="wrapper">some content</div>
</body>

This is probably the simplest solution to this problem. Only need to set four CSS attributes (although one of them is only to make IE happy).

Could not find any resources appropriate for the specified culture or the neutral culture

In my case a series of badly thought global text replacements had inadvertently changed this line in the resource designer cs file.

enter image description here

Since the namespace in that argument did not match the namespace of the class anymore, the application got confused at run time.

Check that the namespace of the designer matches the string argument in that line.

Comparing two java.util.Dates to see if they are in the same day

How about:

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));

You can also set the timezone to the SimpleDateFormat, if needed.

How do I find the parent directory in C#?

This is the most common way -- it really depends on what you are doing exactly: (To explain, the example below will remove the last 10 characters which is what you asked for, however if there are some business rules that are driving your need to find a specific location you should use those to retrieve the directory location, not find the location of something else and modify it.)

// remove last 10 characters from a string
str_directory = str_directory.Substring(0,str_directory.Length-10);

How to clone an InputStream?

Cloning an input stream might not be a good idea, because this requires deep knowledge about the details of the input stream being cloned. A workaround for this is to create a new input stream that reads from the same source again.

So using some Java 8 features this would look like this:

public class Foo {

    private Supplier<InputStream> inputStreamSupplier;

    public void bar() {
        procesDataThisWay(inputStreamSupplier.get());
        procesDataTheOtherWay(inputStreamSupplier.get());
    }

    private void procesDataThisWay(InputStream) {
        // ...
    }

    private void procesDataTheOtherWay(InputStream) {
        // ...
    }
}

This method has the positive effect that it will reuse code that is already in place - the creation of the input stream encapsulated in inputStreamSupplier. And there is no need to maintain a second code path for the cloning of the stream.

On the other hand, if reading from the stream is expensive (because a it's done over a low bandwith connection), then this method will double the costs. This could be circumvented by using a specific supplier that will store the stream content locally first and provide an InputStream for that now local resource.

What's the fastest way to loop through an array in JavaScript?

It's just 2018 so an update could be nice...

And I really have to disagree with the accepted answer. It defers on different browsers. some do forEach faster, some for-loop, and some while here is a benchmark on all method http://jsben.ch/mW36e

arr.forEach( a => {
  // ...
}

and since you can see alot of for-loop like for(a = 0; ... ) then worth to mention that without 'var' variables will be define globally and this can dramatically affects on speed so it'll get slow.

Duff's device run faster on opera but not in firefox

_x000D_
_x000D_
var arr = arr = new Array(11111111).fill(255);_x000D_
var benches =     _x000D_
[ [ "empty", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; a++);_x000D_
}]_x000D_
, ["for-loop", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; ++a)_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["for-loop++", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; a++)_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["for-loop - arr.length", () => {_x000D_
  for(var a = 0; a < arr.length; ++a )_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["reverse for-loop", () => {_x000D_
  for(var a = arr.length - 1; a >= 0; --a )_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
,["while-loop", () => {_x000D_
  var a = 0, l = arr.length;_x000D_
  while( a < l ) {_x000D_
    var b = arr[a] + 1;_x000D_
    ++a;_x000D_
  }_x000D_
}]_x000D_
, ["reverse-do-while-loop", () => {_x000D_
  var a = arr.length - 1; // CAREFUL_x000D_
  do {_x000D_
    var b = arr[a] + 1;_x000D_
  } while(a--);   _x000D_
}]_x000D_
, ["forEach", () => {_x000D_
  arr.forEach( a => {_x000D_
    var b = a + 1;_x000D_
  });_x000D_
}]_x000D_
, ["for const..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( const a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["for let..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( let a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["for var..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( var a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["Duff's device", () => {_x000D_
  var len = arr.length;_x000D_
  var i, n = len % 8 - 1;_x000D_
_x000D_
  if (n > 0) {_x000D_
    do {_x000D_
      var b = arr[len-n] + 1;_x000D_
    } while (--n); // n must be greater than 0 here_x000D_
  }_x000D_
  n = (len * 0.125) ^ 0;_x000D_
  if (n > 0) { _x000D_
    do {_x000D_
      i = --n <<3;_x000D_
      var b = arr[i] + 1;_x000D_
      var c = arr[i+1] + 1;_x000D_
      var d = arr[i+2] + 1;_x000D_
      var e = arr[i+3] + 1;_x000D_
      var f = arr[i+4] + 1;_x000D_
      var g = arr[i+5] + 1;_x000D_
      var h = arr[i+6] + 1;_x000D_
      var k = arr[i+7] + 1;_x000D_
    }_x000D_
    while (n); // n must be greater than 0 here also_x000D_
  }_x000D_
}]];_x000D_
function bench(title, f) {_x000D_
  var t0 = performance.now();_x000D_
  var res = f();_x000D_
  return performance.now() - t0; // console.log(`${title} took ${t1-t0} msec`);_x000D_
}_x000D_
var globalVarTime = bench( "for-loop without 'var'", () => {_x000D_
  // Here if you forget to put 'var' so variables'll be global_x000D_
  for(a = 0, l = arr.length; a < l; ++a)_x000D_
     var b = arr[a] + 1;_x000D_
});_x000D_
var times = benches.map( function(a) {_x000D_
                      arr = new Array(11111111).fill(255);_x000D_
                      return [a[0], bench(...a)]_x000D_
                     }).sort( (a,b) => a[1]-b[1] );_x000D_
var max = times[times.length-1][1];_x000D_
times = times.map( a => {a[2] = (a[1]/max)*100; return a; } );_x000D_
var template = (title, time, n) =>_x000D_
  `<div>` +_x000D_
    `<span>${title} &nbsp;</span>` +_x000D_
    `<span style="width:${3+n/2}%">&nbsp;${Number(time.toFixed(3))}msec</span>` +_x000D_
  `</div>`;_x000D_
_x000D_
var strRes = times.map( t => template(...t) ).join("\n") + _x000D_
            `<br><br>for-loop without 'var' ${globalVarTime} msec.`;_x000D_
var $container = document.getElementById("container");_x000D_
$container.innerHTML = strRes;
_x000D_
body { color:#fff; background:#333; font-family:helvetica; }_x000D_
body > div > div {  clear:both   }_x000D_
body > div > div > span {_x000D_
  float:left;_x000D_
  width:43%;_x000D_
  margin:3px 0;_x000D_
  text-align:right;_x000D_
}_x000D_
body > div > div > span:nth-child(2) {_x000D_
  text-align:left;_x000D_
  background:darkorange;_x000D_
  animation:showup .37s .111s;_x000D_
  -webkit-animation:showup .37s .111s;_x000D_
}_x000D_
@keyframes showup { from { width:0; } }_x000D_
@-webkit-keyframes showup { from { width:0; } }
_x000D_
<div id="container"> </div>
_x000D_
_x000D_
_x000D_

indexOf and lastIndexOf in PHP?

You need the following functions to do this in PHP:

strpos Find the position of the first occurrence of a substring in a string

strrpos Find the position of the last occurrence of a substring in a string

substr Return part of a string

Here's the signature of the substr function:

string substr ( string $string , int $start [, int $length ] )

The signature of the substring function (Java) looks a bit different:

string substring( int beginIndex, int endIndex )

substring (Java) expects the end-index as the last parameter, but substr (PHP) expects a length.

It's not hard, to get the desired length by the end-index in PHP:

$sub = substr($str, $start, $end - $start);

Here is the working code

$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
    $pt_password = substr($message, $start);
}
else {
    $end = strrpos($message, '-');
    $pt_password = substr($message, $start, $end - $start);
}

How to use order by with union all in sql?

You don't really need to have parenthesis. You can sort directly:

SELECT *, 1 AS RN FROM TABLE_A
UNION ALL 
SELECT *, 2 AS RN FROM TABLE_B
ORDER BY RN, COLUMN_1