Programs & Examples On #Throughput

When to use RabbitMQ over Kafka?

Use RabbitMQ when:

  • You don’t have to handle with Bigdata and you prefer a convenient in-built UI for monitoring
  • No need of automatically replicable queues
  • No multi subscribers for the messages- Since unlike Kafka which is a log, RabbitMQ is a queue and messages are removed once consumed and acknowledgment arrived
  • If you have the requirements to use Wildcards and regex for messages
  • If defining message priority is important

In Short: RabbitMQ is good for simple use cases, with low traffic of data, with the benefit of priority queue and flexible routing options. For massive data and high throughput use Kafka.

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Ok, I want to provide a small answer to one of the sub-questions that the OP asked that don't seem to be addressed in the existing questions. Caveat, I have not done any testing or code generation, or disassembly, just wanted to share a thought for others to possibly expound upon.

Why does the static change the performance?

The line in question: uint64_t size = atol(argv[1])<<20;

Short Answer

I would look at the assembly generated for accessing size and see if there are extra steps of pointer indirection involved for the non-static version.

Long Answer

Since there is only one copy of the variable whether it was declared static or not, and the size doesn't change, I theorize that the difference is the location of the memory used to back the variable along with where it is used in the code further down.

Ok, to start with the obvious, remember that all local variables (along with parameters) of a function are provided space on the stack for use as storage. Now, obviously, the stack frame for main() never cleans up and is only generated once. Ok, what about making it static? Well, in that case the compiler knows to reserve space in the global data space of the process so the location can not be cleared by the removal of a stack frame. But still, we only have one location so what is the difference? I suspect it has to do with how memory locations on the stack are referenced.

When the compiler is generating the symbol table, it just makes an entry for a label along with relevant attributes, like size, etc. It knows that it must reserve the appropriate space in memory but doesn't actually pick that location until somewhat later in process after doing liveness analysis and possibly register allocation. How then does the linker know what address to provide to the machine code for the final assembly code? It either knows the final location or knows how to arrive at the location. With a stack, it is pretty simple to refer to a location based one two elements, the pointer to the stackframe and then an offset into the frame. This is basically because the linker can't know the location of the stackframe before runtime.

Throughput and bandwidth difference?

In most cases with "bandwidth" and "throughput" it is OVER complicated; like trying to learn calculus in one day. There is NO need for this, in MOST cases when referencing "Bandwidth" and "Throughput".

All you need to know in MOST cases is this:

"MB" means mega "BYTES"; OR 8 bits and 8 bits and 8 bits, etc; is being sent down the line. Mb means mega "bits". OR a single bit and bit and bit, etc; down the line.

Example: IF your carrier says this is a "6 Mb line"; it means that is the maximum Bandwidth. More succinctly it means that you ONLY are going to benefit 750 kilobytes per/sec "throughput". Now why? Because the line is only sending a series of "bits", which uses 8 bits/sec to create a byte. Thus; you must divide bits/sec by 8 to get to bytes/sec. Thus: a 6Mb line can ONLY deliver 750 thousand bytes/sec.

Another example: I just got a fiber optic line from A T & T; and they LOVE to talk about "bits". So they advertise a whopping "100 mega bits per second". Big deal. Because that is only 12.5 "MBytes/per second.

Remember, EACH "character" on your keyboard or printed on the screen, etc, requires 8 bits; for the other end to "distinguish" what character it is, etc.

So even though I have a "Gargantuan" fiber line touted as "100Mb"; it is really only 12.5 MBytes (characters) per second (100 divided by 8).

Worse: MOST interchange the terms "MB" and "Mb". Worse yet; EVEN The technician that installed the Fiber Optic line and router in my home, did not know what the terms meant. So he thought, and his co-workers (according to him) believed the same. IE: That 100Mb line was a 100MB line. This is very sad.

A T & T reps on the phone rarely know the difference either. Even some of their supervisors do not know it either. Even sadder.

To summarize: "Bandwidth" uses "bits". "Throughput" uses "bytes". And...one byte takes up 8 bits. So again: a 100Mb line (bandwidth) can ONLY produce 12.5 MBytes/sec (throughput).

For whatever it's worth.

Understanding ibeacon distancing

With multiple phones and beacons at the same location, it's going to be difficult to measure proximity with any high degree of accuracy. Try using the Android "b and l bluetooth le scanner" app, to visualize the signal strengths (distance) variations, for multiple beacons, and you'll quickly discover that complex, adaptive algorithms may be required to provide any form of consistent proximity measurement.

You're going to see lots of solutions simply instructing the user to "please hold your phone here", to reduce customer frustration.

How to analyze a JMeter summary report?

A Jmeter Test Plan must have listener to showcase the result of performance test execution.

  • Listeners capture the response coming back from Server while Jmeter runs and showcase in the form of – tree, tables, graphs and log files.

  • It also allows you to save the result in a file for future reference. There are many types of listeners Jmeter provides. Some of them are: Summary Report, Aggregate Report, Aggregate Graph, View Results Tree, View Results in Table etc.

Here is the detailed understanding of each parameter in Summary report.

By referring to the figure:

image

Label: It is the name/URL for the specific HTTP(s) Request. If you have selected “Include group name in label?” option then the name of the Thread Group is applied as the prefix to each label.

Samples: This indicates the number of virtual users per request.

Average: It is the average time taken by all the samples to execute specific label. In our case, the average time for Label 1 is 942 milliseconds & total average time is 584 milliseconds.

Min: The shortest time taken by a sample for specific label. If we look at Min value for Label 1 then, out of 20 samples shortest response time one of the sample had was 584 milliseconds.

Max: The longest time taken by a sample for specific label. If we look at Max value for Label 1 then, out of 20 samples longest response time one of the sample had was 2867 milliseconds.

Std. Dev.: This shows the set of exceptional cases which were deviating from the average value of sample response time. The lesser this value more consistent the data. Standard deviation should be less than or equal to half of the average time for a label.

Error%: Percentage of Failed requests per Label.

Throughput: Throughput is the number of request that are processed per time unit(seconds, minutes, hours) by the server. This time is calculated from the start of first sample to the end of the last sample. Larger throughput is better.

KB/Sec: This indicates the amount of data downloaded from server during the performance test execution. In short, it is the Throughput measured in Kilobytes per second.

For more information: http://www.testingjournals.com/understand-summary-report-jmeter/

Parsing huge logfiles in Node.js - read in line-by-line

You can use the inbuilt readline package, see docs here. I use stream to create a new output stream.

var fs = require('fs'),
    readline = require('readline'),
    stream = require('stream');

var instream = fs.createReadStream('/path/to/file');
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;

var rl = readline.createInterface({
    input: instream,
    output: outstream,
    terminal: false
});

rl.on('line', function(line) {
    console.log(line);
    //Do your stuff ...
    //Then write to outstream
    rl.write(cubestuff);
});

Large files will take some time to process. Do tell if it works.

How can I generate a list or array of sequential integers in Java?

With Java 8 it is so simple so it doesn't even need separate method anymore:

List<Integer> range = IntStream.rangeClosed(start, end)
    .boxed().collect(Collectors.toList());

Which concurrent Queue implementation should I use in Java?

ConcurrentLinkedQueue means no locks are taken (i.e. no synchronized(this) or Lock.lock calls). It will use a CAS - Compare and Swap operation during modifications to see if the head/tail node is still the same as when it started. If so, the operation succeeds. If the head/tail node is different, it will spin around and try again.

LinkedBlockingQueue will take a lock before any modification. So your offer calls would block until they get the lock. You can use the offer overload that takes a TimeUnit to say you are only willing to wait X amount of time before abandoning the add (usually good for message type queues where the message is stale after X number of milliseconds).

Fairness means that the Lock implementation will keep the threads ordered. Meaning if Thread A enters and then Thread B enters, Thread A will get the lock first. With no fairness, it is undefined really what happens. It will most likely be the next thread that gets scheduled.

As for which one to use, it depends. I tend to use ConcurrentLinkedQueue because the time it takes my producers to get work to put onto the queue is diverse. I don't have a lot of producers producing at the exact same moment. But the consumer side is more complicated because poll won't go into a nice sleep state. You have to handle that yourself.

How can I get the current network interface throughput statistics on Linux/UNIX?

You can use iperf to benchmark network performance (maximum possible throughput). See following links for details:

http://en.wikipedia.org/wiki/Iperf

https://iperf.fr/

https://code.google.com/p/iperf/

What Process is using all of my disk IO

You're looking for iotop (assuming you've got kernel >2.6.20 and Python 2.5). Failing that, you're looking into hooking into the filesystem. I recommend the former.

Avoid synchronized(this) in Java?

No, you shouldn't always. However, I tend to avoid it when there are multiple concerns on a particular object that only need to be threadsafe in respect to themselves. For example, you might have a mutable data object that has "label" and "parent" fields; these need to be threadsafe, but changing one need not block the other from being written/read. (In practice I would avoid this by declaring the fields volatile and/or using java.util.concurrent's AtomicFoo wrappers).

Synchronization in general is a bit clumsy, as it slaps a big lock down rather than thinking exactly how threads might be allowed to work around each other. Using synchronized(this) is even clumsier and anti-social, as it's saying "no-one may change anything on this class while I hold the lock". How often do you actually need to do that?

I would much rather have more granular locks; even if you do want to stop everything from changing (perhaps you're serialising the object), you can just acquire all of the locks to achieve the same thing, plus it's more explicit that way. When you use synchronized(this), it's not clear exactly why you're synchronizing, or what the side effects might be. If you use synchronized(labelMonitor), or even better labelLock.getWriteLock().lock(), it's clear what you are doing and what the effects of your critical section are limited to.

How do you determine the ideal buffer size when using FileInputStream?

Optimum buffer size is related to a number of things: file system block size, CPU cache size and cache latency.

Most file systems are configured to use block sizes of 4096 or 8192. In theory, if you configure your buffer size so you are reading a few bytes more than the disk block, the operations with the file system can be extremely inefficient (i.e. if you configured your buffer to read 4100 bytes at a time, each read would require 2 block reads by the file system). If the blocks are already in cache, then you wind up paying the price of RAM -> L3/L2 cache latency. If you are unlucky and the blocks are not in cache yet, the you pay the price of the disk->RAM latency as well.

This is why you see most buffers sized as a power of 2, and generally larger than (or equal to) the disk block size. This means that one of your stream reads could result in multiple disk block reads - but those reads will always use a full block - no wasted reads.

Now, this is offset quite a bit in a typical streaming scenario because the block that is read from disk is going to still be in memory when you hit the next read (we are doing sequential reads here, after all) - so you wind up paying the RAM -> L3/L2 cache latency price on the next read, but not the disk->RAM latency. In terms of order of magnitude, disk->RAM latency is so slow that it pretty much swamps any other latency you might be dealing with.

So, I suspect that if you ran a test with different cache sizes (haven't done this myself), you will probably find a big impact of cache size up to the size of the file system block. Above that, I suspect that things would level out pretty quickly.

There are a ton of conditions and exceptions here - the complexities of the system are actually quite staggering (just getting a handle on L3 -> L2 cache transfers is mind bogglingly complex, and it changes with every CPU type).

This leads to the 'real world' answer: If your app is like 99% out there, set the cache size to 8192 and move on (even better, choose encapsulation over performance and use BufferedInputStream to hide the details). If you are in the 1% of apps that are highly dependent on disk throughput, craft your implementation so you can swap out different disk interaction strategies, and provide the knobs and dials to allow your users to test and optimize (or come up with some self optimizing system).

Disable/Enable button in Excel/VBA

This is working for me (Excel 2016) with a new ActiveX button, assign a control to you button and you're all set.

Sub deactivate_buttons()

     ActiveSheet.Shapes.Item("CommandButton1").ControlFormat.Enabled = False

End Sub

It changes the "Enabled" property in the ActiveX button Properties box to False and the button becomes inactive and greyed out.

Using Default Arguments in a Function

In PHP 8 we can use named arguments for this problem.

So we could solve the problem described by the original poster of this question:

What if I want to use the default argument for $x and set a different argument for $y?

With:

foo(blah: "blah", y: "test");

Reference: https://wiki.php.net/rfc/named_params (in particular the "Skipping defaults" section)

Declaring multiple variables in JavaScript

It's much more readable when doing it this way:

var hey = 23;
var hi = 3;
var howdy 4;

But takes less space and lines of code this way:

var hey=23,hi=3,howdy=4;

It can be ideal for saving space, but let JavaScript compressors handle it for you.

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

<?php
ini_set('xdebug.max_nesting_level', 9999);
... your code ...

P.S. Change 9999 to any number you want.

Creating and playing a sound in swift

This code works for me. Use Try and Catch for AVAudioPlayer

import UIKit
import AVFoundation
class ViewController: UIViewController {

    //Make sure that sound file is present in your Project.
    var CatSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Meow-sounds.mp3", ofType: "mp3")!)
    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        do {

            audioPlayer = try AVAudioPlayer(contentsOfURL: CatSound)
            audioPlayer.prepareToPlay()

        } catch {

            print("Problem in getting File")

        }      
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func button1Action(sender: AnyObject) {

        audioPlayer.play()
    }
}

ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored

It means the path you input caused an error. In your LD_PRELOAD command, modify the path like the error tips:

/usr/lib/liblunar-calendar-preload.so

How to add google-services.json in Android?

google-services.json file work like API keys means it store your project_id and api key with json format for all google services(Which enable by you at google console) so no need manage all at different places.

Important process when uses google-services.json

at application gradle you should add

apply plugin: 'com.google.gms.google-services'.

at top level gradle you should add below dependency

  dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

Python datetime to string without microsecond component

I found this to be the simplest way.

>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>> 

How to send parameters from a notification-click to an activity?

If you use

android:taskAffinity="myApp.widget.notify.activity"
android:excludeFromRecents="true"

in your AndroidManifest.xml file for the Activity to launch, you have to use the following in your intent:

Intent notificationClick = new Intent(context, NotifyActivity.class);
    Bundle bdl = new Bundle();
    bdl.putSerializable(NotifyActivity.Bundle_myItem, myItem);
    notificationClick.putExtras(bdl);
    notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
    notificationClick.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);  // schließt tasks der app und startet einen seperaten neuen

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(NotifyActivity.class);
    stackBuilder.addNextIntent(notificationClick);

    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(notificationPendingIntent);

Important is to set unique data e.g. using an unique id like:

notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));

how to print a string to console in c++

"Visual Studio does not support std::cout as debug tool for non-console applications"
- from Marius Amado-Alves' answer to "How can I see cout output in a non-console application?"

Which means if you use it, Visual Studio shows nothing in the "output" window (in my case VS2008)

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

I had same issue too.

In my case, I recently add an internal class to somewhere in project. One of the dependencies in solution has same class name and both of them are added correctly to references.

I changed my last activity and rebuild, it works.

Be sure that your compiler messages are valid. In my case I catch reference error from there, not listed as an error in Error List.

Log to the base 2 in python

In python 3 or above, math class has the following functions

import math

math.log2(x)
math.log10(x)
math.log1p(x)

or you can generally use math.log(x, base) for any base you want.

Good way of getting the user's location in Android

This is my solution which works fairly well:

private Location bestLocation = null;
private Looper looper;
private boolean networkEnabled = false, gpsEnabled = false;

private synchronized void setLooper(Looper looper) {
    this.looper = looper;
}

private synchronized void stopLooper() {
    if (looper == null) return;
    looper.quit();
}

@Override
protected void runTask() {
    final LocationManager locationManager = (LocationManager) service
            .getSystemService(Context.LOCATION_SERVICE);
    final SharedPreferences prefs = getPreferences();
    final int maxPollingTime = Integer.parseInt(prefs.getString(
            POLLING_KEY, "0"));
    final int desiredAccuracy = Integer.parseInt(prefs.getString(
            DESIRED_KEY, "0"));
    final int acceptedAccuracy = Integer.parseInt(prefs.getString(
            ACCEPTED_KEY, "0"));
    final int maxAge = Integer.parseInt(prefs.getString(AGE_KEY, "0"));
    final String whichProvider = prefs.getString(PROVIDER_KEY, "any");
    final boolean canUseGps = whichProvider.equals("gps")
            || whichProvider.equals("any");
    final boolean canUseNetwork = whichProvider.equals("network")
            || whichProvider.equals("any");
    if (canUseNetwork)
        networkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (canUseGps)
        gpsEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
    // If any provider is enabled now and we displayed a notification clear it.
    if (gpsEnabled || networkEnabled) removeErrorNotification();
    if (gpsEnabled)
        updateBestLocation(locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER));
    if (networkEnabled)
        updateBestLocation(locationManager
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
    if (desiredAccuracy == 0
            || getLocationQuality(desiredAccuracy, acceptedAccuracy,
                    maxAge, bestLocation) != LocationQuality.GOOD) {
        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                updateBestLocation(location);
                if (desiredAccuracy != 0
                        && getLocationQuality(desiredAccuracy,
                                acceptedAccuracy, maxAge, bestLocation)
                                == LocationQuality.GOOD)
                    stopLooper();
            }

            public void onProviderEnabled(String provider) {
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER))networkEnabled =true;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER)) gpsEnabled = true;
                // The user has enabled a location, remove any error
                // notification
                if (canUseGps && gpsEnabled || canUseNetwork
                        && networkEnabled) removeErrorNotification();
            }

            public void onProviderDisabled(String provider) {
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER))networkEnabled=false;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER)) gpsEnabled = false;
                if (!gpsEnabled && !networkEnabled) {
                    showErrorNotification();
                    stopLooper();
                }
            }

            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
                Log.i(LOG_TAG, "Provider " + provider + " statusChanged");
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER)) networkEnabled = 
                        status == LocationProvider.AVAILABLE
                        || status == LocationProvider.TEMPORARILY_UNAVAILABLE;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER))
                    gpsEnabled = status == LocationProvider.AVAILABLE
                      || status == LocationProvider.TEMPORARILY_UNAVAILABLE;
                // None of them are available, stop listening
                if (!networkEnabled && !gpsEnabled) {
                    showErrorNotification();
                    stopLooper();
                }
                // The user has enabled a location, remove any error
                // notification
                else if (canUseGps && gpsEnabled || canUseNetwork
                        && networkEnabled) removeErrorNotification();
            }
        };
        if (networkEnabled || gpsEnabled) {
            Looper.prepare();
            setLooper(Looper.myLooper());
            // Register the listener with the Location Manager to receive
            // location updates
            if (canUseGps)
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 1000, 1,
                        locationListener, Looper.myLooper());
            if (canUseNetwork)
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 1000, 1,
                        locationListener, Looper.myLooper());
            Timer t = new Timer();
            t.schedule(new TimerTask() {

                @Override
                public void run() {
                    stopLooper();
                }
            }, maxPollingTime * 1000);
            Looper.loop();
            t.cancel();
            setLooper(null);
            locationManager.removeUpdates(locationListener);
        } else // No provider is enabled, show a notification
        showErrorNotification();
    }
    if (getLocationQuality(desiredAccuracy, acceptedAccuracy, maxAge,
            bestLocation) != LocationQuality.BAD) {
        sendUpdate(new Event(EVENT_TYPE, locationToString(desiredAccuracy,
                acceptedAccuracy, maxAge, bestLocation)));
    } else Log.w(LOG_TAG, "LocationCollector failed to get a location");
}

private synchronized void showErrorNotification() {
    if (notifId != 0) return;
    ServiceHandler handler = service.getHandler();
    NotificationInfo ni = NotificationInfo.createSingleNotification(
            R.string.locationcollector_notif_ticker,
            R.string.locationcollector_notif_title,
            R.string.locationcollector_notif_text,
            android.R.drawable.stat_notify_error);
    Intent intent = new Intent(
            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    ni.pendingIntent = PendingIntent.getActivity(service, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Message msg = handler.obtainMessage(ServiceHandler.SHOW_NOTIFICATION);
    msg.obj = ni;
    handler.sendMessage(msg);
    notifId = ni.id;
}

private void removeErrorNotification() {
    if (notifId == 0) return;
    ServiceHandler handler = service.getHandler();
    if (handler != null) {
        Message msg = handler.obtainMessage(
                ServiceHandler.CLEAR_NOTIFICATION, notifId, 0);
        handler.sendMessage(msg);
        notifId = 0;
    }
}

@Override
public void interrupt() {
    stopLooper();
    super.interrupt();
}

private String locationToString(int desiredAccuracy, int acceptedAccuracy,
        int maxAge, Location location) {
    StringBuilder sb = new StringBuilder();
    sb.append(String.format(
            "qual=%s time=%d prov=%s acc=%.1f lat=%f long=%f",
            getLocationQuality(desiredAccuracy, acceptedAccuracy, maxAge,
                    location), location.getTime() / 1000, // Millis to
                                                            // seconds
            location.getProvider(), location.getAccuracy(), location
                    .getLatitude(), location.getLongitude()));
    if (location.hasAltitude())
        sb.append(String.format(" alt=%.1f", location.getAltitude()));
    if (location.hasBearing())
        sb.append(String.format(" bearing=%.2f", location.getBearing()));
    return sb.toString();
}

private enum LocationQuality {
    BAD, ACCEPTED, GOOD;

    public String toString() {
        if (this == GOOD) return "Good";
        else if (this == ACCEPTED) return "Accepted";
        else return "Bad";
    }
}

private LocationQuality getLocationQuality(int desiredAccuracy,
        int acceptedAccuracy, int maxAge, Location location) {
    if (location == null) return LocationQuality.BAD;
    if (!location.hasAccuracy()) return LocationQuality.BAD;
    long currentTime = System.currentTimeMillis();
    if (currentTime - location.getTime() < maxAge * 1000
            && location.getAccuracy() <= desiredAccuracy)
        return LocationQuality.GOOD;
    if (acceptedAccuracy == -1
            || location.getAccuracy() <= acceptedAccuracy)
        return LocationQuality.ACCEPTED;
    return LocationQuality.BAD;
}

private synchronized void updateBestLocation(Location location) {
    bestLocation = getBestLocation(location, bestLocation);
}

protected Location getBestLocation(Location location,
        Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return location;
    }
    if (location == null) return currentBestLocation;
    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;
    // If it's been more than two minutes since the current location, use
    // the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return location;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return currentBestLocation;
    }
    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
            .getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;
    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());
    // Determine location quality using a combination of timeliness and
    // accuracy
    if (isMoreAccurate) {
        return location;
    } else if (isNewer && !isLessAccurate) {
        return location;
    } else if (isNewer && !isSignificantlyLessAccurate
            && isFromSameProvider) {
        return location;
    }
    return bestLocation;
}

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) return provider2 == null;
    return provider1.equals(provider2);
}

VBA shorthand for x=x+1?

Sadly there are no operation-assignment operators in VBA.

(Addition-assignment += are available in VB.Net)

Pointless workaround;

Sub Inc(ByRef i As Integer)
   i = i + 1  
End Sub
...
Static value As Integer
inc value
inc value

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

    $(document).on('keyup keydown', function(e){shifted = e.shiftKey} );

How can I change the image displayed in a UIImageView programmatically?

To set image on your imageView use below line of code,

self.imgObj.image=[UIImage imageNamed:@"yourImage.png"];                         

Get all rows from SQLite

I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:

String name;
if (cursor.moveToFirst()) {

        while (cursor.isAfterLast() == false) {
            name = cursor.getString(cursor
                    .getColumnIndex(countyname));

            list.add(name);
            cursor.moveToNext();
        }
}

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I encountered the same problem and finally found out that the <tx:annotaion-driven /> was not defined within the [dispatcher]-servlet.xml where component-scan element enabled @service annotated class.

Simply put <tx:annotaion-driven /> with component-scan element together, the problem disappeared.

How to implement a ViewPager with different Fragments / Layouts

Create new instances in your fragments and do like so in your Activity

 private class SlidePagerAdapter extends FragmentStatePagerAdapter {
    public SlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch(position){
            case 0:
                return Fragment1.newInstance();
            case 1:
                return Fragment2.newInstance();
            case 2:
                return Fragment3.newInstance();
            case 3:
                return Fragment4.newInstance();


            default: break;

        }
        return null;
    }

how to add new <li> to <ul> onclick with javascript

You have not appended your li as a child to your ul element

Try this

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  ul.appendChild(li);
}

If you need to set the id , you can do so by

li.setAttribute("id", "element4");

Which turns the function into

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  li.setAttribute("id", "element4"); // added line
  ul.appendChild(li);
  alert(li.id);
}

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

How to do a FULL OUTER JOIN in MySQL?

You can do the following:

(SELECT 
    *
FROM
    table1 t1
        LEFT JOIN
    table2 t2 ON t1.id = t2.id
WHERE
    t2.id IS NULL)
UNION ALL
 (SELECT 
    *
FROM
    table1 t1
        RIGHT JOIN
    table2 t2 ON t1.id = t2.id
WHERE
    t1.id IS NULL);

Comparing double values in C#

Use decimal. It doesn't have this "problem".

Clear screen in shell

An easier way to clear a screen while in python is to use Ctrl + L though it works for the shell as well as other programs.

How to use document.getElementByName and getElementByTag?

  1. The getElementsByName() method accesses all elements with the specified name. this method returns collection of elements that is an array.
  2. The getElementsByTagName() method accesses all elements with the specified tagname. this method returns collection of elements that is an array.
  3. Accesses the first element with the specified id. this method returns only a single element.

eg:

<script type="text/javascript">
    function getElements() {
        var x=document.getElementById("y");
        alert(x.value);
    }
</script>
</head>
<body>
    <input name="x" id="y" type="text" size="20" /><br />

This will return a single HTML element and display the value attribute of it.

<script type="text/javascript">
    function getElements() {
        var x=document.getElementsByName("x");
        alert(x.length);
    }
</script>
</head>
<body>
    <input name="x" id="y" type="text" size="20" /><br />
    <input name="x" id="y" type="text" size="20" /><br />

this will return an array of HTML elements and number of elements that match the name attribute.

Extracted from w3schools.

Determine if two rectangles overlap each other?

Ask yourself the opposite question: How can I determine if two rectangles do not intersect at all? Obviously, a rectangle A completely to the left of rectangle B does not intersect. Also if A is completely to the right. And similarly if A is completely above B or completely below B. In any other case A and B intersect.

What follows may have bugs, but I am pretty confident about the algorithm:

struct Rectangle { int x; int y; int width; int height; };

bool is_left_of(Rectangle const & a, Rectangle const & b) {
   if (a.x + a.width <= b.x) return true;
   return false;
}
bool is_right_of(Rectangle const & a, Rectangle const & b) {
   return is_left_of(b, a);
}

bool not_intersect( Rectangle const & a, Rectangle const & b) {
   if (is_left_of(a, b)) return true;
   if (is_right_of(a, b)) return true;
   // Do the same for top/bottom...
 }

bool intersect(Rectangle const & a, Rectangle const & b) {
  return !not_intersect(a, b);
}

How to run PowerShell in CMD

I'd like to add the following to Shay Levy's correct answer: You can make your life easier if you create a little batch script run.cmd to launch your powershell script:

@echo off & setlocal
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC"

Put it in the same path as SQLExecutor.ps1 and from now on you can run it by simply double-clicking on run.cmd.


Note:

  • If you require command line arguments inside the run.cmd batch, simply pass them as %1 ... %9 (or use %* to pass all parameters) to the powershell script, i.e.
    powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*

  • The variable batchPath contains the executing path of the batch file itself (this is what the expression %~dp0 is used for). So you just put the powershell script in the same path as the calling batch file.

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

'-replace' does a regex search and you have special characters in that last one (like +) So you might use the non-regex replace version like this:

$c = $c.replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==')

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I have worked alot with msaccess vba. I think you are looking for MID function

example

    dim myReturn as string
    myreturn = mid("bonjour tout le monde",9,4)

will give you back the value "tout"

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Python datetimes are a little clunky. Use arrow.

> str(arrow.utcnow())
'2014-05-17T01:18:47.944126+00:00'

Arrow has essentially the same api as datetime, but with timezones and some extra niceties that should be in the main library.

A format compatible with Javascript can be achieved by:

arrow.utcnow().isoformat().replace("+00:00", "Z")
'2018-11-30T02:46:40.714281Z'

Javascript Date.parse will quietly drop microseconds from the timestamp.

What's the difference between SoftReference and WeakReference in Java?

Weak Reference http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ref/WeakReference.html

Principle: weak reference is related to garbage collection. Normally, object having one or more reference will not be eligible for garbage collection.
The above principle is not applicable when it is weak reference. If an object has only weak reference with other objects, then its ready for garbage collection.

Let's look at the below example: We have an Map with Objects where Key is reference a object.

import java.util.HashMap;   
public class Test {

    public static void main(String args[]) {
        HashMap<Employee, EmployeeVal> aMap = new 
                       HashMap<Employee, EmployeeVal>();

        Employee emp = new Employee("Vinoth");
        EmployeeVal val = new EmployeeVal("Programmer");

        aMap.put(emp, val);

        emp = null;

        System.gc();
        System.out.println("Size of Map" + aMap.size());

    }
}

Now, during the execution of the program we have made emp = null. The Map holding the key makes no sense here as it is null. In the above situation, the object is not garbage collected.

WeakHashMap

WeakHashMap is one where the entries (key-to-value mappings) will be removed when it is no longer possible to retrieve them from the Map.

Let me show the above example same with WeakHashMap

import java.util.WeakHashMap;

public class Test {

    public static void main(String args[]) {
        WeakHashMap<Employee, EmployeeVal> aMap = 
                    new WeakHashMap<Employee, EmployeeVal>();

        Employee emp = new Employee("Vinoth");
        EmployeeVal val = new EmployeeVal("Programmer");

        aMap.put(emp, val);

        emp = null;

        System.gc();
        int count = 0;
        while (0 != aMap.size()) {
            ++count;
            System.gc();
        }
        System.out.println("Took " + count
                + " calls to System.gc() to result in weakHashMap size of : "
                + aMap.size());
    }
}

Output: Took 20 calls to System.gc() to result in aMap size of : 0.

WeakHashMap has only weak references to the keys, not strong references like other Map classes. There are situations which you have to take care when the value or key is strongly referenced though you have used WeakHashMap. This can avoided by wrapping the object in a WeakReference.

import java.lang.ref.WeakReference;
import java.util.HashMap;

public class Test {

    public static void main(String args[]) {
        HashMap<Employee, EmployeeVal> map = 
                      new HashMap<Employee, EmployeeVal>();
        WeakReference<HashMap<Employee, EmployeeVal>> aMap = 
                       new WeakReference<HashMap<Employee, EmployeeVal>>(
                map);

        map = null;

        while (null != aMap.get()) {
            aMap.get().put(new Employee("Vinoth"),
                    new EmployeeVal("Programmer"));
            System.out.println("Size of aMap " + aMap.get().size());
            System.gc();
        }
        System.out.println("Its garbage collected");
    }
}

Soft References.

Soft Reference is slightly stronger that weak reference. Soft reference allows for garbage collection, but begs the garbage collector to clear it only if there is no other option.

The garbage collector does not aggressively collect softly reachable objects the way it does with weakly reachable ones -- instead it only collects softly reachable objects if it really "needs" the memory. Soft references are a way of saying to the garbage collector, "As long as memory isn't too tight, I'd like to keep this object around. But if memory gets really tight, go ahead and collect it and I'll deal with that." The garbage collector is required to clear all soft references before it can throw OutOfMemoryError.

How to select bottom most rows?

You can use the OFFSET FETCH clause.

SELECT COUNT(1) FROM COHORT; --Number of results to expect

SELECT * FROM COHORT 
ORDER BY ID
OFFSET 900 ROWS --Assuming you expect 1000 rows
FETCH NEXT 100 ROWS ONLY;

(This is for Microsoft SQL Server)

Official documentation: https://www.sqlservertutorial.net/sql-server-basics/sql-server-offset-fetch/

Adding images or videos to iPhone Simulator

The simplest way to get images, videos, etc onto the simulator is to drag and drop them from your computer onto the simulator. This will cause the Simulator to open the Photos app and start populating the library.


If you want a scriptable method, read on.

Note - while this is valid, and works, I think Koen's solution below is now a better one, since it does not require rebooting the simulator.

Identify your simulator by going to xCode->Devices, selecting your simulator, and checking the Identifier value. Or you can ensure the simulator is running and run the following to get the device ID xcrun simctl list | grep Booted

Go to

~/Library/Developer/CoreSimulator/Devices/[Simulator Identifier]/data/Media/DCIM/100APPLE

and add IMG_nnnn.THM and IMG_nnnn.JPG. You will then need to reset your simulator (Hardware->Reboot) to allow it to notice the new changes. It doesn't matter if they are not JPEGs - they can both be PNGs, but it appears that both of them must be present for it to work. You may need to create DCIM if it doesn't already exist, and in that case you should start nnnn from 0001. The JPG files are the fullsize version, while the THM files are the thumbnail, and are 75x75 pixels in size. I wrote a script to do this, but there's a better documented one over here(-link no longer work).

You can also add photos from safari in the simulator, by Tapping and Holding on the image. If you drag an image (or any other file, like a PDF) to the simulator, it will immediately open Safari and display the image, so this is quite an easy way of getting images to it.

Xcode variables

The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.

Excel Validation Drop Down list using VBA

You are defining your array as xlValidateList(), so when you try to assign the type, it gets confused as to what you are trying to assign to the type.

Instead, try this:

Dim MyList(5) As String
MyList(0) = 1
MyList(1) = 2
MyList(2) = 3
MyList(3) = 4
MyList(4) = 5
MyList(5) = 6

With Range("A1").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
         Operator:=xlBetween, Formula1:=Join(MyList, ",")
End With

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd/mm/yy format.

select  LEFT(convert(varchar(10), @date, 103),6) + Right(Year(@date)+ 1,2)

How can I stop a While loop?

just indent your code correctly:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            return period
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            return 0
        else:   
            return period

You need to understand that the break statement in your example will exit the infinite loop you've created with while True. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break statement by a return statement.

Following your idea to use an infinite loop, this is the best way to write it:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            break
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            period = 0
            break

    return period

MySQL select rows where left join is null

One of the best approach if you do not want to return any columns from table2 is to use the NOT EXISTS

SELECT  table1.id 
FROM    table1 T1
WHERE
  NOT EXISTS (SELECT *
              FROM table2 T2
              WHERE T1.id = T2.user_one
                  OR T1.id = T2.user_two)

Semantically this says what you want to query: Select every row where there is no matching record in the second table.

MySQL is optimized for EXISTS: It returns as soon as it finds the first matching record.

Error: Local workspace file ('angular.json') could not be found

Check your folder structure where you are executing the command, you should run the command 'ng serve' where there should be a angular.json file in the structure.

angular.json file will be generated by default when we run the command

npm install -g '@angular/cli' ng new Project_name then cd project_folder then, run ng serve. it worked for me

How do I disable text selection with CSS or JavaScript?

Try this CSS code for cross-browser compatibility.

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;

How to use android emulator for testing bluetooth application?

You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

  • No support for placing or receiving actual phone calls. However, You can simulate phone calls (placed and received) through the emulator console
  • No support for USB
  • No support for device-attached headphones
  • No support for determining SD card insert/eject
  • No support for WiFi, Bluetooth, NFC

Refer to the documentation

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.

int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();

Hope this answers the question.

AngularJS - Animate ng-view transitions

Try checking his post. It shows how to implement transitions between web pages using AngularJS's ngRoute and ngAnimate: How to Make iPhone-Style Web Page Transitions Using AngularJS & CSS

Can I change the Android startActivity() transition animation?

Starting from API level 5 you can call overridePendingTransition immediately to specify an explicit transition animation:

startActivity();
overridePendingTransition(R.anim.hold, R.anim.fade_in);

or

finish();
overridePendingTransition(R.anim.hold, R.anim.fade_out);

How to pull specific directory with git

If you want to get the latest changes in a directory without entering it, you can do:

$ git -C <Path to directory> pull

How to return a custom object from a Spring Data JPA GROUP BY query

@Repository
public interface ExpenseRepo extends JpaRepository<Expense,Long> {
    List<Expense> findByCategoryId(Long categoryId);

    @Query(value = "select category.name,SUM(expense.amount) from expense JOIN category ON expense.category_id=category.id GROUP BY expense.category_id",nativeQuery = true)
    List<?> getAmountByCategory();

}

The above code worked for me.

How to interpolate variables in strings in JavaScript, without concatenation?

Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no. Although you could try sprintf for JavaScript to get halfway there:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);

How to remove text from a string?

Plain old JavaScript will suffice - jQuery is not necessary for such a simple task:

var myString = "data-123";
var myNewString = myString.replace("data-", "");

See: .replace() docs on MDN for additional information and usage.

what is the use of $this->uri->segment(3) in codeigniter pagination

By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0);

It helps avoid having to write code like this:

[if ($this->uri->segment(3) === FALSE)
{
    $product_id = 0;
}
else
{
    $product_id = $this->uri->segment(3);
}]

Service Temporarily Unavailable Magento?

You can do this thing:

Go to http://localhost/magento/downloader url. Here I am running the magento store on my localhost. Now you can login to magento connect manager and uninstall the extension which you installed previously.

Hope this works !!!!!

Thanks.

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

Some applications like skype uses wamp's default port:80 so you have to find out which application is accessing this port you can easily find it by using TCP View. End the service accessing this port and restart wamp server. Now it will work.

Why doesn't Java offer operator overloading?

James Gosling likened designing Java to the following:

"There's this principle about moving, when you move from one apartment to another apartment. An interesting experiment is to pack up your apartment and put everything in boxes, then move into the next apartment and not unpack anything until you need it. So you're making your first meal, and you're pulling something out of a box. Then after a month or so you've used that to pretty much figure out what things in your life you actually need, and then you take the rest of the stuff -- forget how much you like it or how cool it is -- and you just throw it away. It's amazing how that simplifies your life, and you can use that principle in all kinds of design issues: not do things just because they're cool or just because they're interesting."

You can read the context of the quote here

Basically operator overloading is great for a class that models some kind of point, currency or complex number. But after that you start running out of examples fast.

Another factor was the abuse of the feature in C++ by developers overloading operators like '&&', '||', the cast operators and of course 'new'. The complexity resulting from combining this with pass by value and exceptions is well covered in the Exceptional C++ book.

Full-screen iframe with a height of 100%

Here is a concise code. It does relies on a jquery method to find the current window height. On load of iFrame it sets the height of the iframe be the same as the current window. Then to handle resizing of the page, the body tag has an onresize event handler which sets the iframe's height whenever the document is resized.

<html>
<head>
    <title>my I frame is as tall as your page</title>
     <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body onresize="$('#iframe1').attr('height', $(window).height());" style="margin:0;" >
    <iframe id="iframe1" src="yourpage.html" style="width:100%;"  onload="this.height=$(window).height();"></iframe>
</body>
</html>

here's a working sample: http://jsbin.com/soqeq/1/

Auto-center map with multiple markers in Google Maps API v3

I think you have to calculate latitudine min and longitude min: Here is an Example with the function to use to center your point:

//Example values of min & max latlng values
var lat_min = 1.3049337;
var lat_max = 1.3053515;
var lng_min = 103.2103116;
var lng_max = 103.8400188;

map.setCenter(new google.maps.LatLng(
  ((lat_max + lat_min) / 2.0),
  ((lng_max + lng_min) / 2.0)
));
map.fitBounds(new google.maps.LatLngBounds(
  //bottom left
  new google.maps.LatLng(lat_min, lng_min),
  //top right
  new google.maps.LatLng(lat_max, lng_max)
));

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

I found the solution to the problem of serializing entities was as follows:

#config/config.yml

services:
    serializer.method:
        class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
    serializer.encoder.json:
        class: Symfony\Component\Serializer\Encoder\JsonEncoder
    serializer:
        class: Symfony\Component\Serializer\Serializer
        arguments:
            - [@serializer.method]
            - {json: @serializer.encoder.json }

in my controller:

$serializer = $this->get('serializer');

$entity = $this->get('doctrine')
               ->getRepository('myBundle:Entity')
               ->findOneBy($params);


$collection = $this->get('doctrine')
               ->getRepository('myBundle:Entity')
               ->findBy($params);

$toEncode = array(
    'response' => array(
        'entity' => $serializer->normalize($entity),
        'entities' => $serializer->normalize($collection)
    ),
);

return new Response(json_encode($toEncode));

other example:

$serializer = $this->get('serializer');

$collection = $this->get('doctrine')
               ->getRepository('myBundle:Entity')
               ->findBy($params);

$json = $serializer->serialize($collection, 'json');

return new Response($json);

you can even configure it to deserialize arrays in http://api.symfony.com/2.0

How to keep an iPhone app running on background fully operational

For running on stock iOS devices, make your app an audio player/recorder or a VOIP app, a legitimate one for submitting to the App store, or a fake one if only for your own use.

Even this won't make an app "fully operational" whatever that is, but restricted to limited APIs.

Remove CSS from a Div using JQuery

You can remove inline properties this way:

$(selector).css({'property':'', 'property':''});

For example:

$(actpar).css({'top':'', 'opacity':''});

This is essentially mentioned above, and it definitely does the trick.

BTW, this is useful in instances such as when you need to clear a state after animation. Sure I could write a half dozen classes to deal with this, or I could use my base class and #id do some math, and clear the inline style that the animation applies.

$(actpar).animate({top:0, opacity:1, duration:500}, function() {
   $(this).css({'top':'', 'opacity':''});
});

Static extension methods

No, but you could have something like:

bool b;
b = b.YourExtensionMethod();

How to properly set the 100% DIV height to match document/window height?

why don't you use width: 100% and height: 100%.

Could not complete the operation due to error 80020101. IE

Switch off compatibility view if you use IE9.

Java: how to convert HashMap<String, Object> to array

If you want the keys and values, you can always do this via the entrySet:

hashMap.entrySet().toArray(); // returns a Map.Entry<K,V>[]

From each entry you can (of course) get both the key and value via the getKey and getValue methods

CharSequence VS String in Java?

An issue that DO arise in practical Android code is that comparing them with CharSequence.equals is valid but does not necessarily work as intended.

EditText t = (EditText )getView(R.id.myEditText); // Contains "OK"
Boolean isFalse = t.getText().equals("OK"); // will always return false.

Comparison should be made by

("OK").contentEquals(t.GetText()); 

Command to change the default home directory of a user

Found out that this breaks some applications, the better way to do it is

In addition to symlink, on more recent distros and filesystems, as root you can also use bind-mount:

mkdir /home/username 
mount --bind --verbose /extra-home/username /home/username

This is useful for allowing access "through" the /home directory to subdirs via daemons that are otherwise configured to avoid pathing through symlinks (apache, ftpd, etc.).

You have to remember (or init script) to bind upon restarts, of course.

An example init script in /etc/fstab is

/extra-home/username /home/username none defaults,bind 0 0

Remove composer

During the installation you got a message Composer successfully installed to: ... this indicates where Composer was installed. But you might also search for the file composer.phar on your system.

Then simply:

  1. Delete the file composer.phar.
  2. Delete the Cache Folder:
    • Linux: /home/<user>/.composer
    • Windows: C:\Users\<username>\AppData\Roaming\Composer

That's it.

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

Is it possible to display my iPhone on my computer monitor?

Do not we have an app which can stream the digital movie from iOS devices like iPhone or iPad to be played on a high definition LED or Plasma TV?

I know of an app air video server which can be used to display content played on computer or laptop on iOS device. But is there any app that can do the reverse & play the digital content from iphone to LED tv .

How to set True as default value for BooleanField on Django?

from django.db import models

class Foo(models.Model):
    any_field = models.BooleanField(default=True)

CSS to make table 100% of max-width

Like this

demo

css

table{
    width:100%;
}

How to set up Android emulator proxy settings

Now there is a setting in Android emulator enter image description here

Multi-Line Comments in Ruby?

Despite the existence of =begin and =end, the normal and a more correct way to comment is to use #'s on each line. If you read the source of any ruby library, you will see that this is the way multi-line comments are done in almost all cases.

How to set minDate to current date in jQuery UI Datepicker?

can also use:

$("input.DateFrom").datepicker({
    minDate: 'today'
});

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

How do I make background-size work in IE?

you can use this file (https://github.com/louisremi/background-size-polyfill “background-size polyfill”) for IE8 that is really simple to use:

.selector {
background-size: cover;
-ms-behavior: url(/backgroundsize.min.htc);
}

Initialize value of 'var' in C# to null

The var keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var keyword has a type. For instance, you'll find that the following code outputs "String".

var myString = "";
Console.Write(myString.GetType().Name);

Furthermore, the code above is equivalent to:

String myString = "";
Console.Write(myString.GetType().Name);

The var keyword is simply C#'s way of saying "I can figure out the type for myString from the context, so don't worry about specifying the type."

var myVariable = (MyType)null or MyType myVariable = null should work because you are giving the C# compiler context to figure out what type myVariable should will be.

For more information:

Display all post meta keys and meta values of the same post ID in wordpress

WordPress have the function get_metadata this get all meta of object (Post, term, user...)

Just use

get_metadata( 'post', 15 );

How to add Class in <li> using wp_nav_menu() in Wordpress?

use this filter nav_menu_css_class as shown below

function add_classes_on_li($classes, $item, $args) {
    $classes[] = 'nav-item';
    return $classes;
}
add_filter('nav_menu_css_class','add_classes_on_li',1,3);

UPDATE

To use this filter with specific menu

if ( 'main-menu' === $args->theme_location ) { //replace main-menu with your menu
    $classes[] = "nav-item"; 
}

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


What is the purpose of global.asax in asp.net

The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application

How to to send mail using gmail in Laravel?

in bluehost i could not reset password; with this driver worked:

MAIL_DRIVER=sendmail

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

Run CMD in administrator mode 1.bcdedit 2.bcdedit /set hypervisorlaunchtype off 3.Reboot system

This worked for me!!

Adding and removing extensionattribute to AD object

To clear the value you can always reset it to $Null. For example:

Set-Mailbox -Identity "username" -CustomAttribute1 $Null

Python Sets vs Lists

I was interested in the results when checking, with CPython, if a value is one of a small number of literals. set wins in Python 3 vs tuple, list and or:

from timeit import timeit

def in_test1():
  for i in range(1000):
    if i in (314, 628):
      pass

def in_test2():
  for i in range(1000):
    if i in [314, 628]:
      pass

def in_test3():
  for i in range(1000):
    if i in {314, 628}:
      pass

def in_test4():
  for i in range(1000):
    if i == 314 or i == 628:
      pass

print("tuple")
print(timeit("in_test1()", setup="from __main__ import in_test1", number=100000))
print("list")
print(timeit("in_test2()", setup="from __main__ import in_test2", number=100000))
print("set")
print(timeit("in_test3()", setup="from __main__ import in_test3", number=100000))
print("or")
print(timeit("in_test4()", setup="from __main__ import in_test4", number=100000))

Output:

tuple
4.735646052286029
list
4.7308746771886945
set
3.5755991376936436
or
4.687681658193469

For 3 to 5 literals, set still wins by a wide margin, and or becomes the slowest.

In Python 2, set is always the slowest. or is the fastest for 2 to 3 literals, and tuple and list are faster with 4 or more literals. I couldn't distinguish the speed of tuple vs list.

When the values to test were cached in a global variable out of the function, rather than creating the literal within the loop, set won every time, even in Python 2.

These results apply to 64-bit CPython on a Core i7.

Example: Communication between Activity and Service using Messaging

Everything is fine.Good example of activity/service communication using Messenger.

One comment : the method MyService.isRunning() is not required.. bindService() can be done any number of times. no harm in that.

If MyService is running in a different process then the static function MyService.isRunning() will always return false. So there is no need of this function.

Android emulator: could not get wglGetExtensionsStringARB error

i had a same issue because of my Nvidea Graphics card Driver Problem.

If your System has Dedicated Graphics card then Check for the latest Driver and Install it.

Other wise simply Choose Emulated Performance as Software in Emulator Configurations enter image description here

After Updating the driver the issue is resolved :)

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

How to get all registered routes in Express?

A function to log all routes in express 4 (can be easily tweaked for v3~)

function space(x) {
    var res = '';
    while(x--) res += ' ';
    return res;
}

function listRoutes(){
    for (var i = 0; i < arguments.length;  i++) {
        if(arguments[i].stack instanceof Array){
            console.log('');
            arguments[i].stack.forEach(function(a){
                var route = a.route;
                if(route){
                    route.stack.forEach(function(r){
                        var method = r.method.toUpperCase();
                        console.log(method,space(8 - method.length),route.path);
                    })
                }
            });
        }
    }
}

listRoutes(router, routerAuth, routerHTML);

Logs output:

GET       /isAlive
POST      /test/email
POST      /user/verify

PUT       /login
POST      /login
GET       /player
PUT       /player
GET       /player/:id
GET       /players
GET       /system
POST      /user
GET       /user
PUT       /user
DELETE    /user

GET       /
GET       /login

Made this into a NPM https://www.npmjs.com/package/express-list-routes

Unzip a file with php

Just change

system('unzip $master.zip');

To this one

system('unzip ' . $master . '.zip');

or this one

system("unzip {$master}.zip");

How to find where gem files are installed

You can check it from your command prompt by running gem help commands and then selecting the proper command:

kirti@kirti-Aspire-5733Z:~$  gem help commands
GEM commands are:

    build                  Build a gem from a gemspec
    cert                   Manage RubyGems certificates and signing settings
    check                  Check a gem repository for added or missing files
    cleanup                Clean up old versions of installed gems in the local
                           repository
    contents               Display the contents of the installed gems
    dependency             Show the dependencies of an installed gem
    environment            Display information about the RubyGems environment
    fetch                  Download a gem and place it in the current directory
    generate_index         Generates the index files for a gem server directory
    help                   Provide help on the 'gem' command
    install                Install a gem into the local repository
    list                   Display gems whose name starts with STRING
    lock                   Generate a lockdown list of gems
    mirror                 Mirror all gem files (requires rubygems-mirror)
    outdated               Display all gems that need updates
    owner                  Manage gem owners on RubyGems.org.
    pristine               Restores installed gems to pristine condition from
                           files located in the gem cache
    push                   Push a gem up to RubyGems.org
    query                  Query gem information in local or remote repositories
    rdoc                   Generates RDoc for pre-installed gems
    regenerate_binstubs    Re run generation of executable wrappers for gems.
    search                 Display all gems whose name contains STRING
    server                 Documentation and gem repository HTTP server
    sources                Manage the sources and cache file RubyGems uses to
                           search for gems
    specification          Display gem specification (in yaml)
    stale                  List gems along with access times
    uninstall              Uninstall gems from the local repository
    unpack                 Unpack an installed gem to the current directory
    update                 Update installed gems to the latest version
    which                  Find the location of a library file you can require
    yank                   Remove a specific gem version release from
                           RubyGems.org

For help on a particular command, use 'gem help COMMAND'.

Commands may be abbreviated, so long as they are unambiguous.
e.g. 'gem i rake' is short for 'gem install rake'.
kirti@kirti-Aspire-5733Z:~$ 

Now from the above I can see the command environment is helpful. So I would do:

kirti@kirti-Aspire-5733Z:~$ gem help environment
Usage: gem environment [arg] [options]


  Common Options:
    -h, --help                       Get help on this command
    -V, --[no-]verbose               Set the verbose level of output
    -q, --quiet                      Silence commands
        --config-file FILE           Use this config file instead of default
        --backtrace                  Show stack backtrace on errors
        --debug                      Turn on Ruby debugging


  Arguments:
    packageversion  display the package version
    gemdir          display the path where gems are installed
    gempath         display path used to search for gems
    version         display the gem format version
    remotesources   display the remote gem servers
    platform        display the supported gem platforms
    <omitted>       display everything

  Summary:
    Display information about the RubyGems environment

  Description:
    The RubyGems environment can be controlled through command line arguments,
    gemrc files, environment variables and built-in defaults.

    Command line argument defaults and some RubyGems defaults can be set in a
    ~/.gemrc file for individual users and a /etc/gemrc for all users. These
    files are YAML files with the following YAML keys:

      :sources: A YAML array of remote gem repositories to install gems from
      :verbose: Verbosity of the gem command. false, true, and :really are the
                levels
      :update_sources: Enable/disable automatic updating of repository metadata
      :backtrace: Print backtrace when RubyGems encounters an error
      :gempath: The paths in which to look for gems
      :disable_default_gem_server: Force specification of gem server host on
    push
      <gem_command>: A string containing arguments for the specified gem command

    Example:

      :verbose: false
      install: --no-wrappers
      update: --no-wrappers
      :disable_default_gem_server: true

    RubyGems' default local repository can be overridden with the GEM_PATH and
    GEM_HOME environment variables. GEM_HOME sets the default repository to
    install into. GEM_PATH allows multiple local repositories to be searched for
    gems.

    If you are behind a proxy server, RubyGems uses the HTTP_PROXY,
    HTTP_PROXY_USER and HTTP_PROXY_PASS environment variables to discover the
    proxy server.

    If you would like to push gems to a private gem server the RUBYGEMS_HOST
    environment variable can be set to the URI for that server.

    If you are packaging RubyGems all of RubyGems' defaults are in
    lib/rubygems/defaults.rb.  You may override these in
    lib/rubygems/defaults/operating_system.rb
kirti@kirti-Aspire-5733Z:~$ 

Finally to show you what you asked, I would do:

kirti@kirti-Aspire-5733Z:~$ gem environment gemdir
/home/kirti/.rvm/gems/ruby-2.0.0-p0
kirti@kirti-Aspire-5733Z:~$ gem environment gempath
/home/kirti/.rvm/gems/ruby-2.0.0-p0:/home/kirti/.rvm/gems/ruby-2.0.0-p0@global
kirti@kirti-Aspire-5733Z:~$ 

Finding first blank row, then writing to it

ActiveSheet.Range("A10000").End(xlup).offset(1,0).Select

Get user's non-truncated Active Directory groups from command line

Or you could use dsquery and dsget:

dsquery user domainroot -name <userName> | dsget user -memberof

To retrieve group memberships something like this:

Tue 09/10/2013 13:17:41.65
C:\
>dsquery user domainroot -name jqpublic | dsget user -memberof
"CN=Technical Support Staff,OU=Acme,OU=Applications,DC=YourCompany,DC=com"
"CN=Technical Support Staff,OU=Contosa,OU=Applications,DC=YourCompany,DC=com"
"CN=Regional Administrators,OU=Workstation,DC=YourCompany,DC=com"

Although I can't find any evidence that I ever installed this package on my computer, you might need to install the Remote Server Administration Tools for Windows 7.

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

Shared folder between MacOSX and Windows on Virtual Box

At first I was stuck trying to figure out out to "insert" the Guest Additions CD image in Windows because I presumed it was a separate download that I would have to mount or somehow attach to the virtual CD drive. But just going through the Mac VirtualBox Devices menu and picking "Insert Guest Additions CD Image..." seemed to do the trick. Nothing to mount, nothing to "insert".

Elsewhere I found that the Guest Additions update was part of the update package, so I guess the new VB found the new GA CD automatically when Windows went looking. I wish I had known that to start.

Also, it appears that when I installed the Guest Additions on my Linked Base machine, it propagated to the other machines that were based on it. Sweet. Only one installation for multiple "machines".

I still haven't found that documented, but it appears to be the case (probably I'm not looking for the right explanation terms because I don't already know the explanation). How that works should probably be a different thread.

How to write log base(2) in c/c++

Consult your basic mathematics course, log n / log 2. It doesn't matter whether you choose log or log10in this case, dividing by the log of the new base does the trick.

Can there exist two main methods in a Java program?

The below code in file "Locomotive.java" will compile and run successfully, with the execution results showing

2<SPACE>

As mentioned in above post, the overload rules still work for the main method. However, the entry point is the famous psvm (public static void main(String[] args))

public class Locomotive {
    Locomotive() { main("hi");}

    public static void main(String[] args) {
        System.out.print("2 ");
    }

    public static void main(String args) {
        System.out.print("3 " + args);
    }
}

Using SSH keys inside docker container

A concise overview of the challenges of SSH inside Docker containers is detailed here. For connecting to trusted remotes from within a container without leaking secrets there are a few ways:

Beyond these there's also the possibility of using a key-store running in a separate docker container accessible at runtime when using Compose. The drawback here is additional complexity due to the machinery required to create and manage a keystore such as Vault by HashiCorp.

For SSH key use in a stand-alone Docker container see the methods linked above and consider the drawbacks of each depending on your specific needs. If, however, you're running inside Compose and want to share a key to an app at runtime (reflecting practicalities of the OP) try this:

  • Create a docker-compose.env file and add it to your .gitignore file.
  • Update your docker-compose.yml and add env_file for service requiring the key.
  • Access public key from environment at application runtime, e.g. process.node.DEPLOYER_RSA_PUBKEY in the case of a Node.js application.

The above approach is ideal for development and testing and, while it could satisfy production requirements, in production you're better off using one of the other methods identified above.

Additional resources:

Cannot execute RUN mkdir in a Dockerfile

The problem is that /var/www doesn't exist either, and mkdir isn't recursive by default -- it expects the immediate parent directory to exist.

Use:

mkdir -p /var/www/app

...or install a package that creates a /var/www prior to reaching this point in your Dockerfile.

Is there a typescript List<> and/or Map<> class/library?

Did they add a runtime List<> and/or Map<> type class to typepad 1.0

No, providing a runtime is not the focus of the TypeScript team.

is there a solid library out there someone wrote that provides this functionality?

I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections

Update

JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts : https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want

Have log4net use application config file for configuration data

From the config shown in the question there is but one appender configured and it is named "EventLogAppender". But in the config for root, the author references an appender named "ConsoleAppender", hence the error message.

Best XML Parser for PHP

Hi I think the SimpleXml is very useful . And with it I am using xpath;

$xml = simplexml_load_file("som_xml.xml");

$blocks  = $xml->xpath('//block'); //gets all <block/> tags
$blocks2 = $xml->xpath('//layout/block'); //gets all <block/> which parent are   <layout/>  tags

I use many xml configs and this helps me to parse them really fast. SimpleXml is written on C so it's very fast.

jQuery: value.attr is not a function

Contents of that jQuery object are plain DOM elements, which doesn't respond to jQuery methods (e.g. .attr). You need to wrap the value by $() to turn it into a jQuery object to use it.

    console.info("cat_id: ", $(value).attr('cat_id'));

or just use the DOM method directly

    console.info("cat_id: ", value.getAttribute('cat_id'));

form action with javascript

I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:

action="javascript:checkout()"

You try this?

Don't forget include the script reference in the html head.

I don't know cause of that works in firefox. Regards.

How can I convert a .py to .exe for Python?

I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.

Here's the pypi https://pypi.python.org/pypi/cx_Freeze

The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html

I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.

How do I use cx_freeze?

Get column index from label in a data frame

This seems to be an efficient way to list vars with column number:

cbind(names(df)) 

Output:

     [,1]
[1,] "A" 
[2,] "B" 
[3,] "C" 

Sometimes I like to copy variables with position into my code so I use this function:

varnums<- function(x) {w=as.data.frame(c(1:length(colnames(x))),
          paste0('# ',colnames(x)))
names(w)= c("# Var/Pos")
w}
varnums(df)

Output:

# Var/Pos
# A         1
# B         2
# C         3

How to create jobs in SQL Server Express edition

SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.

What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:

backup.bat:

sqlcmd -i backup.sql

backup.sql:

backup database TeamCity to disk = 'c:\backups\MyBackup.bak'

Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.

The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE queries instead.


If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.

It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:

How do I get started with the SQL Server Maintenance Solution on SQL Server Express?

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

  1. Download MaintenanceSolution.sql.

  2. Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.

  3. Create cmd files to execute the stored procedures; for example:
    sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txt

  4. In Windows Scheduled Tasks, create tasks to call the cmd files.

  5. Schedule the tasks.

  6. Start the tasks and verify that they are completing successfully.

TypeScript: correct way to do string equality?

The === is not for checking string equalit , to do so you can use the Regxp functions for example

if (x.match(y) === null) {
// x and y are not equal 
}

there is also the test function

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host: git.eclipse.org
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

Array functions in jQuery

You can use Underscore.js. It really makes things simple.

For example, removing elements from an array, you need to do:

_.without([1, 2, 3], 2);

And the result will be [1, 3].

It reduces the code that you write using jQuery.grep, etc. in jQuery.

are there dictionaries in javascript like python?

Have created a simple dictionary in JS here:

function JSdict() {
    this.Keys = [];
    this.Values = [];
}

// Check if dictionary extensions aren't implemented yet.
// Returns value of a key
if (!JSdict.prototype.getVal) {
    JSdict.prototype.getVal = function (key) {
        if (key == null) {
            return "Key cannot be null";
        }
        for (var i = 0; i < this.Keys.length; i++) {
            if (this.Keys[i] == key) {
                return this.Values[i];
            }
        }
        return "Key not found!";
    }
}


// Check if dictionary extensions aren't implemented yet.
// Updates value of a key
if (!JSdict.prototype.update) {
    JSdict.prototype.update = function (key, val) {
        if (key == null || val == null) {
            return "Key or Value cannot be null";
        }
        // Verify dict integrity before each operation
        if (keysLength != valsLength) {
            return "Dictionary inconsistent. Keys length don't match values!";
        }
        var keysLength = this.Keys.length;
        var valsLength = this.Values.length;
        var flag = false;
        for (var i = 0; i < keysLength; i++) {
            if (this.Keys[i] == key) {
                this.Values[i] = val;
                flag = true;
                break;
            }
        }
        if (!flag) {
            return "Key does not exist";
        }
    }
}



// Check if dictionary extensions aren't implemented yet.
// Adds a unique key value pair
if (!JSdict.prototype.add) {
    JSdict.prototype.add = function (key, val) {
        // Allow only strings or numbers as keys
        if (typeof (key) == "number" || typeof (key) == "string") {
            if (key == null || val == null) {
                return "Key or Value cannot be null";
            }
            if (keysLength != valsLength) {
                return "Dictionary inconsistent. Keys length don't match values!";
            }
            var keysLength = this.Keys.length;
            var valsLength = this.Values.length;
            for (var i = 0; i < keysLength; i++) {
                if (this.Keys[i] == key) {
                    return "Duplicate keys not allowed!";
                }
            }
            this.Keys.push(key);
            this.Values.push(val);
        }
        else {
            return "Only number or string can be key!";
        }
    }
}

// Check if dictionary extensions aren't implemented yet.
// Removes a key value pair
if (!JSdict.prototype.remove) {
    JSdict.prototype.remove = function (key) {
        if (key == null) {
            return "Key cannot be null";
        }
        if (keysLength != valsLength) {
            return "Dictionary inconsistent. Keys length don't match values!";
        }
        var keysLength = this.Keys.length;
        var valsLength = this.Values.length;
        var flag = false;
        for (var i = 0; i < keysLength; i++) {
            if (this.Keys[i] == key) {
                this.Keys.shift(key);
                this.Values.shift(this.Values[i]);
                flag = true;
                break;
            }
        }
        if (!flag) {
            return "Key does not exist";
        }
    }
}

The above implementation can now be used to simulate a dictionary as:

var dict = new JSdict();

dict.add(1, "one")

dict.add(1, "one more")
"Duplicate keys not allowed!"

dict.getVal(1)
"one"

dict.update(1, "onne")

dict.getVal(1)
"onne"

dict.remove(1)

dict.getVal(1)
"Key not found!"

This is just a basic simulation. It can be further optimized by implementing a better running time algorithm to work in atleast O(nlogn) time complexity or even less. Like merge/quick sort on arrays and then some B-search for lookups. I Didn't give a try or searched about mapping a hash function in JS.

Also, Key and Value for the JSdict obj can be turned into private variables to be sneaky.

Hope this helps!

EDIT >> After implementing the above, I personally used the JS objects as associative arrays that are available out-of-the-box.

However, I would like to make a special mention about two methods that actually proved helpful to make it a convenient hashtable experience.

Viz: dict.hasOwnProperty(key) and delete dict[key]

Read this post as a good resource on this implementation/usage. Dynamically creating keys in JavaScript associative array

THanks!

Detecting TCP Client Disconnect

In TCP there is only one way to detect an orderly disconnect, and that is by getting zero as a return value from read()/recv()/recvXXX() when reading.

There is also only one reliable way to detect a broken connection: by writing to it. After enough writes to a broken connection, TCP will have done enough retries and timeouts to know that it's broken and will eventually cause write()/send()/sendXXX() to return -1 with an errno/WSAGetLastError() value of ECONNRESET, or in some cases 'connection timed out'. Note that the latter is different from 'connect timeout', which can occur in the connect phase.

You should also set a reasonable read timeout, and drop connections that fail it.

The answer here about ioctl() and FIONREAD is compete nonsense. All that does is tell you how many bytes are presently in the socket receive buffer, available to be read without blocking. If a client doesn't send you anything for five minutes that doesn't constitute a disconnect, but it does cause FIONREAD to be zero. Not the same thing: not even close.

Java - escape string to prevent SQL injection

If really you can't use Defense Option 1: Prepared Statements (Parameterized Queries) or Defense Option 2: Stored Procedures, don't build your own tool, use the OWASP Enterprise Security API. From the OWASP ESAPI hosted on Google Code:

Don’t write your own security controls! Reinventing the wheel when it comes to developing security controls for every web application or web service leads to wasted time and massive security holes. The OWASP Enterprise Security API (ESAPI) Toolkits help software developers guard against security-related design and implementation flaws.

For more details, see Preventing SQL Injection in Java and SQL Injection Prevention Cheat Sheet.

Pay a special attention to Defense Option 3: Escaping All User Supplied Input that introduces the OWASP ESAPI project).

Select default option value from typescript angular 6

You can do this:

<select  class='form-control' 
        (change)="ChangingValue($event)" [value]='46'>
  <option value='47'>47</option>
  <option value='46'>46</option>
  <option value='45'>45</option>
</select>

// Note: You can set the value of select only from options tag. In the above example, you cannot set the value of select to anything other than 45, 46, 47.

Here, you can ply with this.

Git commit in terminal opens VIM, but can't get back to terminal

Simply doing the vim "save and quit" command :wq should do the trick.

In order to have Git open it in another editor, you need to change the Git core.editor setting to a command which runs the editor you want.

git config --global core.editor "command to start sublime text 2"

Excel - match data from one range to another and get the value from the cell to the right of the matched data

Put this formula in cell d31 and copy down to d39

 =iferror(vlookup(b31,$f$3:$g$12,2,0),"")

Here's what is going on. VLOOKUP:

  • Takes a value (here the contents of b31),
  • Looks for it in the first column of a range (f3:f12 in the range f3:g12), and
  • Returns the value for the corresponding row in a column in that range (in this case, the 2nd column or g3:g12 of the range f3:g12).

As you know, the last argument of VLOOKUP sets the match type, with FALSE or 0 indicating an exact match.

Finally, IFERROR handles the #N/A when VLOOKUP does not find a match.

Using sed and grep/egrep to search and replace

try something using a for loop

 for i in `egrep -lR "YOURSEARCH" .` ; do echo  $i; sed 's/f/k/' <$i >/tmp/`basename $i`; mv /tmp/`basename $i` $i; done

not pretty, but should do.

Can't change table design in SQL Server 2008

Prevent saving changes that require table re-creation

Five swift clicks

Prevent saving changes that require table re-creation in five clicks

  1. Tools
  2. Options
  3. Designers
  4. Prevent saving changes that require table re-creation
  5. OK.

After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.

Further explanation

  • By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*

  • When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.

*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.

Div 100% height works on Firefox but not in IE

Its hard to give you a good answer, without seeing the html that you are actually using.

Are you outputting a doctype / using standards mode rendering? Without actually being able to look into a html repro, that would be my first guess for a html interpretation difference between firefox and internet explorer.

For files in directory, only echo filename (no path)

if you want filename only :

for file in /home/user/*; do       
  f=$(echo "${file##*/}");
  filename=$(echo $f| cut  -d'.' -f 1); #file has extension, it return only filename
  echo $filename
done

for more information about cut command see here.

Swift: Display HTML data in a label or textView

Swift 5

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
            documentAttributes: nil) else { return nil }
        return html
    }
}

Call:

myLabel.attributedText = "myString".htmlAttributedString()

Access-control-allow-origin with multiple domains

You can add this code to your asp.net webapi project

in file Global.asax

    protected void Application_BeginRequest()
{
    string origin = Request.Headers.Get("Origin");
    if (Request.HttpMethod == "OPTIONS")
    {
        Response.AddHeader("Access-Control-Allow-Origin", origin);
        Response.AddHeader("Access-Control-Allow-Headers", "*");
        Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
        Response.StatusCode = 200;
        Response.End();
    }
    else
    {
        Response.AddHeader("Access-Control-Allow-Origin", origin);
        Response.AddHeader("Access-Control-Allow-Headers", "*");
        Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
    }
}

Using Image control in WPF to display System.Drawing.Bitmap

According to http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/

   [DllImport("gdi32")]
   static extern int DeleteObject(IntPtr o);

   public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
   {
       IntPtr ip = source.GetHbitmap();
       BitmapSource bs = null;
       try
       {
           bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, 
              IntPtr.Zero, Int32Rect.Empty, 
              System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
       }
       finally
       {
           DeleteObject(ip);
       }

       return bs;
   }

It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF.

image1.Source = YourUtilClass.loadBitmap(SomeBitmap);

Explain ggplot2 warning: "Removed k rows containing missing values"

Even if your data falls within your specified limits (e.g. c(0, 335)), adding a geom_jitter() statement could push some points outside those limits, producing the same error message.

library(ggplot2)

range(mtcars$hp)
#> [1]  52 335

# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) + 
    geom_point() +
    scale_y_continuous(limits=c(0,335))


# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) + 
    geom_point() +
    geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
    scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).

Created on 2020-08-24 by the reprex package (v0.3.0)

Adding a Time to a DateTime in C#

You can use the DateTime.Add() method to add the time to the date.

DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);

You can also create your timespan by parsing a String, if that is what you need to do.

Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.

Calculating and printing the nth prime number

Although many correct and detailed explanations are available. but here is my C implementation:

#include<stdio.h>
#include<conio.h> 

main()
{
int pk,qd,am,no,c=0;
printf("\n Enter the Number U want to Find");
scanf("%d",&no);
for(pk=2;pk<=1000;pk++)
{
am=0;
for(qd=2;qd<=pk/2;qd++)
{
if(pk%qd==0)
{
am=1;
break;
}}
if(am==0)
c++;
if(c==no)
{
printf("%d",pk);
break;
}}
getch();
return 0;
}

View tabular file such as CSV from command line

I used pisswillis's answer for a long time.

csview()
{
    local file="$1"
    sed "s/,/\t/g" "$file" | less -S
}

But then combined some code I found at http://chrisjean.com/2011/06/17/view-csv-data-from-the-command-line which works better for me:

csview()
{
    local file="$1"
    cat "$file" | sed -e 's/,,/, ,/g' | column -s, -t | less -#5 -N -S
}

The reason it works better for me is that it handles wide columns better.

What's the difference between 'r+' and 'a+' when open file in python?

One difference is for r+ if the files does not exist, it'll not be created and open fails. But in case of a+ the file will be created if it does not exist.

Python NameError: name is not defined

Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

This will also result in

NameError: name 'Tree' is not defined

That's because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

d3 add text to circle

Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:

enter image description here

The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same div in a page header.

The main code is:

var width = 960,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)

d3.json("data.json", function(json) {
    /* Define the data for the circles */
    var elem = svg.selectAll("g")
        .data(json.nodes)

    /*Create and place the "blocks" containing the circle and the text */  
    var elemEnter = elem.enter()
        .append("g")
        .attr("transform", function(d){return "translate("+d.x+",80)"})

    /*Create the circle for each block */
    var circle = elemEnter.append("circle")
        .attr("r", function(d){return d.r} )
        .attr("stroke","black")
        .attr("fill", "white")

    /* Create the text for each block */
    elemEnter.append("text")
        .attr("dx", function(d){return -20})
        .text(function(d){return d.label})
})

and the json file is:

{"nodes":[
  {"x":80, "r":40, "label":"Node 1"}, 
  {"x":200, "r":60, "label":"Node 2"}, 
  {"x":380, "r":80, "label":"Node 3"}
]}

The resulting html code shows the encapsulation you want:

<svg width="960" height="500">
    <g transform="translate(80,80)">
        <circle r="40" stroke="black" fill="white"></circle>
        <text dx="-20">Node 1</text>
    </g>
    <g transform="translate(200,80)">
        <circle r="60" stroke="black" fill="white"></circle>
        <text dx="-20">Node 2</text>
    </g>
    <g transform="translate(380,80)">
        <circle r="80" stroke="black" fill="white"></circle>
        <text dx="-20">Node 3</text>
    </g>
</svg>

How to pass command-line arguments to a PowerShell ps1 file

You could declare your parameters in the file, like param:

[string]$para1
[string]$param2

And then call the PowerShell file like so .\temp.ps1 para1 para2....para10, etc.

Set element width or height in Standards Mode

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";

Removing double quotes from variables in batch file creates problems with CMD environment

You have an extra double quote at the end, which is adding it back to the end of the string (after removing both quotes from the string).

Input:

set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget

Output:

widget="a very useful item"
widget=a very useful item

Note: To replace Double Quotes " with Single Quotes ' do the following:

set widget=%widget:"='%

Note: To replace the word "World" (not case sensitive) with BobB do the following:

set widget="Hello World!"
set widget=%widget:world=BobB%
set widget

Output:

widget="Hello BobB!"

As far as your initial question goes (save the following code to a batch file .cmd or .bat and run):

@ECHO OFF
ECHO %0
SET BathFileAndPath=%~0
ECHO %BathFileAndPath%
ECHO "%BathFileAndPath%"
ECHO %~0
ECHO %0
PAUSE

Output:

"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
Press any key to continue . . .

%0 is the Script Name and Path.
%1 is the first command line argument, and so on.

Android + Pair devices via bluetooth programmatically

Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.

Try this to do pairing:

If you are able to search the devices then this would be your next step

ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;

I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices:

BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);

Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
    Log.i("Log","Paired");
}
} catch (Exception e) 
{
    e.printStackTrace(); 
}

The createBond() method:

public boolean createBond(BluetoothDevice btDevice)  
    throws Exception  
    { 
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");  
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    }  

Add this line into your Receiver in the ACTION_FOUND

if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    arrayListBluetoothDevices.add(device);
                }

How to get second-highest salary employees in a table

declare

cntr number :=0;

cursor c1 is

select salary from employees order by salary desc;

z c1%rowtype;

begin

open c1;

fetch c1 into z;

while (c1%found) and (cntr <= 1) loop


cntr := cntr + 1;

fetch c1 into z;

dbms_output.put_line(z.salary);

end loop;

end;

Load image from resources area of project in C#

With and ImageBox named "ImagePreview FormStrings.MyImageNames contains a regular get/set string cast method, which are linked to a scrollbox type list. The images have the same names as the linked names on the list, except for the .bmp endings. All bitmaps are dragged into the resources.resx

Object rm = Properties.Resources.ResourceManager.GetObject(FormStrings.MyImageNames);
Bitmap myImage = (Bitmap)rm;
ImagePreview.Image = myImage;

How do you easily horizontally center a <div> using CSS?

In your html file you write:

<div class="banner">
  Center content
</div>

your css file you write:

.banner {
display: block;
margin: auto;
width: 100px;
height: 50px;
}

works for me.

Maven project.build.directory

You can find those maven properties in the super pom.

You find the jar here:

${M2_HOME}/lib/maven-model-builder-3.0.3.jar

Open the jar with 7-zip or some other archiver (or use the jar tool).

Navigate to

org/apache/maven/model

There you'll find the pom-4.0.0.xml.

It contains all those "short cuts":

<project>
    ...
    <build>
        <directory>${project.basedir}/target</directory>
        <outputDirectory>${project.build.directory}/classes</outputDirectory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
        <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
        <scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
        <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
        ...
    </build>
    ...
</project>

Update

After some lobbying I am adding a link to the pom-4.0.0.xml. This allows you to see the properties without opening up the local jar file.

Print string and variable contents on the same line in R

Easiest way to do this is to use paste()

> paste("Today is", date())
[1] "Today is Sat Feb 21 15:25:18 2015"

paste0() would result in the following:

> paste0("Today is", date())
[1] "Today isSat Feb 21 15:30:46 2015"

Notice there is no default seperator between the string and x. Using a space at the end of the string is a quick fix:

> paste0("Today is ", date())
[1] "Today is Sat Feb 21 15:32:17 2015"

Then combine either function with print()

> print(paste("This is", date()))
[1] "This is Sat Feb 21 15:34:23 2015"

Or

> print(paste0("This is ", date()))
[1] "This is Sat Feb 21 15:34:56 2015"

As other users have stated, you could also use cat()

Reading data from XML

Alternatively, you can use XPathNavigator:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();

string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");

..

/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
                                      XPathNavigator navigator, string xpath) {
    StringBuilder sb = new StringBuilder();
    sb.Append(description);
    XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
    while (bookNodesIterator.MoveNext())
       sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
    return sb.ToString();
}

Replace CRLF using powershell

The following will be able to process very large files quickly.

$file = New-Object System.IO.StreamReader -Arg "file1.txt"
$outstream = [System.IO.StreamWriter] "file2.txt"
$count = 0 

while ($line = $file.ReadLine()) {
      $count += 1
      $s = $line -replace "`n", "`r`n"
      $outstream.WriteLine($s)
  }

$file.close()
$outstream.close()

Write-Host ([string] $count + ' lines have been processed.')

how to make a full screen div, and prevent size to be changed by content?

Or even just:

<div id="full-size">
  Your contents go here
</div>
html,body{ margin:0; padding:0; height:100%; width:100%; }
#full-size{
  height:100%;
  width:100%;
  overflow:hidden; /* or overflow:auto; if you want scrollbars */
}

(html, body can be set to like.. 95%-99% or some such to account for slight inconsistencies in margins, etc.)

Java - Reading XML file

If using another library is an option, the following may be easier:

package for_so;

import java.io.File;

import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;

public class Q7704827_SimpleRead
{
    public static void
    main(String[] args)
    {
        String fileName = args[0];

        TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
        String recipient = emailNode.nextTextFieldE("recipient");
        String sender = emailNode.nextTextFieldE("sender");
        String subject = emailNode.nextTextFieldE("subject");
        String description = emailNode.nextTextFieldE("description");
        emailNode.verifyNoMoreChildren();

        System.out.println("recipient =  " + recipient);
        System.out.println("sender =     " + sender);
        System.out.println("subject =    " + subject);
        System.out.println("desciption = " + description);
    }
}

The library and its documentation are at rasmustorkel.com

Error: Selection does not contain a main type

I had this problem in two projects. Maven and command line worked as expected for both. The problems were Eclipse specific. Two different solutions: Project 1): Move the main method declaration to the top within the class, above all other declarations like fields and constructors. Crazy, but it worked. Project 2): The solution for Project 1) did not remedy the problem. However, removing lombok imports and explicitly writing a getter method solved the problem

Conclusion: Eclipse and/or the lombok plugin have/has a bug.

How to read response headers in angularjs?

response.headers();

will give you all the headers (defaulat & customs). worked for me !!

enter image description here

enter image description here

Note . I tested on the same domain only. We may need to add Access-Control-Expose-Headers header on the server for cross domain.

Trigger back-button functionality on button click in Android

With this code i solved my problem.For back button paste these two line code.Hope this will help you.

Only paste this code on button click

super.onBackPressed();

Example:-

Button backButton = (Button)this.findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    super.onBackPressed();
  }
});

Pause in Python

If you type

input("")

It will wait for them to press any button then it will continue. Also you can put text between the quotes.

How to unzip a file in Powershell?

In PowerShell v5+, there is an Expand-Archive command (as well as Compress-Archive) built in:

Expand-Archive c:\a.zip -DestinationPath c:\a

Multiple conditions in ngClass - Angular 4

<a [ngClass]="{'class1':array.status === 'active','class2':array.status === 'idle','class3':array.status === 'inactive',}">

Tomcat won't stop or restart

I had this error message having started up a second Tomcat server on a Linux server.

$CATALINA_PID was set but the specified file does not exist. Is Tomcat running? Stop aborted.

When starting up the 2nd Tomcat I had set CATALINA_PID as asked but my mistake was to set it to a directory (I assumed Tomcat would write a default file name in there with the pid).

The fix was simply to change my CATALINA_PID to add a file name to the end of it (I chose catalina.pid from the above examples). Next I went to the directory and did a simple:

touch catalina.pid

creating an empty file of the correct name. Then when I did my shutdown.sh I got the message back saying:

PID file is empty and has been ignored.
Tomcat stopped.

I didn't have the option to kill Tomcat as the JVM was in use so I was glad I found this.

How to see the changes in a Git commit?

I like the below command to compare a specific commit and its last commit:

git diff <commit-hash>^-

Example:

git diff cd1b3f485^-

Finding and removing non ascii characters from an Oracle Varchar2

I think this will do the trick:

SELECT REGEXP_REPLACE(COLUMN, '[^[:print:]]', '')

No output to console from a WPF application?

You can use

Trace.WriteLine("text");

This will output to the "Output" window in Visual Studio (when debugging).

make sure to have the Diagnostics assembly included:

using System.Diagnostics;

Java; String replace (using regular expressions)?

What is your polynomial? If you're "processing" it, I'm envisioning some sort of tree of sub-expressions being generated at some point, and would think that it would be much simpler to use that to generate your string than to re-parse the raw expression with a regex.

Just throwing a different way of thinking out there. I'm not sure what else is going on in your app.

Getting files by creation date in .NET

You can use Linq

var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);

Code to loop through all records in MS Access

In "References", import DAO 3.6 object reference.

private sub showTableData

dim db as dao.database
dim rs as dao.recordset

set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously

'populate the table
rs.movelast
rs.movefirst

do while not rs.EOF
   debug.print(rs!myField) 'myField is a field name in table myTable
   rs.movenext             'press Ctrl+G to see debuG window beneath
loop

msgbox("End of Table")

end sub

You can interate data objects like queries and filtered tables in different ways:

Trhough query:

private sub showQueryData

dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string

sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"

set db = currentDb
set rs = db.openRecordset(sqlStr)

rs.movefirst

do while not rs.EOF
  debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
  rs.movenext
loop

msgbox("End of customers from Brazil")

end sub

You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.

I hope I've helped.

What happens to C# Dictionary<int, int> lookup if the key does not exist?

Consider the option of encapsulating this particular dictionary and provide a method to return the value for that key:

public static class NumbersAdapter
{
    private static readonly Dictionary<string, string> Mapping = new Dictionary<string, string>
    {
        ["1"] = "One",
        ["2"] = "Two",
        ["3"] = "Three"
    };

    public static string GetValue(string key)
    {
        return Mapping.ContainsKey(key) ? Mapping[key] : key;
    }
}

Then you can manage the behaviour of this dictionary.

For example here: if the dictionary doesn't have the key, it returns key that you pass by parameter.

Add vertical scroll bar to panel

Try this instead for 'only' scrolling vertical.
(auto scroll needs to be false before it will accept changes)

mypanel.AutoScroll = false;
mypanel.HorizontalScroll.Enabled = false;
mypanel.HorizontalScroll.Visible = false;
mypanel.HorizontalScroll.Maximum = 0;
mypanel.AutoScroll = true;

Make page to tell browser not to cache/preserve input values

Are you explicitly setting the values as blank? For example:

<input type="text" name="textfield" value="">

That should stop browsers putting data in where it shouldn't. Alternatively, you can add the autocomplete attribute to the form tag:

<form autocomplete="off" ...></form>

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

GCC dump preprocessor defines

The simple approach (gcc -dM -E - < /dev/null) works fine for gcc but fails for g++. Recently I required a test for a C++11/C++14 feature. Recommendations for their corresponding macro names are published at https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations. But:

g++ -dM -E - < /dev/null | fgrep __cpp_alias_templates

always fails, because it silently invokes the C-drivers (as if invoked by gcc). You can see this by comparing its output against that of gcc or by adding a g++-specific command line option like (-std=c++11) which emits the error message cc1: warning: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C.

Because (the non C++) gcc will never support "Templates Aliases" (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf) you must add the -x c++ option to force the invocation of the C++ compiler (Credits for using the -x c++ options instead of an empty dummy file go to yuyichao, see below):

g++ -dM -E -x c++ /dev/null | fgrep __cpp_alias_templates

There will be no output because g++ (revision 4.9.1, defaults to -std=gnu++98) does not enable C++11-features by default. To do so, use

g++ -dM -E -x c++ -std=c++11 /dev/null | fgrep __cpp_alias_templates

which finally yields

#define __cpp_alias_templates 200704

noting that g++ 4.9.1 does support "Templates Aliases" when invoked with -std=c++11.

How to get these two divs side-by-side?

User float:left property in child div class

check for div structure in detail : http://www.dzone.com/links/r/div_table.html

Python time measure function

Elaborating on @Jonathan Ray I think this does the trick a bit better

import time
import inspect

def timed(f:callable):
    start = time.time()
    ret = f()
    elapsed = 1000*(time.time() - start)
    source_code=inspect.getsource(f).strip('\n') 
    logger.info(source_code+":  "+str(elapsed)+" seconds")
    return ret

It allows to take a regular line of code, say a = np.sin(np.pi) and transform it rather simply into

a = timed(lambda: np.sin(np.pi))

so that the timing is printed onto the logger and you can keep the same assignment of the result to a variable you might need for further work.

I suppose in Python 3.8 one could use the := but I do not have 3.8 yet

How can I transform string to UTF-8 in C#?

@anothershrubery answer worked for me. I've made an enhancement using StringEntensions Class so I can easily convert any string at all in my program.

Method:

public static class StringExtensions
{
    public static string ToUTF8(this string text)
    {
        return Encoding.UTF8.GetString(Encoding.Default.GetBytes(text));
    }
}

Usage:

string myString = "Acción";
string strConverted = myString.ToUTF8();

Or simply:

string strConverted = "Acción".ToUTF8();

How to delete an app from iTunesConnect / App Store Connect

I had the same problem with a dummy app that happened to have the same name as my final app and couldn't publish because the App Name is already in use

To fix it, instead of deleting it(which you can't) I just changed the name of the dummy app to something random and hit SAVE. Then I was able to add the new app with the proper name

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

    SELECT art.* , sec.section.title, cat.title, use1.name, use2.name as modifiedby
FROM article art
INNER JOIN section sec ON art.section_id = sec.section.id
INNER JOIN category cat ON art.category_id = cat.id
INNER JOIN user use1 ON art.author_id = use1.id
LEFT JOIN user use2 ON art.modified_by = use2.id
WHERE art.id = '1';

Hope This Might Help

How to fast-forward a branch to head?

If you are standing on a different branch and want to checkout the newest version of master you can also do

git checkout -B master origin/master

Best way to find the intersection of multiple sets?

As of 2.6, set.intersection takes arbitrarily many iterables.

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s3 = set([2, 4, 6])
>>> s1 & s2 & s3
set([2])
>>> s1.intersection(s2, s3)
set([2])
>>> sets = [s1, s2, s3]
>>> set.intersection(*sets)
set([2])

StringStream in C#

You have a number of options:

One is to not use streams, but use the TextWriter

   void Print(TextWriter writer) 
   {
   }

   void Main() 
  {
    var textWriter = new StringWriter();
    Print(writer);
    string myString = textWriter.ToString();
   }

It's likely that TextWriter is the appropriate level of abstraction for your print function. Streams are aimed at writing binary data, while TextWriter works at a higher abstraction level, specifically geared towards outputting strings.

If your motivation is that you also want your Print function to write to files, you can get a text writer from a filestream as well.

void Print(TextWriter writer) 
{
}

void PrintToFile(string filePath) 
{
     using(var textWriter = new StreamWriter(filePath))
     {
         Print(writer);
     }
}

If you REALLY want a stream you can look at MemoryStream.

Validation error: "No validator could be found for type: java.lang.Integer"

You can add hibernate validator dependency, to provide a Validator

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.12.Final</version>
</dependency>

Return value in a Bash function

As an add-on to others' excellent posts, here's an article summarizing these techniques:

  • set a global variable
  • set a global variable, whose name you passed to the function
  • set the return code (and pick it up with $?)
  • 'echo' some data (and pick it up with MYVAR=$(myfunction) )

Returning Values from Bash Functions

How to get form values in Symfony2 controller

If you have extra fields in the form that not defined in Entity , $form->getData() doesn't work , one way could be this :

$request->get("form")["foo"] 

Or :

$form->get('foo')->getData();

Hide element by class in pure Javascript

document.getElementsByClassName returns an HTMLCollection(an array-like object) of all elements matching the class name. The style property is defined for Element not for HTMLCollection. You should access the first element using the bracket(subscript) notation.

document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';

Updated jsFiddle

To change the style rules of all elements matching the class, using the Selectors API:

[].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
  el.style.visibility = 'hidden';
});

If for...of is available:

for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';

Rollback a Git merge

git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705

But may have unexpected side-effects. See --mainline parent-number option in git-scm.com/docs/git-revert

Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !

node.js Error: connect ECONNREFUSED; response from server

i ran the local mysql database, but not in administrator mode, which threw this error

imagecreatefromjpeg and similar functions are not working in PHP

In CentOS, RedHat, etc. use below command. don't forget to restart the Apache. Because the PHP module has to be loaded.

yum -y install php-gd
service httpd restart

Checking if a textbox is empty in Javascript

function valid(id)
    {
        var textVal=document.getElementById(id).value;
        if (!textVal.match("Tryit") 
        {
            alert("Field says Tryit");
            return false;
        } 
        else 
        {
            return true;
        }
     }

Use this for expressing things

Histogram Matplotlib

I just realized that the hist documentation is explicit about what to do when you already have an np.histogram

counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)

The important part here is that your counts are simply the weights. If you do it like that, you don't need the bar function anymore

Variable name as a string in Javascript

Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.

_x000D_
_x000D_
var obj = { myFirstName: 'John' };_x000D_
obj.foo = 'Another name';_x000D_
for(key in obj)_x000D_
    console.log(key + ': ' + obj[key]);
_x000D_
_x000D_
_x000D_

ld cannot find -l<library>

I had a similar problem with another library and the reason why it didn't found it, was that I didn't run the make install (after running ./configure and make) for that library. The make install may require root privileges (in this case use: sudo make install). After running the make install you should have the so files in the correct folder, i.e. here /usr/local/lib and not in the folder mentioned by you.

Python 3.6 install win32api?

Take a look at this answer: ImportError: no module named win32api

You can use

pip install pypiwin32

Maven in Eclipse: step by step installation

IF you want to install Maven in Eclipse(Java EE) Indigo Then follow these Steps :

  1. Eclipse -> Help -> Install New Software.

  2. Type " http://download.eclipse.org/releases/indigo/ " & Hit Enter.

  3. Expand " Collaboration " tag.

  4. Select Maven plugin from there.

  5. Click on next .

  6. Accept the agreement & click finish.

After installing the maven it will ask for restarting the Eclipse,So restart the eclipse again to see the changes.

Is background-color:none valid CSS?

No, use transparent instead none . See working example here in this example if you will change transparent to none it will not work

use like .class { background-color:transparent; }


Where .class is what you will name your transparent class.

Python error: "IndexError: string index out of range"

You are iterating over one string (word), but then using the index into that to look up a character in so_far. There is no guarantee that these two strings have the same length.

Make Bootstrap's Carousel both center AND responsive?

None of the above solutions worked for me. It's possible that there were some other styles conflicting.

For myself, the following worked, hopefully it may help someone else. I'm using bootstrap 4.

.carousel-inner img {       
   display:block;
   height: auto; 
   max-width: 100%;
}

How to reload / refresh model data from the server programmatically?

You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:

function PersonListCtrl($scope, $http) {
  $scope.loadData = function () {
     $http.get('/persons').success(function(data) {
       $scope.persons = data;
     });
  };

  //initial load
  $scope.loadData();
}

then in your markup

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="loadData()">Refresh</button>
</div>

As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:

for example (just puedo code) in your controller:

$scope.addPerson = function() {
     $scope.persons.push({ name: 'Test Monkey' });
};

Then you could use that in your view or whatever you'd want to do.

Hide all elements with class using plain Javascript

There are many ways to hide all elements which has certain class in javascript one way is to using for loop but here i want to show you other ways to doing it.

1.forEach and querySelectorAll('.classname')

document.querySelectorAll('.classname').forEach(function(el) {
   el.style.display = 'none';
});

2.for...of with getElementsByClassName

for (let element of document.getElementsByClassName("classname")){
   element.style.display="none";
}

3.Array.protoype.forEach getElementsByClassName

Array.prototype.forEach.call(document.getElementsByClassName("classname"), function(el) {
    // Do something amazing below
    el.style.display = 'none';
});

4.[ ].forEach and getElementsByClassName

[].forEach.call(document.getElementsByClassName("classname"), function (el) {
    el.style.display = 'none';
});

i have shown some of the possible ways, there are also more ways to do it, but from above list you can Pick whichever suits and easy for you.

Note: all above methods are supported in modern browsers but may be some of them will not work in old age browsers like internet explorer.

How can I create a border around an Android LinearLayout?

Try This in your res/drawable

    <?xml version="1.0" encoding="UTF-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
  <shape
    android:shape="rectangle">
    <padding android:left="15dp"
        android:right="15dp"
        android:top="15dp"
        android:bottom="15dp"/>
    <stroke android:width="10dp"
        android:color="@color/colorPrimary"/>
  </shape>
</item><item android:left="-5dp"
        android:right="-5dp"
        android:top="-5dp"
        android:bottom="-5dp">
  <shape android:shape="rectangle">
    <solid android:color="@color/background" />
  </shape></item></layer-list>

Reversing a linked list in Java, recursively

There's code in one reply that spells it out, but you might find it easier to start from the bottom up, by asking and answering tiny questions (this is the approach in The Little Lisper):

  1. What is the reverse of null (the empty list)? null.
  2. What is the reverse of a one element list? the element.
  3. What is the reverse of an n element list? the reverse of the rest of the list followed by the first element.

public ListNode Reverse(ListNode list)
{
    if (list == null) return null; // first question

    if (list.next == null) return list; // second question

    // third question - in Lisp this is easy, but we don't have cons
    // so we grab the second element (which will be the last after we reverse it)

    ListNode secondElem = list.next;

    // bug fix - need to unlink list from the rest or you will get a cycle
    list.next = null;

    // then we reverse everything from the second element on
    ListNode reverseRest = Reverse(secondElem);

    // then we join the two lists
    secondElem.next = list;

    return reverseRest;
}

tkinter: how to use after method

You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

tiles_letter = ['a', 'b', 'c', 'd', 'e']

def add_letter():
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles


root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():
    if not tiles_letter:
        return
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it

Calling Member Functions within Main C++

From your question it is unclear if you want to be able use the class without an identity or if calling the method requires you to create an instance of the class. This depends on whether you want the printInformation member to write some general information or more specific about the object identity.

Case 1: You want to use the class without creating an instance. The members of that class should be static, using this keyword you tell the compiler that you want to be able to call the method without having to create a new instance of the class.

class MyClass
{
public:
    static void printInformation();
};

Case 2: You want the class to have an instance, you first need to create an object so that the class has an identity, once that is done you can use the object his methods.

Myclass m;
m.printInformation();

// Or, in the case that you want to use pointers:
Myclass * m = new Myclass();
m->printInformation();

If you don't know when to use pointers, read Pukku's summary in this Stack Overflow question.
Please note that in the current case you would not need a pointer. :-)

Break a previous commit into multiple commits

This method is most useful if your changes were mostly adding new content.

Sometimes you do not want to lose commit message associated with commit that is being split. If you have commited some changes that you want to split, you can:

  1. Edit the changes you want removed out of the file (ie delete the lines or change the files approprietely to fit into first commit). You can use combination of your chosen editor and git checkout -p HEAD^ -- path/to/file to revert some changes into current tree.
  2. Commit this edit as a new commit, with something like git add . ; git commit -m 'removal of things that should be changed later', so you will have original commit in history and you will also have another commit with changes that you made, so the files on current HEAD look like you would want them in first commit after splitting.
000aaa Original commit
000bbb removal of things that should be changed later
  1. Revert the edit with git revert HEAD, this will create revert commit. Files will look like they do on original commit and your history will now look like
000aaa Original commit
000bbb removal of things that should be changed later
000ccc Revert "removal of things that should be changed later" (assuming you didn't edit commit message immediately)
  1. Now, you can squash/fixup first two commits into one with git rebase -i, optionally amend revert commit if you didn't give meaningful commit message to it earlier. You should be left with
000ddd Original commit, but without some content that is changed later
000eee Things that should be changed later

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

CocoaPods Errors on Project Build

It wasn't very intuitive. I went to the base project settings and then I hardcoded paths to my pod.lock and pod.manifest under Check Pods Manifest.lock, because they stayed in different folders in fact, so my paths looked like this:

diff "/Users/admin/Desktop/Experimental/projectfolder/Podfile.lock" "/Users/admin/Desktop/Experimental/projectfolder/Pods/Manifest.lock" > /dev/null
if [[ $? != 0 ]] ; then
    cat << EOM
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
EOM
    exit 1
fi

Setting the MySQL root user password on OS X

None of the previous comments solve the issue on my Mac. I used the commands below and it worked.

$ brew services stop mysql
$ pkill mysqld
$ rm -rf /usr/local/var/mysql/ # NOTE: this will delete your existing database!!!
$ brew postinstall mysql
$ brew services restart mysql
$ mysql -u root

Why SpringMVC Request method 'GET' not supported?

I also had the same issue. I changed it to the following and it worked.

Java :

@RequestMapping(value = "/test", method = RequestMethod.GET)

HTML code:

  <form action="<%=request.getContextPath() %>/test" method="GET">
    <input type="submit" value="submit"> 
    </form>

By default if you do not specify http method in a form it uses GET. To use POST method you need specifically state it.

Hope this helps.

Get string between two strings in a string

Regex is overkill here.

You could use string.Split with the overload that takes a string[] for the delimiters but that would also be overkill.

Look at Substring and IndexOf - the former to get parts of a string given and index and a length and the second for finding indexed of inner strings/characters.

DataTables: Cannot read property style of undefined

The solution is pretty simple.

_x000D_
_x000D_
  <table id="TASK_LIST_GRID" class="table table-striped table-bordered table-hover dataTable no-footer" width="100%" role="grid" aria-describedby="TASK_LIST_GRID_info">_x000D_
  <thead>_x000D_
    <tr role="row">_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Solution</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Status</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Category</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Type</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Due Date</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Create Date</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Owner</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Comments</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Mnemonic</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Domain</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Approve</th>_x000D_
      <th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Dismiss</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody></tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
                TASKLISTGRID = $("#TASK_LIST_GRID").DataTable({_x000D_
                    data : response,_x000D_
                    columns : columns.AdoptionTaskInfo.columns,_x000D_
                    paging: true_x000D_
                });_x000D_
                _x000D_
                //Note: columns : columns.AdoptionTaskInfo.columns has at least a column not definded in the <thead>
_x000D_
_x000D_
_x000D_

Note: columns : columns.AdoptionTaskInfo.columns has at least a column not defined in the table head

Getting SyntaxError for print with keyword argument end=' '

For python 2.7 I had the same issue Just use "from __future__ import print_function" without quotes to resolve this issue.This Ensures Python 2.6 and later Python 2.x can use Python 3.x print function.

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

$ seq 4
1
2
3
4

$ seq 2 5
2
3
4
5

$ seq 4 2 12
4
6
8
10
12

$ seq -w 4 2 12
04
06
08
10
12

$ seq -s, 4 2 12
4,6,8,10,12