Programs & Examples On #Optparse

`optparse` is a deprecated command-line argument parser for Python included in the standard library; it is also a non-deprecated command-line argument parser for Ruby.

Why use argparse rather than optparse?

At first I was as reluctant as @fmark to switch from optparse to argparse, because:

  1. I thought the difference was not that huge.
  2. Quite some VPS still provides Python 2.6 by default.

Then I saw this doc, argparse outperforms optparse, especially when talking about generating meaningful help message: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html

And then I saw "argparse vs. optparse" by @Nicholas, saying we can have argparse available in python <2.7 (Yep, I didn't know that before.)

Now my two concerns are well addressed. I wrote this hoping it will help others with a similar mindset.

How many characters in varchar(max)

For future readers who need this answer quickly:

2^31-1 = 2.147.483.647 characters

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

I made some changes in above code to look for a location fix by both GPS and Network for about 5sec and give me the best known location out of it.

public class LocationService implements LocationListener {

    boolean isGPSEnabled = false;

    boolean isNetworkEnabled = false;

    boolean canGetLocation = false;

    final static long MIN_TIME_INTERVAL = 60 * 1000L;

    Location location;


    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute

    protected LocationManager locationManager;

    private CountDownTimer timer = new CountDownTimer(5 * 1000, 1000) {

        public void onTick(long millisUntilFinished) {

        }

        public void onFinish() {
            stopUsingGPS();
        }
    };

    public LocationService() {
        super(R.id.gps_service_id);
    }


    public void start() {
        if (Utils.isNetworkAvailable(context)) {

            try {


                timer.start();


                locationManager = (LocationManager) context
                        .getSystemService(Context.LOCATION_SERVICE);

                isGPSEnabled = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);

                isNetworkEnabled = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        Location tempLocation = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (tempLocation != null
                                && isBetterLocation(tempLocation,
                                        location))
                            location = tempLocation;
                    }
                }
                if (isGPSEnabled) {

                    locationManager.requestSingleUpdate(
                            LocationManager.GPS_PROVIDER, this, null);
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        Location tempLocation = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (tempLocation != null
                                && isBetterLocation(tempLocation,
                                        location))
                            location = tempLocation;
                    }
                }

            } catch (Exception e) {
                onTaskError(e.getMessage());
                e.printStackTrace();
            }
        } else {
            onOfflineResponse(requestData);
        }
    }

    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(LocationService.this);
        }
    }

    public boolean canGetLocation() {
        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return isGPSEnabled || isNetworkEnabled;
    }

    @Override
    public void onLocationChanged(Location location) {

        if (location != null
                && isBetterLocation(location, this.location)) {

            this.location = location;

        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public Object getResponseObject(Object location) {
        return location;
    }

    public static boolean isBetterLocation(Location location,
            Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > MIN_TIME_INTERVAL;
        boolean isSignificantlyOlder = timeDelta < -MIN_TIME_INTERVAL;
        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 true;
            // If the new location is more than two minutes older, it must
            // be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // 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 true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate
                && isFromSameProvider) {
            return true;
        }
        return false;
    }

}

In the above class, I am registering a location listener for both GPS and network, so an onLocationChanged call back can be called by either or both of them multiple times and we just compare the new location fix with the one we already have and keep the best one.

HTML email with Javascript

Agree completely with Bryan and others.

Instead, consider using multiple sections in your email that you can jump to using links and anchors (the 'a' tag). I think that you can emulate the behavior you want by including multiple copies of the text further down in your email. This is a bet messy though, so you could just have sets of anchors that link to each other and allow you to move back in forth between the 'summary' section and the 'expanded' one.

Example:

<a href="#section1">Jump to section!</a>
<p>A bunch of content</p>
<h2 id="section1">An anchor!</h2>

Clicking on the first link will move focus to the sub-section.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

When an array is passed to a method or function in PHP, it is passed by value unless you explicitly pass it by reference, like so:

function test(&$array) {
    $array['new'] = 'hey';
}

$a = $array(1,2,3);
// prints [0=>1,1=>2,2=>3]
var_dump($a);
test($a);
// prints [0=>1,1=>2,2=>3,'new'=>'hey']
var_dump($a);

In your second question, $b is not a reference to $a, but a copy of $a.

Much like the first example, you can reference $a by doing the following:

$a = array(1,2,3);
$b = &$a;
// prints [0=>1,1=>2,2=>3]
var_dump($b);
$b['new'] = 'hey';
// prints [0=>1,1=>2,2=>3,'new'=>'hey']
var_dump($a);

Can I delete a git commit but keep the changes?

It's as simple as this:

git reset HEAD^

Note: some shells treat ^ as a special character (for example some Windows shells or ZSH with globbing enabled), so you may have to quote "HEAD^" in those cases.

git reset without a --hard or --soft moves your HEAD to point to the specified commit, without changing any files. HEAD^ refers to the (first) parent commit of your current commit, which in your case is the commit before the temporary one.

Note that another option is to carry on as normal, and then at the next commit point instead run:

git commit --amend [-m … etc]

which will instead edit the most recent commit, having the same effect as above.

Note that this (as with nearly every git answer) can cause problems if you've already pushed the bad commit to a place where someone else may have pulled it from. Try to avoid that

sum two columns in R

You can do this :

    df <- data.frame("a" = c(1,2,3,4), "b" = c(4,3,2,1), "x_ind" = c(1,0,1,1), "y_ind" = c(0,0,1,1), "z_ind" = c(0,1,1,1) )
df %>% mutate( bi  = ifelse((df$x_ind + df$y_ind +df$z_ind)== 3, 1,0 ))

Mod of negative number is melting my brain

Single-line implementation using % only once:

int mod(int k, int n) {  return ((k %= n) < 0) ? k+n : k;  }

Clear and reset form input fields

/* See newState and use of it in eventSubmit() for resetting all the state. I have tested it is working for me. Please let me know for mistakes */

import React from 'react';
    
    const newState = {
        fullname: '',
        email: ''
    }
    
    class Form extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                fullname: ' ',
                email: ' '
            }
    
            this.eventChange = this
                .eventChange
                .bind(this);
            this.eventSubmit = this
                .eventSubmit
                .bind(this);
        }
        eventChange(event) {
            const target = event.target;
            const value = target.type === 'checkbox'
                ? target.type
                : target.value;
            const name = target.name;
    
            this.setState({[name]: value})
        }
    
        eventSubmit(event) {
            alert(JSON.stringify(this.state))
            event.preventDefault();
            this.setState({...newState});
        }
    
        render() {
            return (
                <div className="container">
                    <form className="row mt-5" onSubmit={this.eventSubmit}>
                        <label className="col-md-12">
                            Full Name
                            <input
                                type="text"
                                name="fullname"
                                id="fullname"
                                value={this.state.fullname}
                                onChange={this.eventChange}/>
                        </label>
                        <label className="col-md-12">
                            email
                            <input
                                type="text"
                                name="email"
                                id="email"
                                value={this.state.value}
                                onChange={this.eventChange}/>
                        </label>
                        <input type="submit" value="Submit"/>
                    </form>
                </div>
            )
        }
    }
    
    export default Form;
    

(HTML) Download a PDF file instead of opening them in browser when clicked

This is only possible with setting a http response header by the server side code. Namely;

Content-Disposition: attachment; filename=fname.ext

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

The straight up answer to your question is: No. The signature for the PostAsync method is as follows:

public Task PostAsync(Uri requestUri, HttpContent content)

So, while you can pass an object to PostAsync it must be of type HttpContent and your anonymous type does not meet that criteria.

However, there are ways to accomplish what you want to accomplish. First, you will need to serialize your anonymous type to JSON, the most common tool for this is Json.NET. And the code for this is pretty trivial:

var myContent = JsonConvert.SerializeObject(data);

Next, you will need to construct a content object to send this data, I will use a ByteArrayContent object, but you could use or create a different type if you wanted.

var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);

Next, you want to set the content type to let the API know this is JSON.

byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

Then you can send your request very similar to your previous example with the form content:

var result = client.PostAsync("", byteContent).Result

On a side note, calling the .Result property like you're doing here can have some bad side effects such as dead locking, so you want to be careful with this.

Xcode 10 Error: Multiple commands produce

While checking the build log, I noticed a warning:

note: Using new build system
note: Planning build
note: Constructing build description
Build system information
warning: The Copy Bundle Resources build phase contains this target's Info.plist file '/Users/<redacted>/Repositories/Whitesmith/optimize-ios/Carthage/Checkouts/WSStatusBarNotification/Miscellaneous/Info.plist'. (in target 'JDStatusBarNotification')

So, if that's your case then just go to your target:

  1. Build Phases
  2. Copy Bundle Resource
  3. Remove info.plist.

How do I ignore files in Subversion?

  1. open you use JetBrains Product(i.e. Pycharm)
  2. then click the 'commit' button on the top toolbar or use shortcut 'ctrl + k' screenshot_toolbar
  3. on the commit interface, move your unwanted files to another change list as follows. screenshot_commit_change
  4. next time you can only commit default change list.

How do I make a stored procedure in MS Access?

If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

 PARAMETERS SomeParam Text(10);
 SELECT Field FROM Table
 WHERE OtherField=SomeParam

You can also say:

CREATE PROCEDURE ProcedureName
   (Parameter1 datatype, Parameter2 datatype) AS
   SQLStatement

From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs

Note that the procedure contains only one statement.

Unresolved Import Issues with PyDev and Eclipse

I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great:

  • Select Project-> RightClick-> PyDev-> Remove PyDev Project Config
  • file-> restart

And I was using Python 2.7 as an interpreter, although it doesn’t effect, I think.

How can I access Oracle from Python?

In addition to the Oracle instant client, you may also need to install the Oracle ODAC components and put the path to them into your system path. cx_Oracle seems to need access to the oci.dll file that is installed with them.

Also check that you get the correct version (32bit or 64bit) of them that matches your: python, cx_Oracle, and instant client versions.

How do you handle multiple submit buttons in ASP.NET MVC Framework?

This script allows to specify a data-form-action attribute which will work as the HTML5 formaction attribute in all browsers (in an unobtrusive way):

$(document).on('click', '[type="submit"][data-form-action]', function(event) {
    var $this = $(this),
    var formAction = $this.attr('data-form-action'),
    $form = $($this.closest('form'));
    $form.attr('action', formAction);             
});

The form containing the button will be posted to the URL specified in the data-form-action attribute:

<button type="submit" data-form-action="different/url">Submit</button>   

This requires jQuery 1.7. For previous versions you should use live() instead of on().

Referencing Row Number in R

Perhaps with dataframes one of the most easy and practical solution is:

data = dplyr::mutate(data, rownum=row_number())

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

In the below investigation as API, I use http://example.com instead of http://myApiUrl/login from your question, because this first one working.

I assume that your page is on http://my-site.local:8088.

The reason why you see different results is that Postman:

  • set header Host=example.com (your API)
  • NOT set header Origin

This is similar to browsers' way of sending requests when the site and API has the same domain (browsers also set the header item Referer=http://my-site.local:8088, however I don't see it in Postman). When Origin header is not set, usually servers allow such requests by default.

Enter image description here

This is the standard way how Postman sends requests. But a browser sends requests differently when your site and API have different domains, and then CORS occurs and the browser automatically:

  • sets header Host=example.com (yours as API)
  • sets header Origin=http://my-site.local:8088 (your site)

(The header Referer has the same value as Origin). And now in Chrome's Console & Networks tab you will see:

Enter image description here

Enter image description here

When you have Host != Origin this is CORS, and when the server detects such a request, it usually blocks it by default.

Origin=null is set when you open HTML content from a local directory, and it sends a request. The same situation is when you send a request inside an <iframe>, like in the below snippet (but here the Host header is not set at all) - in general, everywhere the HTML specification says opaque origin, you can translate that to Origin=null. More information about this you can find here.

_x000D_
_x000D_
fetch('http://example.com/api', {method: 'POST'});
_x000D_
Look on chrome-console > network tab
_x000D_
_x000D_
_x000D_

If you do not use a simple CORS request, usually the browser automatically also sends an OPTIONS request before sending the main request - more information is here. The snippet below shows it:

_x000D_
_x000D_
fetch('http://example.com/api', {_x000D_
  method: 'POST',_x000D_
  headers: { 'Content-Type': 'application/json'}_x000D_
});
_x000D_
Look in chrome-console -> network tab to 'api' request._x000D_
This is the OPTIONS request (the server does not allow sending a POST request)
_x000D_
_x000D_
_x000D_

You can change the configuration of your server to allow CORS requests.

Here is an example configuration which turns on CORS on nginx (nginx.conf file) - be very careful with setting always/"$http_origin" for nginx and "*" for Apache - this will unblock CORS from any domain.

_x000D_
_x000D_
location ~ ^/index\.php(/|$) {_x000D_
   ..._x000D_
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;_x000D_
    add_header 'Access-Control-Allow-Credentials' 'true' always;_x000D_
    if ($request_method = OPTIONS) {_x000D_
        add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)_x000D_
        add_header 'Access-Control-Allow-Credentials' 'true';_x000D_
        add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days_x000D_
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';_x000D_
        add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';_x000D_
        add_header 'Content-Length' 0;_x000D_
        add_header 'Content-Type' 'text/plain charset=UTF-8';_x000D_
        return 204;_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Here is an example configuration which turns on CORS on Apache (.htaccess file)

_x000D_
_x000D_
# ------------------------------------------------------------------------------_x000D_
# | Cross-domain Ajax requests                                                 |_x000D_
# ------------------------------------------------------------------------------_x000D_
_x000D_
# Enable cross-origin Ajax requests._x000D_
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity_x000D_
# http://enable-cors.org/_x000D_
_x000D_
# <IfModule mod_headers.c>_x000D_
#    Header set Access-Control-Allow-Origin "*"_x000D_
# </IfModule>_x000D_
_x000D_
# Header set Header set Access-Control-Allow-Origin "*"_x000D_
# Header always set Access-Control-Allow-Credentials "true"_x000D_
_x000D_
Access-Control-Allow-Origin "http://your-page.com:80"_x000D_
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"_x000D_
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
_x000D_
_x000D_
_x000D_

Remove an element from a Bash array

http://wiki.bash-hackers.org/syntax/pe#substring_removal

${PARAMETER#PATTERN} # remove from beginning

${PARAMETER##PATTERN} # remove from the beginning, greedy match

${PARAMETER%PATTERN} # remove from the end

${PARAMETER%%PATTERN} # remove from the end, greedy match

In order to do a full remove element, you have to do an unset command with an if statement. If you don't care about removing prefixes from other variables or about supporting whitespace in the array, then you can just drop the quotes and forget about for loops.

See example below for a few different ways to clean up an array.

options=("foo" "bar" "foo" "foobar" "foo bar" "bars" "bar")

# remove bar from the start of each element
options=("${options[@]/#"bar"}")
# options=("foo" "" "foo" "foobar" "foo bar" "s" "")

# remove the complete string "foo" in a for loop
count=${#options[@]}
for ((i = 0; i < count; i++)); do
   if [ "${options[i]}" = "foo" ] ; then
      unset 'options[i]'
   fi
done
# options=(  ""   "foobar" "foo bar" "s" "")

# remove empty options
# note the count variable can't be recalculated easily on a sparse array
for ((i = 0; i < count; i++)); do
   # echo "Element $i: '${options[i]}'"
   if [ -z "${options[i]}" ] ; then
      unset 'options[i]'
   fi
done
# options=("foobar" "foo bar" "s")

# list them with select
echo "Choose an option:"
PS3='Option? '
select i in "${options[@]}" Quit
 do
    case $i in 
       Quit) break ;;
       *) echo "You selected \"$i\"" ;;
    esac
 done

Output

Choose an option:
1) foobar
2) foo bar
3) s
4) Quit
Option? 

Hope that helps.

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

const to Non-const Conversion in C++

The actual code to cast away the const-ness of your pointer would be:

BoxT<T> * nonConstObj = const_cast<BoxT<T> *>(constObj);

But note that this really is cheating. A better solution would either be to figure out why you want to modify a const object, and redesign your code so you don't have to.... or remove the const declaration from your vector, if it turns out you don't really want those items to be read-only after all.

R color scatter plot points based on values

Here is a method using a lookup table of thresholds and associated colours to map the colours to the variable of interest.

 # make a grid 'Grd' of points and number points for side of square 'GrdD'
Grd <- expand.grid(seq(0.5,400.5,10),seq(0.5,400.5,10))
GrdD <- length(unique(Grd$Var1))

# Add z-values to the grid points
Grd$z <- rnorm(length(Grd$Var1), mean = 10, sd =2)

# Make a vector of thresholds 'Brks' to colour code z 
Brks <- c(seq(0,18,3),Inf)

# Make a vector of labels 'Lbls' for the colour threhsolds
Lbls <- Lbls <- c('0-3','3-6','6-9','9-12','12-15','15-18','>18')

# Make a vector of colours 'Clrs' for to match each range
Clrs <- c("grey50","dodgerblue","forestgreen","orange","red","purple","magenta")

# Make up lookup dataframe 'LkUp' of the lables and colours 
LkUp <- data.frame(cbind(Lbls,Clrs),stringsAsFactors = FALSE)

# Add a new variable 'Lbls' the grid dataframe mapping the labels based on z-value
Grd$Lbls <- as.character(cut(Grd$z, breaks = Brks, labels = Lbls))

# Add a new variable 'Clrs' to the grid dataframe based on the Lbls field in the grid and lookup table
Grd <- merge(Grd,LkUp, by.x = 'Lbls')

# Plot the grid using the 'Clrs' field for the colour of each point
plot(Grd$Var1,
     Grd$Var2,
     xlim = c(0,400),
     ylim = c(0,400),
     cex = 1.0,
     col = Grd$Clrs,
     pch = 20,
     xlab = 'mX',
     ylab = 'mY',
     main = 'My Grid',
     axes = FALSE,
     labels = FALSE,
     las = 1
)

axis(1,seq(0,400,100))
axis(2,seq(0,400,100),las = 1)
box(col = 'black')

legend("topleft", legend = Lbls, fill = Clrs, title = 'Z')

Can you 'exit' a loop in PHP?

You are looking for the break statement.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

How do you cast a List of supertypes to a List of subtypes?

When you cast an object reference you are just casting the type of the reference, not the type of the object. casting won't change the actual type of the object.

Java doesn't have implicit rules for converting Object types. (Unlike primitives)

Instead you need to provide how to convert one type to another and call it manually.

public class TestA {}
public class TestB extends TestA{ 
    TestB(TestA testA) {
        // build a TestB from a TestA
    }
}

List<TestA> result = .... 
List<TestB> data = new List<TestB>();
for(TestA testA : result) {
   data.add(new TestB(testA));
}

This is more verbose than in a language with direct support, but it works and you shouldn't need to do this very often.

Trim a string based on the string length

s = s.substring(0, Math.min(s.length(), 10));

Using Math.min like this avoids an exception in the case where the string is already shorter than 10.


Notes:

  1. The above does real trimming. If you actually want to replace the last three (!) characters with dots if it truncates, then use Apache Commons StringUtils.abbreviate.

  2. For typical implementations of String, s.substring(0, s.length()) will return s rather than allocating a new String.

  3. This may behave incorrectly1 if your String contains Unicode codepoints outside of the BMP; e.g. Emojis. For a (more complicated) solution that works correctly for all Unicode code-points, see @sibnick's solution.


1 - A Unicode codepoint that is not on plane 0 (the BMP) is represented as a "surrogate pair" (i.e. two char values) in the String. By ignoring this, we might trim to fewer than 10 code points, or (worse) truncate in the middle of a surrogate pair. On the other hand, String.length() is no longer an ideal measure of Unicode text length, so trimming based on it may be the wrong thing to do.

How do I ignore all files in a folder with a Git repository in Sourcetree?

If your Ignore option is grayed out, you have to stop tracking the file before you can ignore it. You can simply right click on the file and hit "Stop Tracking".

A blue icon should appear next to it. Right click on it again and click ignore.

Specify an SSH key for git push for a given domain

Another alternative is to use ssh-ident, to manage your ssh identities.

It automatically loads and uses different keys based on your current working directory, ssh options, and so on... which means you can easily have a work/ directory and private/ directory that transparently end up using different keys and identities with ssh.

sql searching multiple words in a string

Oracle SQL :

select * 
from MY_TABLE
where REGEXP_LIKE (company , 'Microsodt industry | goglge auto car | oracles    database')
  • company - is the database column name.
  • results - this SQL will show you if company column rows contain one of those companies (OR phrase) please note that : no wild characters are needed, it's built in.

more info at : http://www.techonthenet.com/oracle/regexp_like.php

How to use find command to find all files with extensions from list?

On Mac OS use

find -E packages  -regex ".*\.(jpg|gif|png|jpeg)"

Checking if date is weekend PHP

Here:

function isweekend($year, $month, $day)
{
    $time = mktime(0, 0, 0, $month, $day, $year);
    $weekday = date('w', $time);
    return ($weekday == 0 || $weekday == 6);
}

How to call a Web Service Method?

James' answer is correct, of course, but I should remind you that the whole ASMX thing is, if not obsolete, at least not the current method. I strongly suggest that you look into WCF, if only to avoid learning things you will need to forget.

Date format in the json output using spring boot

You most likely mean "yyyy-MM-dd" small latter 'm' would imply minutes section.

You should do two things

  • add spring.jackson.serialization.write-dates-as-timestamps:false in your application.properties this will disable converting dates to timestamps and instead use a ISO-8601 compliant format

  • You can than customize the format by annotating the getter method of you dateOfBirth property with @JsonFormat(pattern="yyyy-MM-dd")

Escape double quotes in Java

For a String constant you have no choice other than escaping via backslash.

Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.

Laravel 5 Eloquent where and or in Clauses

Using advanced wheres:

CabRes::where('m__Id', 46)
      ->where('t_Id', 2)
      ->where(function($q) {
          $q->where('Cab', 2)
            ->orWhere('Cab', 4);
      })
      ->get();

Or, even better, using whereIn():

CabRes::where('m__Id', 46)
      ->where('t_Id', 2)
      ->whereIn('Cab', $cabIds)
      ->get();

Generating PDF files with JavaScript

I maintain PDFKit, which also powers pdfmake (already mentioned here). It works in both Node and the browser, and supports a bunch of stuff that other libraries do not:

  • Embedding subsetted fonts, with support for unicode.
  • Lots of advanced text layout stuff (columns, page breaking, full unicode line breaking, basic rich text, etc.).
  • Working on even more font stuff for advanced typography (OpenType/AAT ligatures, contextual substitution, etc.). Coming soon: see the fontkit branch if you're interested.
  • More graphics stuff: gradients, etc.
  • Built with modern tools like browserify and streams. Usable both in the browser and node.

Check out http://pdfkit.org/ for a full tutorial to see for yourself what PDFKit can do. And for an example of what kinds of documents can be produced, check out the docs as a PDF generated from some Markdown files using PDFKit itself: http://pdfkit.org/docs/guide.pdf.

You can also try it out interactively in the browser here: http://pdfkit.org/demo/browser.html.

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

How to skip over an element in .map()?

You can use after of you method map(). The method filter() for example in your case:

var sources = images.map(function (img) {
  if(img.src.split('.').pop() === "json"){ // if extension is .json
    return null; // skip
  }
  else {
    return img.src;
  }
});

The method filter:

const sourceFiltered = sources.filter(item => item)

Then, only the existing items are in the new array sourceFiltered.

Swift 3 - Comparing Date objects

Another way to do it:

    switch date1.compare(date2) {
        case .orderedAscending:
            break

        case .orderedDescending:
            break;

        case .orderedSame:
            break
    }

How does cellForRowAtIndexPath work?

Basically it's designing your cell, The cellforrowatindexpath is called for each cell and the cell number is found by indexpath.row and section number by indexpath.section . Here you can use a label, button or textfied image anything that you want which are updated for all rows in the table. Answer for second question In cell for row at index path use an if statement

In Objective C

-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

 NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if(tableView == firstTableView)
  {
      //code for first table view 
      [cell.contentView addSubview: someView];
  }

  if(tableview == secondTableView)
  {
      //code for secondTableView 
      [cell.contentView addSubview: someView];
  }
  return cell;
}

In Swift 3.0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

  if(tableView == firstTableView)   {
     //code for first table view 
  }

  if(tableview == secondTableView)      {
     //code for secondTableView 
  }

  return cell
}

How can I zoom an HTML element in Firefox and Opera?

I would change zoom for transform in all cases because, as explained by other answers, they are not equivalent. In my case it was also necessary to apply transform-origin property to place the items where I wanted.

This worked for me in Chome, Safari and Firefox:

transform: scale(0.4);
transform-origin: top left;
-moz-transform: scale(0.4);
-moz-transform-origin: top left;

Traversing text in Insert mode

You seem to misuse vim, but that's likely due to not being very familiar with it.

The right way is to press Esc, go where you want to do a small correction, fix it, go back and keep editing. It is effective because Vim has much more movements than usual character forward/backward/up/down. After you learn more of them, this will happen to be more productive.

Here's a couple of use-cases:

  • You accidentally typed "accifentally". No problem, the sequence EscFfrdA will correct the mistake and bring you back to where you were editing. The Ff movement will move your cursor backwards to the first encountered "f" character. Compare that with Ctrl+DeldEnd, which does virtually the same in a casual editor, but takes more keystrokes and makes you move your hand out of the alphanumeric area of the keyboard.
  • You accidentally typed "you accidentally typed", but want to correct it to "you intentionally typed". Then Esc2bcw will erase the word you want to fix and bring you to insert mode, so you can immediately retype it. To get back to editing, just press A instead of End, so you don't have to move your hand to reach the End key.
  • You accidentally typed "mouse" instead of "mice". No problem - the good old Ctrl+w will delete the previous word without leaving insert mode. And it happens to be much faster to erase a small word than to fix errors within it. I'm so used to it that I had closed the browser page when I was typing this message...!
  • Repetition count is largely underused. Before making a movement, you can type a number; and the movement will be repeated this number of times. For example, 15h will bring your cursor 15 characters back and 4j will move your cursor 4 lines down. Start using them and you'll get used to it soon. If you made a mistake ten characters back from your cursor, you'll find out that pressing the key 10 times is much slower than the iterative approach to moving the cursor. So you can instead quickly type the keys 12h (as a rough of guess how many characters back that you need to move your cursor), and immediately move forward twice with ll to quickly correct the error.

But, if you still want to do small text traversals without leaving insert mode, follow rson's advice and use Ctrl+O. Taking the first example that I mentioned above, Ctrl+OFf will move you to a previous "f" character and leave you in insert mode.

jQuery Mobile: document ready vs. page events

Some of you might find this useful. Just copy paste it to your page and you will get a sequence in which events are fired in the Chrome console (Ctrl + Shift + I).

$(document).on('pagebeforecreate',function(){console.log('pagebeforecreate');});
$(document).on('pagecreate',function(){console.log('pagecreate');});
$(document).on('pageinit',function(){console.log('pageinit');});
$(document).on('pagebeforehide',function(){console.log('pagebeforehide');});
$(document).on('pagebeforeshow',function(){console.log('pagebeforeshow');});
$(document).on('pageremove',function(){console.log('pageremove');});
$(document).on('pageshow',function(){console.log('pageshow');});
$(document).on('pagehide',function(){console.log('pagehide');});
$(window).load(function () {console.log("window loaded");});
$(window).unload(function () {console.log("window unloaded");});
$(function () {console.log('document ready');});

You are not going see unload in the console as it is fired when the page is being unloaded (when you move away from the page). Use it like this:

$(window).unload(function () { debugger; console.log("window unloaded");});

And you will see what I mean.

WebView and Cookies on Android

If you are using Android Lollipop i.e. SDK 21, then:

CookieManager.getInstance().setAcceptCookie(true);

won't work. You need to use:

CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

I ran into same issue and the above line worked as a charm.

Safe Area of Xcode 9

Apple introduced the topLayoutGuide and bottomLayoutGuide as properties of UIViewController way back in iOS 7. They allowed you to create constraints to keep your content from being hidden by UIKit bars like the status, navigation or tab bar. These layout guides are deprecated in iOS 11 and replaced by a single safe area layout guide.

Refer link for more information.

What is the proper way to test if a parameter is empty in a batch file?

From IF /?:

If Command Extensions are enabled IF changes as follows:

IF [/I] string1 compare-op string2 command
IF CMDEXTVERSION number command
IF DEFINED variable command

......

The DEFINED conditional works just like EXISTS except it takes an environment variable name and returns true if the environment variable is defined.

How to create an empty array in PHP with predefined size?

Possibly related, if you want to initialize and fill an array with a range of values, use PHP's (wait for it...) range function:

$a = range(1, 5);  // array(1,2,3,4,5)
$a = range(0, 10, 2); // array(0,2,4,6,8,10)

How to make picturebox transparent?

Just use the Form Paint method and draw every Picturebox on it, it allows transparency :

    private void frmGame_Paint(object sender, PaintEventArgs e)
    {
        DoubleBuffered = true;
        for (int i = 0; i < Controls.Count; i++)
            if (Controls[i].GetType() == typeof(PictureBox))
            {
                var p = Controls[i] as PictureBox;
                p.Visible = false;
                e.Graphics.DrawImage(p.Image, p.Left, p.Top, p.Width, p.Height);
            }
    }

How to show changed file name only with git log?

Now I use the following to get the list of changed files my current branch has, comparing it to master (the compare-to branch is easily changed):

git log --oneline --pretty="format:" --name-only master.. | awk 'NF' | sort -u

Before, I used to rely on this:

git log --name-status <branch>..<branch> | grep -E '^[A-Z]\b' | sort -k 2,2 -u

which outputs a list of files only and their state (added, modified, deleted):

A   foo/bar/xyz/foo.txt
M   foo/bor/bar.txt
...

The -k2,2 option for sort, makes it sort by file path instead of the type of change (A, M, D,).

Python TypeError: not enough arguments for format string

I got the same error when using % as a percent character in my format string. The solution to this is to double up the %%.

Jackson with JSON: Unrecognized field, not marked as ignorable

Adding setters and getters solved the problem, what I felt is the actual issue was how to solve it but not how to suppress/ignore the error. I got the error "Unrecognized field.. not marked as ignorable.."

Though I use the below annotation on top of the class it was not able to parse the json object and give me the input

@JsonIgnoreProperties(ignoreUnknown = true)

Then I realized that I did not add setters and getters, after adding setters and getters to the "Wrapper" and to the "Student" it worked like a charm.

How do I split a string, breaking at a particular character?

You can use split to split the text.

As an alternative, you can also use match as follow

_x000D_
_x000D_
var str = 'john smith~123 Street~Apt 4~New York~NY~12345';_x000D_
matches = str.match(/[^~]+/g);_x000D_
_x000D_
console.log(matches);_x000D_
document.write(matches);
_x000D_
_x000D_
_x000D_

The regex [^~]+ will match all the characters except ~ and return the matches in an array. You can then extract the matches from it.

Android SharedPreferences in Fragment

The method getSharedPreferences is a method of the Context object, so just calling getSharedPreferences from a Fragment will not work...because it is not a Context! (Activity is an extension of Context, so we can call getSharedPreferences from it).

So you have to get your applications Context by

// this = your fragment
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);

How to create custom button in Android using XML Styles

<gradient android:startColor="#ffdd00"
    android:endColor="@color/colorPrimary"
    android:centerColor="#ffff" />

<corners android:radius="33dp"/>

<padding
    android:bottom="7dp"
    android:left="7dp"
    android:right="7dp"
    android:top="7dp"
    />

Express: How to pass app-instance to routes from a different file?

Or just do that:

var app = req.app

inside the Middleware you are using for these routes. Like that:

router.use( (req,res,next) => {
    app = req.app;
    next();
});

Adding CSRFToken to Ajax request

Everybody that using: var myVar = 'token', is probably the worst idea. I can print it dirrectly in the console. You need to encrypt on the client side, then decrypt on server side.

horizontal scrollbar on top and bottom of table

As far as I'm aware this isn't possible with HTML and CSS.

Make a directory and copy a file

You can use the shell for this purpose.

Set shl = CreateObject("WScript.Shell") 
shl.Run "cmd mkdir YourDir" & copy "

How to always show scrollbar

Setting this will do the trick. Change the @drwable for own style.

android:scrollbars="vertical"
            android:scrollbarAlwaysDrawVerticalTrack="true"
            android:fadeScrollbars="false"
            android:scrollbarThumbVertical="@drawable/scroll"`

Get specific ArrayList item

mainList.get(list_index)

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

How to style the option of an html "select" element?

It's 2017 and it IS possible to target specific select options. In my project I have a table with a class="variations", and the select options are in the table cell td="value", and the select has an ID select#pa_color. The option element also has a class option="attached" (among other class tags). If a user is logged in as a wholesale customer, they can see all of the color options. But retail customers are not allowed to purchase 2 color options, so I've disabled them

<option class="attached" disabled>color 1</option>
<option class="attached" disabled>color 2</option>

It took a little logic, but here is how I targeted the disabled select options.

CSS

table.variations td.value select#pa_color option.attached:disabled {
display: none !important;
}

With that, my color options are only visible to wholesale customers.

How do I change the font size and color in an Excel Drop Down List?

Unfortunately, you can't change the font size or styling in a drop-down list that is created using data validation.

You can style the text in a combo box, however. Follow the instructions here: Excel Data Validation Combo Box

How do I copy a hash in Ruby?

you can use below to deep copy Hash objects.

deeply_copied_hash = Marshal.load(Marshal.dump(original_hash))

Android: java.lang.SecurityException: Permission Denial: start Intent

My problem was that I had this: wrong Instead of this: correct

Run task only if host does not belong to a group

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names is a list (array) of all the groups the current host is in.

How to set the custom border color of UIView programmatically?

swift 3.0

self.uiTextView.layer.borderWidth = 0.5
    self.txtItemShortDes.layer.borderColor = UIColor(red:205.0/255.0, green:205.0/255.0, blue:205.0/255.0, alpha: 1.0).cgColor

How to parse Excel (XLS) file in Javascript/HTML5

If you want the simplest and tiniest way of reading an *.xlsx file in a browser then this library might do:

https://catamphetamine.github.io/read-excel-file/

<input type="file" id="input" />
import readXlsxFile from 'read-excel-file'

const input = document.getElementById('input')

input.addEventListener('change', () => {
  readXlsxFile(input.files[0]).then((data) => {
    // `data` is an array of rows
    // each row being an array of cells.
  })
})

In the example above data is raw string data. It can be parsed to JSON with a strict schema by passing schema argument. See API docs for an example of that.

API docs: http://npmjs.com/package/read-excel-file

Difference between left join and right join in SQL Server

I feel we may require AND condition in where clause of last figure of Outer Excluding JOIN so that we get the desired result of A Union B Minus A Interaction B. I feel query needs to be updated to

SELECT <select_list>
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL AND B.Key IS NULL

If we use OR , then we will get all the results of A Union B

Python: Generate random number between x and y which is a multiple of 5

If you don't want to do it all by yourself, you can use the random.randrange function.

For example import random; print random.randrange(10, 25, 5) prints a number that is between 10 and 25 (10 included, 25 excluded) and is a multiple of 5. So it would print 10, 15, or 20.

Bootstrap: Collapse other sections when one is expanded

Using data-parent, first solution is to stick to the example selector architecture

<div id="myGroup">
    <button class="btn dropdown" data-toggle="collapse" data-target="#keys" data-parent="#myGroup"><i class="icon-chevron-right"></i> Keys  <span class="badge badge-info pull-right">X</span></button>
    <button class="btn dropdown" data-toggle="collapse" data-target="#attrs" data-parent="#myGroup"><i class="icon-chevron-right"></i> Attributes</button>
    <button class="btn dropdown" data-toggle="collapse" data-target="#edit" data-parent="#myGroup"><i class="icon-chevron-right"></i> Edit Details</button>

    <div class="accordion-group">
        <div class="collapse indent" id="keys">
            keys
        </div>

        <div class="collapse indent" id="attrs">
            attrs
        </div>

        <div class="collapse" id="edit">
            edit
        </div>
    </div>
</div>

Demo (jsfiddle)

Second solution is to bind on the events and hide the other collapsible elements yourself.

var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
    $myGroup.find('.collapse.in').collapse('hide');
});

Demo (jsfiddle)

PS: the strange effect in the demos is caused by the min-height set for the example, just ignore that.


Edit: changed the JS event from show to show.bs.collapse as specified in Bootstrap documentation.

What's the best way to parse command line arguments?

I prefer optparse to getopt. It's very declarative: you tell it the names of the options and the effects they should have (e.g., setting a boolean field), and it hands you back a dictionary populated according to your specifications.

http://docs.python.org/lib/module-optparse.html

Get commit list between tags in git

To compare between latest commit of current branch and a tag:

git log --pretty=oneline HEAD...tag

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

How to open local file on Jupyter?

I would suggest you to test it firstly: copy this train.csv to the same directory as this jupyter script in and then change the path to train.csv to test whether this can be loaded successfully.

If yes, that means the previous path input is a problem

If not, that means the file it self denied your access to it, or its real filename can be something else like: train.csv.<hidden extension>

How can I analyze a heap dump in IntelliJ? (memory leak)

The best thing out there is Memory Analyzer (MAT), IntelliJ does not have any bundled heap dump analyzer.

Maintaining the final state at end of a CSS3 animation

Use animation-fill-mode: forwards;

animation-fill-mode: forwards;

The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count).

Note: The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.

Working example

_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  position :relative;_x000D_
  -webkit-animation: mymove 3ss forwards; /* Safari 4.0 - 8.0 */_x000D_
  animation: bubble 3s forwards;_x000D_
  /* animation-name: bubble; _x000D_
  animation-duration: 3s;_x000D_
  animation-fill-mode: forwards; */_x000D_
}_x000D_
_x000D_
/* Safari */_x000D_
@-webkit-keyframes bubble  {_x000D_
  0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}_x000D_
_x000D_
/* Standard syntax */_x000D_
@keyframes bubble  {_x000D_
   0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}
_x000D_
<h1>The keyframes </h1>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

What is Parse/parsing?

Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number.

String tenString = "10"

//This won't work since you can't add an integer and a string
Integer result = 20 + tenString;

//This will set result to 30
Integer result = 20 + Integer.parseInt(tenString);

How to change status bar color to match app in Lollipop? [Android]

To set the status bar color, create a style.xml file under res/values-v21 folder with this content:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppBaseTheme" parent="AppTheme">
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@color/blue</item>
    </style>

</resources>

How can I iterate through a string and also know the index (current position)?

Like this:


    std::string s("Test string");
    std::string::iterator it = s.begin();

    //Use the iterator...
    ++it;
    //...

    std::cout << "index is: " << std::distance(s.begin(), it) << std::endl;

Call to undefined function oci_connect()

  1. Check your php –version as like as PHP 5.6.32 (cli) (built: Oct 25 2017 16:02:15).
  2. Using the OCI8 extension to access Oracle Database. So Download php_oci8.dll from 1https://pecl.php.net/package/oci8/2.0.8/windows. (5.6 Thread Safe (TS) x86 ) php_oci8.dll must be the same version with your php version.Then unzipped it and you will find 1.php_oci8.dll 2.php_oci8_11g.dll (as per your oralce version) these two file pasted into your
    (xampp\php\ext) folder.

  3. Open your php.ini file and add these extension=php_oci8.dll extension=php_oci8_11g.dll

  4. Check your oracle version and service name using these commands

    1. Open your cmd
    2. sqlplus / as sysdba
    3. select * from v$version; Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production, our oracle version is 11g so we can use instantclient_11_1 (Instant Client 32-bit) downloads from https://www.oracle.com/technetwork/topics/winsoft-085727.html
  5. show parameter service_name; service_name is orcl (you should remember this service name)

  6. After downloading instantclient_11_1 unzipped it and then pasted in your Local Disk. And copy the path C:\instantclient_11_1 and then set this path as your user variable & system variable. Note is that my code is working without setting path variable.

  7. Open your cmd and enter into SQL, create your schema following these commands

    1. sqlplus / as sysdba
    2. create user dbname identified by pass123;
    3. grant connect,resource to dbname;

    4. Create table user_info and insert data into your table and commit out. Note: you must commit your data either data is not inserted.

    5. Then this script run in your htdocs

_x000D_
_x000D_
<html>_x000D_
<head><title>Oracle demo</title></head>_x000D_
<body>_x000D_
<?php_x000D_
_x000D_
// Create connection to Oracle_x000D_
$conn = oci_connect("dbname", "pass123", "//localhost/orcl");  // orcl is your service_name_x000D_
_x000D_
$query = 'select * from user_info';_x000D_
$stid = oci_parse($conn, $query);_x000D_
$r = oci_execute($stid);_x000D_
_x000D_
// Fetch each row in an associative array_x000D_
print '<table border="1">';_x000D_
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC)) {_x000D_
   print '<tr>';_x000D_
   foreach ($row as $item) {_x000D_
       print '<td>'.($item !== null ? htmlentities($item, ENT_QUOTES) : '&nbsp').'</td>';_x000D_
   }_x000D_
   print '</tr>';_x000D_
}_x000D_
print '</table>';
_x000D_
_x000D_
_x000D_

Default value in Doctrine

Adding to @romanb brilliant answer.

This adds a little overhead in migration, because you obviously cannot create a field with not null constraint and with no default value.

// this up() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "postgresql");

//lets add property without not null contraint        
$this->addSql("ALTER TABLE tablename ADD property BOOLEAN");

//get the default value for property       
$object = new Object();
$defaultValue = $menuItem->getProperty() ? "true":"false";

$this->addSql("UPDATE tablename SET property = {$defaultValue}");

//not you can add constraint
$this->addSql("ALTER TABLE tablename ALTER property SET NOT NULL");

With this answer, I encourage you to think why do you need the default value in the database in the first place? And usually it is to allow creating objects with not null constraint.

How to ignore a property in class if null, using json.net

To expound slightly on GlennG's very helpful answer (translating the syntax from C# to VB.Net is not always "obvious") you can also decorate individual class properties to manage how null values are handled. If you do this don't use the global JsonSerializerSettings from GlennG's suggestion, otherwise it will override the individual decorations. This comes in handy if you want a null item to appear in the JSON so the consumer doesn't have to do any special handling. If, for example, the consumer needs to know an array of optional items is normally available, but is currently empty... The decoration in the property declaration looks like this:

<JsonPropertyAttribute("MyProperty", DefaultValueHandling:=NullValueHandling.Include)> Public Property MyProperty As New List(of String)

For those properties you don't want to have appear at all in the JSON change :=NullValueHandling.Include to :=NullValueHandling.Ignore. By the way - I've found that you can decorate a property for both XML and JSON serialization just fine (just put them right next to each other). This gives me the option to call the XML serializer in dotnet or the NewtonSoft serializer at will - both work side-by-side and my customers have the option to work with XML or JSON. This is slick as snot on a doorknob since I have customers that require both!

phpMyAdmin - The MySQL Extension is Missing

Just check your php.ini file, In this file Semicolon(;) used for comment if you see then remove semicolon ;.

;extension=mysql.dll

Now your extension is enable but you need to restart appache

extension=mysql.dll

How to initialize struct?

  1. Will "length" ever deviate from the real length of "s". If the answer is no, then you don't need to store length, because strings store their length already, and you can just call s.Length.

  2. To get the syntax you asked for, you can implement an "implicit" operator like so:

    static implicit operator MyStruct(string s) {
        return new MyStruct(...);
    }
    
  3. The implicit operator will work, regardless of whether you make your struct mutable or not.

Facebook how to check if user has liked page and show content?

Here's a working example, which is a fork of this answer:

$(document).ready(function(){
    FB.login(function(response) {
        if (response.status == 'connected') {
            var user_id = response.authResponse.userID;
            var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
            var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid="+user_id;

            FB.api({
                method: 'fql.query',
                query: fql_query
            },
            function(response){
                if (response[0]) {
                    $("#container_like").show();
                } else {
                    $("#container_notlike").show();
                }
            }
            );    
        } else {
        // user is not logged in
        }
    });
});

I used the FB.api method (JavaScript SDK), instead of FB.Data.query, which is deprecated. Or you can use the Graph API like with this example:

$(document).ready(function() {
    FB.login(function(response) {
        if (response.status == 'connected') {
            var user_id = response.authResponse.userID;
            var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
            var fql_query = "SELECT uid FROM page_fan WHERE page_id=" + page_id + " and uid=" + user_id;

            FB.api('/me/likes/'+page_id, function(response) {
                if (response.data[0]) {
                    $("#container_like").show();
                } else {
                    $("#container_notlike").show();
                }
            });
        } else {
            // user is not logged in
        }
    });
});?

Why doesn't java.io.File have a close method?

java.io.File doesn't represent an open file, it represents a path in the filesystem. Therefore having close method on it doesn't make sense.

Actually, this class was misnamed by the library authors, it should be called something like Path.

How do I get a file's directory using the File object?

I found this more useful for getting the absolute file location.

File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

HTML table: keep the same width for columns

In your case, since you are only showing 3 columns:

Name    Value       Business
  or
Name    Business    Ecommerce Pro

why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.

How to use if statements in underscore.js templates?

To check for null values you could use _.isNull from official documentation

isNull_.isNull(object)

Returns true if the value of object is null.

_.isNull(null);
=> true
_.isNull(undefined);
=> false

New og:image size for Facebook share?

Tried to get the 1200x630 image working. Facebook kept complaining that it couldn't read the image, or that it was too small (it was a jpeg image ~150Kb).

Switched to a 200x200 size image, worked perfectly.

https://developers.facebook.com/tools/debug/og/object?q=drift.team

Javascript Object push() function

Do :


var data = new Array();
var tempData = new Array();

taking input of a string word by word

(This is for the benefit of others who may refer)

You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.

#include<iostream>
using namespace std;

main()
{
    char word[50];
    cin>>word;
    while(word){
        //Do stuff with word[]
        cin>>word;
    }
}

How can I delete all cookies with JavaScript?

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

setTimeout in for-loop does not print consecutive values

You can use the extra arguments to setTimeout to pass parameters to the callback function.

for (var i = 1; i <= 2; i++) {
    setTimeout(function(j) { alert(j) }, 100, i);
}

Note: This doesn't work on IE9 and below browsers.

using where and inner join in mysql

Try this:

SELECT Locations.Name, Schools.Name
FROM Locations
INNER JOIN School_Locations ON School_Locations.Locations_Id = Locations.Id
INNER JOIN Schools ON School.Id = Schools_Locations.School_Id
WHERE Locations.Type = "coun"

You can join Locations to School_Locations and then School_Locations to School. This forms a set of all related Locations and Schools, which you can then widdle down using the WHERE clause to those whose Location is of type "coun."

Delete item from array and shrink array

Using ArrayUtils.removeElement(Object[],Object) from org.apache.commons.lang is by far the easiest way to do this.

int[] numbers = {1,2,3,4,5,6,7};
//removing number 1
numbers =(int[])ArrayUtils.removeElement(numbers, 1);

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

Go to:

Settings -> Preferences You will see a dialog box. There click the Auto-completion tab where you can set the auto complete option.See image below: Follow it

If your code not detected automatically then you choose your coding language form Language menu

How to use LDFLAGS in makefile

In more complicated build scenarios, it is common to break compilation into stages, with compilation and assembly happening first (output to object files), and linking object files into a final executable or library afterward--this prevents having to recompile all object files when their source files haven't changed. That's why including the linking flag -lm isn't working when you put it in CFLAGS (CFLAGS is used in the compilation stage).

The convention for libraries to be linked is to place them in either LOADLIBES or LDLIBS (GNU make includes both, but your mileage may vary):

LDLIBS=-lm

This should allow you to continue using the built-in rules rather than having to write your own linking rule. For other makes, there should be a flag to output built-in rules (for GNU make, this is -p). If your version of make does not have a built-in rule for linking (or if it does not have a placeholder for -l directives), you'll need to write your own:

client.o: client.c
    $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ $<

client: client.o
    $(CC) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $@

VSCode regex find & replace submatch math?

For beginners, the accepted answer is correct, but a little terse if you're not that familiar with either VSC or Regex.

So, in case this is your first contact with either:

To find and modify text,

  1. In the "Find" step, you can use regex with "capturing groups," e.g. I want to find (group1) and (group2), using parentheses. This would find the same text as I want to find group1 and group2, but with the difference that you can then reference group1 and group2 in the next step:

  2. In the "Replace" step, you can refer to the capturing groups via $1, $2 etc, so you could change the sentence to I found $1 and $2 having a picnic, which would output I found group1 and group2 having a picnic.

Notes:

  • Instead of just a string, anything inside or outside the () can be a regular expression.

  • $0 refers to the whole match

How do you find all subclasses of a given class in Java?

It should be noted as well that this will of course only find all those subclasses that exist on your current classpath. Presumably this is OK for what you are currently looking at, and chances are you did consider this, but if you have at any point released a non-final class into the wild (for varying levels of "wild") then it is entirely feasible that someone else has written their own subclass that you will not know about.

Thus if you happened to be wanting to see all subclasses because you want to make a change and are going to see how it affects subclasses' behaviour - then bear in mind the subclasses that you can't see. Ideally all of your non-private methods, and the class itself should be well-documented; make changes according to this documentation without changing the semantics of methods/non-private fields and your changes should be backwards-compatible, for any subclass that followed your definition of the superclass at least.

Python conversion from binary string to hexadecimal

format(int(bits, 2), '0' + str(len(bits) / 4) + 'x')

How to check if a file exists in a folder?

This is a way to see if any XML-files exists in that folder, yes.

To check for specific files use File.Exists(path), which will return a boolean indicating wheter the file at path exists.

Split string by single spaces

You can even develop your own split function (I know, little old-fashioned):

size_t split(const std::string &txt, std::vector<std::string> &strs, char ch)
{
    size_t pos = txt.find( ch );
    size_t initialPos = 0;
    strs.clear();

    // Decompose statement
    while( pos != std::string::npos ) {
        strs.push_back( txt.substr( initialPos, pos - initialPos ) );
        initialPos = pos + 1;

        pos = txt.find( ch, initialPos );
    }

    // Add the last one
    strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );

    return strs.size();
}

Then you just need to invoke it with a vector<string> as argument:

int main()
{
    std::vector<std::string> v;

    split( "This  is a  test", v, ' ' );
    dump( cout, v );

    return 0;
}

Find the code for splitting a string in IDEone.

Hope this helps.

Sass and combined child selector

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red

Difference between a class and a module

Basically, the module cannot be instantiated. When a class includes a module, a proxy superclass is generated that provides access to all the module methods as well as the class methods.

A module can be included by multiple classes. Modules cannot be inherited, but this "mixin" model provides a useful type of "multiple inheritrance". OO purists will disagree with that statement, but don't let purity get in the way of getting the job done.


(This answer originally linked to http://www.rubycentral.com/pickaxe/classes.html, but that link and its domain are no longer active.)

Is there any use for unique_ptr with array?

One reason you might use a unique_ptr is if you don't want to pay the runtime cost of value-initializing the array.

std::vector<char> vec(1000000); // allocates AND value-initializes 1000000 chars

std::unique_ptr<char[]> p(new char[1000000]); // allocates storage for 1000000 chars

The std::vector constructor and std::vector::resize() will value-initialize T - but new will not do that if T is a POD.

See Value-Initialized Objects in C++11 and std::vector constructor

Note that vector::reserve is not an alternative here: Is accessing the raw pointer after std::vector::reserve safe?

It's the same reason a C programmer might choose malloc over calloc.

Generating random integer from a range

A fast, somewhat better than yours, but still not properly uniform distributed solution is

output = min + (rand() % static_cast<int>(max - min + 1))

Except when the size of the range is a power of 2, this method produces biased non-uniform distributed numbers regardless the quality of rand(). For a comprehensive test of the quality of this method, please read this.

Web.Config Debug/Release

The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.

In your .Debug/.Release files, you need to add the following parameter in your connection string fields:

xdt:Transform="SetAttributes" xdt:Locator="Match(name)"

This will cause each connection string line to find the matching name and update the attributes accordingly.

Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.

Here's an example from one of my apps. Here's the web.config file section:

<connectionStrings>
      <add name="EAF" connectionString="[Test Connection String]" />
</connectionString>

And here's the web.config.release section doing the proper transform:

<connectionStrings>
      <add name="EAF" connectionString="[Prod Connection String]"
           xdt:Transform="SetAttributes"
           xdt:Locator="Match(name)" />
</connectionStrings>

One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.

For more details you can see the MSDN documentation

https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx

How to change the value of ${user} variable used in Eclipse templates

It seems that your best bet is to redefine the java user.name variable either at your command line, or using the eclipse.ini file in your eclipse install root directory.

This seems to work fine for me:

-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Duser.name=Davide Inglima
-Xms40m
-Xmx512m    

Update:

http://morlhon.net/blog/2005/09/07/eclipse-username/ is a dead link...

Here's a new one: https://web.archive.org/web/20111225025454/http://morlhon.net:80/blog/2005/09/07/eclipse-username/

How to check if a date is greater than another in Java?

Parse the string into date, then compare using compareTo, before or after

Date d = new Date();
d.compareTo(anotherDate)

i.e

Date date1 = new SimpleDateFormat("MM/dd/yyyy").parse(date1string)
Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse(date2string)

date1.compareTo(date2);

Copying the comment provided below by @MuhammadSaqib to complete this answer.

Returns the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument, and a value greater than 0 if this Date is after the Date argument. and NullPointerException - if anotherDate is null.

javadoc for compareTo http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#compareTo(java.util.Date)

Groovy executing shell commands

To add one more important information to above provided answers -

For a process

def proc = command.execute();

always try to use

def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)

rather than

def output = proc.in.text;

to capture the outputs after executing commands in groovy as the latter is a blocking call (SO question for reason).

VB.NET Connection string (Web.Config, App.Config)

Connection in APPConfig

<connectionStrings>
  <add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"   providerName="System.Data.SqlClient" />
</connectionStrings>

In Class.Cs

public string ConnectionString
{
    get
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    }
}

What is the equivalent of Java static methods in Kotlin?

except Michael Anderson's answer, i have coding with other two way in my project.

First:

you can white all variable to one class. created a kotlin file named Const

object Const {
    const val FIRST_NAME_1 = "just"
    const val LAST_NAME_1 = "YuMu"
}

You can use it in kotlin and java code

 Log.d("stackoverflow", Const.FIRST_NAME_1)

Second:

You can use Kotlin's extension function
created a kotlin file named Ext, below code is the all code in Ext file

package pro.just.yumu

/**
 * Created by lpf on 2020-03-18.
 */

const val FIRST_NAME = "just"
const val LAST_NAME = "YuMu"

You can use it in kotlin code

 Log.d("stackoverflow", FIRST_NAME)

You can use it in java code

 Log.d("stackoverflow", ExtKt.FIRST_NAME);

How can I make SMTP authenticated in C#

using System.Net;
using System.Net.Mail;

using(SmtpClient smtpClient = new SmtpClient())
{
    var basicCredential = new NetworkCredential("username", "password"); 
    using(MailMessage message = new MailMessage())
    {
        MailAddress fromAddress = new MailAddress("[email protected]"); 

        smtpClient.Host = "mail.mydomain.com";
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = basicCredential;

        message.From = fromAddress;
        message.Subject = "your subject";
        // Set IsBodyHtml to true means you can send HTML email.
        message.IsBodyHtml = true;
        message.Body = "<h1>your message body</h1>";
        message.To.Add("[email protected]"); 

        try
        {
            smtpClient.Send(message);
        }
        catch(Exception ex)
        {
            //Error, could not send the message
            Response.Write(ex.Message);
        }
    }
}

You may use the above code.

Convert or extract TTC font to TTF - how to?

http://transfonter.org/ will do the job for you. Just upload your .ttc and it will give you a folder with all the fonttypes in .ttf files.

Removing Conda environment

This worked for me:

conda env remove --name tensorflow

Initial bytes incorrect after Java AES/CBC decryption

In this answer I choose to approach the "Simple Java AES encrypt/decrypt example" main theme and not the specific debugging question because I think this will profit most readers.

This is a simple summary of my blog post about AES encryption in Java so I recommend reading through it before implementing anything. I will however still provide a simple example to use and give some pointers what to watch out for.

In this example I will choose to use authenticated encryption with Galois/Counter Mode or GCM mode. The reason is that in most case you want integrity and authenticity in combination with confidentiality (read more in the blog).

AES-GCM Encryption/Decryption Tutorial

Here are the steps required to encrypt/decrypt with AES-GCM with the Java Cryptography Architecture (JCA). Do not mix with other examples, as subtle differences may make your code utterly insecure.

1. Create Key

As it depends on your use-case, I will assume the simplest case: a random secret key.

SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
SecretKey secretKey = SecretKeySpec(key, "AES");

Important:

2. Create the Initialization Vector

An initialization vector (IV) is used so that the same secret key will create different cipher texts.

byte[] iv = new byte[12]; //NEVER REUSE THIS IV WITH SAME KEY
secureRandom.nextBytes(iv);

Important:

3. Encrypt with IV and Key

final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv); //128 bit auth tag length
cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
byte[] cipherText = cipher.doFinal(plainText);

Important:

  • use 16 byte / 128 bit authentication tag (used to verify integrity/authenticity)
  • the authentication tag will be automatically appended to the cipher text (in the JCA implementation)
  • since GCM behaves like a stream cipher, no padding is required
  • use CipherInputStream when encrypting large chunks of data
  • want additional (non-secret) data checked if it was changed? You may want to use associated data with cipher.updateAAD(associatedData); More here.

3. Serialize to Single Message

Just append IV and ciphertext. As stated above, the IV doesn't need to be secret.

ByteBuffer byteBuffer = ByteBuffer.allocate(iv.length + cipherText.length);
byteBuffer.put(iv);
byteBuffer.put(cipherText);
byte[] cipherMessage = byteBuffer.array();

Optionally encode with Base64 if you need a string representation. Either use Android's or Java 8's built-in implementation (do not use Apache Commons Codec - it's an awful implementation). Encoding is used to "convert" byte arrays to string representation to make it ASCII safe e.g.:

String base64CipherMessage = Base64.getEncoder().encodeToString(cipherMessage);

4. Prepare Decryption: Deserialize

If you have encoded the message, first decode it to byte array:

byte[] cipherMessage = Base64.getDecoder().decode(base64CipherMessage)

Important:

5. Decrypt

Initialize the cipher and set the same parameters as with the encryption:

final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
//use first 12 bytes for iv
AlgorithmParameterSpec gcmIv = new GCMParameterSpec(128, cipherMessage, 0, 12);
cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmIv);
//use everything from 12 bytes on as ciphertext
byte[] plainText = cipher.doFinal(cipherMessage, 12, cipherMessage.length - 12);

Important:

  • don't forget to add associated data with cipher.updateAAD(associatedData); if you added it during encryption.

A working code snippet can be found in this gist.


Note that most recent Android (SDK 21+) and Java (7+) implementations should have AES-GCM. Older versions may lack it. I still choose this mode, since it is easier to implement in addition to being more efficient compared to similar mode of Encrypt-then-Mac (with e.g. AES-CBC + HMAC). See this article on how to implement AES-CBC with HMAC.

What is the best way to test for an empty string in Go?

Assuming that empty spaces and all leading and trailing white spaces should be removed:

import "strings"
if len(strings.TrimSpace(s)) == 0 { ... }

Because :
len("") // is 0
len(" ") // one empty space is 1
len(" ") // two empty spaces is 2

Implement a loading indicator for a jQuery AJAX call

There is a global configuration using jQuery. This code runs on every global ajax request.

<div id='ajax_loader' style="position: fixed; left: 50%; top: 50%; display: none;">
    <img src="themes/img/ajax-loader.gif"></img>
</div>

<script type="text/javascript">
    jQuery(function ($){
        $(document).ajaxStop(function(){
            $("#ajax_loader").hide();
         });
         $(document).ajaxStart(function(){
             $("#ajax_loader").show();
         });    
    });    
</script>

Here is a demo: http://jsfiddle.net/sd01fdcm/

How to load data from a text file in a PostgreSQL database?

There's Pgloader that uses the aforementioned COPY command and which can load data from csv (and MySQL, SQLite and dBase). It's also using separate threads for reading and copying data, so it's quite fast (interestingly enough, it got written from Python to Common Lisp and got a 20 to 30x speed gain, see blog post).

To load the csv file one needs to write a little configuration file, like

LOAD CSV  
  FROM 'path/to/file.csv' (x, y, a, b, c, d)  
  INTO postgresql:///pgloader?csv (a, b, d, c)  
  …

How to execute 16-bit installer on 64-bit Win7?

I am mostly posting this in case someone comes along and is not aware that VB2005 and VB2008 have update utilities that convert older VB versions to it's format. Especially since no one bothered to point that fact out.

Points taken, but maintenance of this VB6 product is unavoidable. It would also be costly in man-hours to replace the Sheridan controls with native ones. Simply developing on a 32-bit machine would be a better alternative than doing that. I would like to install everything on Win7 64-bit ideally. – CJ7

Have you tried utilizing the code upgrade functionality of VB Express 2005+?

If not, 1. Make a copy of your code - folder and all. 2. Import the project into VB express 2005. This will activate the update wizard. 3. Debug and get the app running. 4. Create a new installer utilizing MS free tool. 5. You now have a 32 bit application with a 32 bit installer.

Until you do this, you will never know how difficult or hard it will be to update and modernize the program. It is quite possible that the wizard will update the Sheridan controls to the VB 2005 controls. Again, you will not know if it does and how well it does it until you try it.

Alternatively, stick with the 32 Bit versions of Windows 7 and 8. I have Windows 7 x64 and a program that will not run. However, the program will run in Windows 7 32 bit as well as Windows 8 RC 32 bit. Under Windows 8 RC 32, I was prompted to enable 16 bit emulation which I did and the program rand quite fine afterwords.

Convert a char to upper case using regular expressions (EditPad Pro)

You can also capitalize the first letter of the match using \I1 and \I2 etc instead of $1 and $2.

pandas dataframe groupby datetime month

Managed to do it:

b = pd.read_csv('b.dat')
b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')
b.groupby(by=[b.index.month, b.index.year])

Or

b.groupby(pd.Grouper(freq='M'))  # update for v0.21+

Dynamically create and submit form

Try with this code -
It is a totally dynamic solution:

    var form = $(document.createElement('form'));
    $(form).attr("action", "reserves.php");
    $(form).attr("method", "POST");

    var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val("bla");
    $(form).append($(input));
    $(form).submit();

How to change the height of a <br>?

What works for me is adding this inline between paragraph tags... not the best solution though.

<br style="line-height:32px">

-------- Edit ---------

I ran into issues with PC/Mac with this... It gives the text the new line-height but does not do the line-break... You may want to do some tests yourself. Sorry!

changing source on html5 video tag

I hated all these answers because they were too short or relied on other frameworks.

Here is "one" vanilla JS way of doing this, working in Chrome, please test in other browsers:

http://jsfiddle.net/mattdlockyer/5eCEu/2/

HTML:

<video id="video" width="320" height="240"></video>

JS:

var video = document.getElementById('video');
var source = document.createElement('source');

source.setAttribute('src', 'http://www.tools4movies.com/trailers/1012/Kill%20Bill%20Vol.3.mp4');

video.appendChild(source);
video.play();

setTimeout(function() {  
    video.pause();

    source.setAttribute('src', 'http://www.tools4movies.com/trailers/1012/Despicable%20Me%202.mp4'); 

    video.load();
    video.play();
}, 3000);

LINQ Where with AND OR condition

Well, you're going to have to check for null somewhere. You could do something like this:

from item in db.vw_Dropship_OrderItems
         where (listStatus == null || listStatus.Contains(item.StatusCode)) 
            && (listMerchants == null || listMerchants.Contains(item.MerchantId))
         select item;

How do I break out of nested loops in Java?

Below is an example where "break" statement pushes the cursor out of the for loop whenever the condition is met.

public class Practice3_FindDuplicateNumber {

    public static void main(String[] args) {
        Integer[] inp = { 2, 3, 4, 3, 3 };
        Integer[] aux_arr = new Integer[inp.length];
        boolean isduplicate = false;
        for (int i = 0; i < aux_arr.length; i++) {

            aux_arr[i] = -1;

        }
        outer: for (int i = 0; i < inp.length; i++) {
            if (aux_arr[inp[i]] == -200) {
                System.out.println("Duplicate Found at index: " + i + " Carrying value: " + inp[i]);
                isduplicate = true;
                break outer;
            } else {
                aux_arr[inp[i]] = -200;
            }
        }

        for (Integer integer : aux_arr) {
            System.out.println(integer);
        }

        if (isduplicate == false) {
            System.out.println("No Duplicates!!!!!");
        } else {
            System.out.println("Duplicates!!!!!");
        }
    }

}

How to make audio autoplay on chrome

temp fix

$(document).on('click', "#buttonStarter", function(evt)
{
var context = new AudioContext();
document.getElementById('audioPlayer').play();
$("#buttonStarter").hide()
$("#Game").show()
});

Or use a custom player to trigger play http://zohararad.github.io/audio5js/

Note : Autoplay will be renabled in 31 December

Git, How to reset origin/master to a commit?

Since I had a similar situation, I thought I'd share my situation and how these answers helped me (thanks everyone).

So I decided to work locally by amending my last commit every time I wanted to save my progress on the main branch (I know, I should've branched out, committed on that, kept pushing and later merge back to master).

One late night, in paranoid fear of loosing my progress to hardware failure or something out of the ether, I decided to push master to origin. Later I kept amending my local master branch and when I decided it's time to push again, I was faced with different master branches and found out I can't amend origin/upstream (duh!) like I can local development branches.

So I didn't checkout master locally because I already was after a commit. Master was unchanged. I didn't even need to reset --hard, my current commit was OK.

I just forced push to origin, without even specifying what commit I wanted to force on master since in this case it's whatever HEAD is at. Checked git diff master..origin/master so there weren't any differences and that's it. All fixed. Thanks! (I know, I'm a git newbie, please forgive!).

So if you're already OK with your master branch locally, just:

git push --force origin master
git diff master..origin/master

Array initialization in Perl

If I understand you, perhaps you don't need an array of zeroes; rather, you need a hash. The hash keys will be the values in the other array and the hash values will be the number of times the value exists in the other array:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my %tallies;
$tallies{$_} ++ for @other_array;

print "$_ => $tallies{$_}\n" for sort {$a <=> $b} keys %tallies;    

Output:

0 => 3
1 => 1
2 => 2
3 => 3
4 => 1

To answer your specific question more directly, to create an array populated with a bunch of zeroes, you can use the technique in these two examples:

my @zeroes = (0) x 5;            # (0,0,0,0,0)

my @zeroes = (0) x @other_array; # A zero for each item in @other_array.
                                 # This works because in scalar context
                                 # an array evaluates to its size.

How to set image button backgroundimage for different state?

mhh. I got another solution which helped me, 'cause I just have two different sates:

  • either the item is not clicked
  • or it is clicked and so it will be highlighted

In my .xml I define the ImageButton like this:

 <ImageButton
    android:id="@+id/imageButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/selector" />

The corresponding selector file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ico_100_checked" android:state_selected="true"/>
    <item android:drawable="@drawable/ico_100_unchecked"/>

</selector>

And in my onCreate I call:

final ImageButton ib = (ImageButton) value.findViewById(R.id.imageButton);

    OnClickListener ocl =new OnClickListener() {
        @Override
        public void onClick(View button) {
            if (button.isSelected()){
                button.setSelected(false);
            } else {
                ib.setSelected(false);
                //put all the other buttons you might want to disable here...
                button.setSelected(true);
            }
        }
    };

ib.setOnClickListener(ocl);
//add ocl to all the other buttons

done. hope this helps. took me a while to figure out.

how to convert 2d list to 2d numpy array?

np.array() is even more powerful than what unutbu said above. You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:

aArray=np.array([1,1,1])

bArray=np.array([2,2,2])

aList=[aArray, bArray]

xArray=np.array(aList)

xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.

How do I check if a Sql server string is null or empty

When dealing with VARCHAR/NVARCHAR data most other examples treat white-space the same as empty string which is equal to C# function IsNullOrWhiteSpace.

This version respects white-space and works the same as the C# function IsNullOrEmpty:

IIF(ISNULL(DATALENGTH(val), 0) = 0, whenTrueValue, whenFalseValue)

Simple test:

SELECT
    '"' + val + '"' AS [StrValue],
    IIF(ISNULL(DATALENGTH(val), 0) = 0, 'TRUE', 'FALSE') AS IsNullOrEmpty
FROM ( VALUES 
    (NULL), 
    (''), 
    (' '), 
    ('a'), 
    ('a ')
) S (val)

What does the arrow operator, '->', do in Java?

This one is useful as well when you want to implement a functional interface

Runnable r = ()-> System.out.print("Run method");

is equivalent to

Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.print("Run method");
        }
};

Youtube iframe wmode issue

recently I saw that sometimes the flash player doesn't recognize &wmode=opaque, istead you should pass &WMode=opaque too (notice the uppercase).

Perform .join on value in array of objects

lets say the objects array is referenced by the variable users

If ES6 can be used then the easiest solution will be:

users.map(user => user.name).join(', ');

If not, and lodash can be used so :

 _.map(users, function(user) {
     return user.name;
 }).join(', ');

How to split the filename from a full path in batch?

Parse a filename from the fully qualified path name (e.g., c:\temp\my.bat) to any component (e.g., File.ext).

Single line of code:

For %%A in ("C:\Folder1\Folder2\File.ext") do (echo %%~fA)

You can change out "C:\Folder1\Folder2\File.ext" for any full path and change "%%~fA" for any of the other options you will find by running "for /?" at the command prompt.

Elaborated Code

set "filename=C:\Folder1\Folder2\File.ext"
For %%A in ("%filename%") do (
    echo full path: %%~fA
    echo drive: %%~dA
    echo path: %%~pA
    echo file name only: %%~nA
    echo extension only: %%~xA
    echo expanded path with short names: %%~sA
    echo attributes: %%~aA
    echo date and time: %%~tA
    echo size: %%~zA
    echo drive + path: %%~dpA
    echo name.ext: %%~nxA
    echo full path + short name: %%~fsA)

Standalone Batch Script
Save as C:\cmd\ParseFn.cmd.

Add C:\cmd to your PATH environment variable and use it to store all of you reusable batch scripts.

@echo off
@echo ::___________________________________________________________________::
@echo ::                                                                   ::
@echo ::                              ParseFn                              ::
@echo ::                                                                   ::
@echo ::                           Chris Advena                            ::
@echo ::___________________________________________________________________::
@echo.

::
:: Process arguements
::
if "%~1%"=="/?" goto help
if "%~1%"=="" goto help
if "%~2%"=="/?" goto help
if "%~2%"=="" (
    echo !!! Error: ParseFn requires two inputs. !!!
    goto help)

set in=%~1%
set out=%~2%
:: echo "%in:~3,1%"   "%in:~0,1%"
if "%in:~3,1%"=="" (
    if "%in:~0,1%"=="/" (
    set in=%~2%
    set out=%~1%)
)

::
:: Parse filename
::
set "ret="
For %%A in ("%in%") do (
    if "%out%"=="/f" (set ret=%%~fA)
    if "%out%"=="/d" (set ret=%%~dA)
    if "%out%"=="/p" (set ret=%%~pA)
    if "%out%"=="/n" (set ret=%%~nA)
    if "%out%"=="/x" (set ret=%%~xA)
    if "%out%"=="/s" (set ret=%%~sA)
    if "%out%"=="/a" (set ret=%%~aA)
    if "%out%"=="/t" (set ret=%%~tA)
    if "%out%"=="/z" (set ret=%%~zA)
    if "%out%"=="/dp" (set ret=%%~dpA)
    if "%out%"=="/nx" (set ret=%%~nxA)
    if "%out%"=="/fs" (set ret=%%~fsA)
)
echo ParseFn result: %ret%
echo.

goto end
:help
@echo off
:: @echo ::___________________________________________________________________::
:: @echo ::                                                                   ::
:: @echo ::                           ParseFn Help                            ::
:: @echo ::                                                                   ::
:: @echo ::                           Chris Advena                            ::
:: @echo ::___________________________________________________________________::
@echo.
@echo ParseFn parses a fully qualified path name (e.g., c:\temp\my.bat)
@echo into the requested component, such as drive, path, filename, 
@echo extenstion, etc.
@echo.
@echo Syntax: /switch filename
@echo where,
@echo   filename is a fully qualified path name including drive, 
@echo   folder(s), file name, and extension
@echo.
@echo   Select only one switch:
@echo       /f - fully qualified path name
@echo       /d - drive letter only
@echo       /p - path only
@echo       /n - file name only
@echo       /x - extension only
@echo       /s - expanded path contains short names only
@echo       /a - attributes of file
@echo       /t - date/time of file
@echo       /z - size of file
@echo      /dp - drive + path
@echo      /nx - file name + extension
@echo      /fs - full path + short name
@echo.

:end
:: @echo ::___________________________________________________________________::
:: @echo ::                                                                   ::
:: @echo ::                         ParseFn finished                          ::
:: @echo ::___________________________________________________________________::
:: @echo.

C++ convert hex string to signed integer

I had the same problem today, here's how I solved it so I could keep lexical_cast<>

typedef unsigned int    uint32;
typedef signed int      int32;

class uint32_from_hex   // For use with boost::lexical_cast
{
    uint32 value;
public:
    operator uint32() const { return value; }
    friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
    {
        in >> std::hex >> outValue.value;
    }
};

class int32_from_hex   // For use with boost::lexical_cast
{
    uint32 value;
public:
    operator int32() const { return static_cast<int32>( value ); }
    friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
    {
        in >> std::hex >> outvalue.value;
    }
};

uint32 material0 = lexical_cast<uint32_from_hex>( "0x4ad" );
uint32 material1 = lexical_cast<uint32_from_hex>( "4ad" );
uint32 material2 = lexical_cast<uint32>( "1197" );

int32 materialX = lexical_cast<int32_from_hex>( "0xfffefffe" );
int32 materialY = lexical_cast<int32_from_hex>( "fffefffe" );
// etc...

(Found this page when I was looking for a less sucky way :-)

Cheers, A.

Parser Error when deploy ASP.NET application

Interesting all the different scenarios..

In my case...I had uploaded my site to GoDaddy and was getting the Parser Error.

I resolved it by commenting out compilers under system.codedom in web.config. And also add a custom profile for publishing that would precompile during publishing.

  <system.codedom>
    <!--GoDaddy does not compile!-->
    <!--<compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>-->
  </system.codedom>

How to unescape HTML character entities in Java?

I tried Apache Commons StringEscapeUtils.unescapeHtml3() in my project, but wasn't satisfied with its performance. Turns out, it does a lot of unnecessary operations. For one, it allocates a StringWriter for every call, even if there's nothing to unescape in the string. I've rewritten that code differently, now it works much faster. Whoever finds this in google is welcome to use it.

Following code unescapes all HTML 3 symbols and numeric escapes (equivalent to Apache unescapeHtml3). You can just add more entries to the map if you need HTML 4.

package com.example;

import java.io.StringWriter;
import java.util.HashMap;

public class StringUtils {

    public static final String unescapeHtml3(final String input) {
        StringWriter writer = null;
        int len = input.length();
        int i = 1;
        int st = 0;
        while (true) {
            // look for '&'
            while (i < len && input.charAt(i-1) != '&')
                i++;
            if (i >= len)
                break;

            // found '&', look for ';'
            int j = i;
            while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';')
                j++;
            if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) {
                i++;
                continue;
            }

            // found escape 
            if (input.charAt(i) == '#') {
                // numeric escape
                int k = i + 1;
                int radix = 10;

                final char firstChar = input.charAt(k);
                if (firstChar == 'x' || firstChar == 'X') {
                    k++;
                    radix = 16;
                }

                try {
                    int entityValue = Integer.parseInt(input.substring(k, j), radix);

                    if (writer == null) 
                        writer = new StringWriter(input.length());
                    writer.append(input.substring(st, i - 1));

                    if (entityValue > 0xFFFF) {
                        final char[] chrs = Character.toChars(entityValue);
                        writer.write(chrs[0]);
                        writer.write(chrs[1]);
                    } else {
                        writer.write(entityValue);
                    }

                } catch (NumberFormatException ex) { 
                    i++;
                    continue;
                }
            }
            else {
                // named escape
                CharSequence value = lookupMap.get(input.substring(i, j));
                if (value == null) {
                    i++;
                    continue;
                }

                if (writer == null) 
                    writer = new StringWriter(input.length());
                writer.append(input.substring(st, i - 1));

                writer.append(value);
            }

            // skip escape
            st = j + 1;
            i = st;
        }

        if (writer != null) {
            writer.append(input.substring(st, len));
            return writer.toString();
        }
        return input;
    }

    private static final String[][] ESCAPES = {
        {"\"",     "quot"}, // " - double-quote
        {"&",      "amp"}, // & - ampersand
        {"<",      "lt"}, // < - less-than
        {">",      "gt"}, // > - greater-than

        // Mapping to escape ISO-8859-1 characters to their named HTML 3.x equivalents.
        {"\u00A0", "nbsp"}, // non-breaking space
        {"\u00A1", "iexcl"}, // inverted exclamation mark
        {"\u00A2", "cent"}, // cent sign
        {"\u00A3", "pound"}, // pound sign
        {"\u00A4", "curren"}, // currency sign
        {"\u00A5", "yen"}, // yen sign = yuan sign
        {"\u00A6", "brvbar"}, // broken bar = broken vertical bar
        {"\u00A7", "sect"}, // section sign
        {"\u00A8", "uml"}, // diaeresis = spacing diaeresis
        {"\u00A9", "copy"}, // © - copyright sign
        {"\u00AA", "ordf"}, // feminine ordinal indicator
        {"\u00AB", "laquo"}, // left-pointing double angle quotation mark = left pointing guillemet
        {"\u00AC", "not"}, // not sign
        {"\u00AD", "shy"}, // soft hyphen = discretionary hyphen
        {"\u00AE", "reg"}, // ® - registered trademark sign
        {"\u00AF", "macr"}, // macron = spacing macron = overline = APL overbar
        {"\u00B0", "deg"}, // degree sign
        {"\u00B1", "plusmn"}, // plus-minus sign = plus-or-minus sign
        {"\u00B2", "sup2"}, // superscript two = superscript digit two = squared
        {"\u00B3", "sup3"}, // superscript three = superscript digit three = cubed
        {"\u00B4", "acute"}, // acute accent = spacing acute
        {"\u00B5", "micro"}, // micro sign
        {"\u00B6", "para"}, // pilcrow sign = paragraph sign
        {"\u00B7", "middot"}, // middle dot = Georgian comma = Greek middle dot
        {"\u00B8", "cedil"}, // cedilla = spacing cedilla
        {"\u00B9", "sup1"}, // superscript one = superscript digit one
        {"\u00BA", "ordm"}, // masculine ordinal indicator
        {"\u00BB", "raquo"}, // right-pointing double angle quotation mark = right pointing guillemet
        {"\u00BC", "frac14"}, // vulgar fraction one quarter = fraction one quarter
        {"\u00BD", "frac12"}, // vulgar fraction one half = fraction one half
        {"\u00BE", "frac34"}, // vulgar fraction three quarters = fraction three quarters
        {"\u00BF", "iquest"}, // inverted question mark = turned question mark
        {"\u00C0", "Agrave"}, // ? - uppercase A, grave accent
        {"\u00C1", "Aacute"}, // ? - uppercase A, acute accent
        {"\u00C2", "Acirc"}, // ? - uppercase A, circumflex accent
        {"\u00C3", "Atilde"}, // ? - uppercase A, tilde
        {"\u00C4", "Auml"}, // ? - uppercase A, umlaut
        {"\u00C5", "Aring"}, // ? - uppercase A, ring
        {"\u00C6", "AElig"}, // ? - uppercase AE
        {"\u00C7", "Ccedil"}, // ? - uppercase C, cedilla
        {"\u00C8", "Egrave"}, // ? - uppercase E, grave accent
        {"\u00C9", "Eacute"}, // ? - uppercase E, acute accent
        {"\u00CA", "Ecirc"}, // ? - uppercase E, circumflex accent
        {"\u00CB", "Euml"}, // ? - uppercase E, umlaut
        {"\u00CC", "Igrave"}, // ? - uppercase I, grave accent
        {"\u00CD", "Iacute"}, // ? - uppercase I, acute accent
        {"\u00CE", "Icirc"}, // ? - uppercase I, circumflex accent
        {"\u00CF", "Iuml"}, // ? - uppercase I, umlaut
        {"\u00D0", "ETH"}, // ? - uppercase Eth, Icelandic
        {"\u00D1", "Ntilde"}, // ? - uppercase N, tilde
        {"\u00D2", "Ograve"}, // ? - uppercase O, grave accent
        {"\u00D3", "Oacute"}, // ? - uppercase O, acute accent
        {"\u00D4", "Ocirc"}, // ? - uppercase O, circumflex accent
        {"\u00D5", "Otilde"}, // ? - uppercase O, tilde
        {"\u00D6", "Ouml"}, // ? - uppercase O, umlaut
        {"\u00D7", "times"}, // multiplication sign
        {"\u00D8", "Oslash"}, // ? - uppercase O, slash
        {"\u00D9", "Ugrave"}, // ? - uppercase U, grave accent
        {"\u00DA", "Uacute"}, // ? - uppercase U, acute accent
        {"\u00DB", "Ucirc"}, // ? - uppercase U, circumflex accent
        {"\u00DC", "Uuml"}, // ? - uppercase U, umlaut
        {"\u00DD", "Yacute"}, // ? - uppercase Y, acute accent
        {"\u00DE", "THORN"}, // ? - uppercase THORN, Icelandic
        {"\u00DF", "szlig"}, // ? - lowercase sharps, German
        {"\u00E0", "agrave"}, // ? - lowercase a, grave accent
        {"\u00E1", "aacute"}, // ? - lowercase a, acute accent
        {"\u00E2", "acirc"}, // ? - lowercase a, circumflex accent
        {"\u00E3", "atilde"}, // ? - lowercase a, tilde
        {"\u00E4", "auml"}, // ? - lowercase a, umlaut
        {"\u00E5", "aring"}, // ? - lowercase a, ring
        {"\u00E6", "aelig"}, // ? - lowercase ae
        {"\u00E7", "ccedil"}, // ? - lowercase c, cedilla
        {"\u00E8", "egrave"}, // ? - lowercase e, grave accent
        {"\u00E9", "eacute"}, // ? - lowercase e, acute accent
        {"\u00EA", "ecirc"}, // ? - lowercase e, circumflex accent
        {"\u00EB", "euml"}, // ? - lowercase e, umlaut
        {"\u00EC", "igrave"}, // ? - lowercase i, grave accent
        {"\u00ED", "iacute"}, // ? - lowercase i, acute accent
        {"\u00EE", "icirc"}, // ? - lowercase i, circumflex accent
        {"\u00EF", "iuml"}, // ? - lowercase i, umlaut
        {"\u00F0", "eth"}, // ? - lowercase eth, Icelandic
        {"\u00F1", "ntilde"}, // ? - lowercase n, tilde
        {"\u00F2", "ograve"}, // ? - lowercase o, grave accent
        {"\u00F3", "oacute"}, // ? - lowercase o, acute accent
        {"\u00F4", "ocirc"}, // ? - lowercase o, circumflex accent
        {"\u00F5", "otilde"}, // ? - lowercase o, tilde
        {"\u00F6", "ouml"}, // ? - lowercase o, umlaut
        {"\u00F7", "divide"}, // division sign
        {"\u00F8", "oslash"}, // ? - lowercase o, slash
        {"\u00F9", "ugrave"}, // ? - lowercase u, grave accent
        {"\u00FA", "uacute"}, // ? - lowercase u, acute accent
        {"\u00FB", "ucirc"}, // ? - lowercase u, circumflex accent
        {"\u00FC", "uuml"}, // ? - lowercase u, umlaut
        {"\u00FD", "yacute"}, // ? - lowercase y, acute accent
        {"\u00FE", "thorn"}, // ? - lowercase thorn, Icelandic
        {"\u00FF", "yuml"}, // ? - lowercase y, umlaut
    };

    private static final int MIN_ESCAPE = 2;
    private static final int MAX_ESCAPE = 6;

    private static final HashMap<String, CharSequence> lookupMap;
    static {
        lookupMap = new HashMap<String, CharSequence>();
        for (final CharSequence[] seq : ESCAPES) 
            lookupMap.put(seq[1].toString(), seq[0]);
    }

}

UTC Date/Time String to Timezone

PHP's DateTime object is pretty flexible.

$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');

How to hide action bar before activity is created, and then show it again?

you can use this :

getSupportActionBar().hide(); if it doesn't work try this one :

getActionBar().hide();

if above doesn't work try like this :

in your directory = res/values/style.xml , open style.xml -> there is attribute parent change to parent="Theme.AppCompat.Light.DarkActionBar"

if all of it doesn't work too. i don't know anymore. but for me it works.

validate natural input number with ngpattern

This is working

<form name="myform" ng-submit="create()">
    <input type="number"
           name="price_field"
           ng-model="price"
           require
           ng-pattern="/^\d{0,9}(\.\d{1,9})?$/">
    <span  ng-show="myform.price_field.$error.pattern">Not valid number!</span>
    <input type="submit" class="btn">
 </form>

Convert varchar to uniqueidentifier in SQL Server

SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('B33D42A3AC5A4D4C81DD72F3D5C49025',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))

How can I move all the files from one folder to another using the command line?

Lookup move /? on Windows and man mv on Unix systems

Pass variable to function in jquery AJAX success callback

I'm doing it this way:

    function f(data,d){
    console.log(d);
    console.log(data);
}
$.ajax({
    url:u,
    success:function(data){ f(data,d);  }
});

Select tableview row programmatically

Use this category to select a table row and execute a given segue after a delay.
Call this within your viewDidAppear method:

[tableViewController delayedSelection:withSegueIdentifier:]


@implementation UITableViewController (TLUtils)

-(void)delayedSelection:(NSIndexPath *)idxPath withSegueIdentifier:(NSString *)segueID {
    if (!idxPath) idxPath = [NSIndexPath indexPathForRow:0 inSection:0];                                                                                                                                                                 
    [self performSelector:@selector(selectIndexPath:) withObject:@{@"NSIndexPath": idxPath, @"UIStoryboardSegue": segueID } afterDelay:0];                                                                                               
}

-(void)selectIndexPath:(NSDictionary *)args {
    NSIndexPath *idxPath = args[@"NSIndexPath"];                                                                                                                                                                                         
    [self.tableView selectRowAtIndexPath:idxPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];                                                                                                                            

    if ([self.tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)])
        [self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:idxPath];                                                                                                                                              

    [self performSegueWithIdentifier:args[@"UIStoryboardSegue"] sender:self];                                                                                                                                                            
}

@end

How to display div after click the button in Javascript?

HTML Code:

<div id="welcomeDiv"  style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />

Javascript:

function showDiv() {
   document.getElementById('welcomeDiv').style.display = "block";
}

See the Demo: http://jsfiddle.net/rathoreahsan/vzmnJ/

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

The X-Frame-Options header is a security feature enforced at the browser level.

If you have control over your user base (IT dept for corp app), you could try something like a greasemonkey script (if you can a) deploy greasemonkey across everyone and b) deploy your script in a shared way)...

Alternatively, you can proxy their result. Create an endpoint on your server, and have that endpoint open a connection to the target endpoint, and simply funnel traffic backwards.

Sum up a column from a specific row down

=Sum(C:C)-Sum(C1:C5)

Sum everything then remove the sum of the values in the cells you don't want, no Volatile Offset's, Indirect's, or Array's needed.

Just for fun if you don't like that method you could also use:

=SUM($C$6:INDEX($C:$C,MATCH(9.99999999999999E+307,$C:$C))

The above formula will Sum only from C6 through the last cell in C:C where a match of a number is found. This is also non-volatile, but I believe more costly and sloppy. Just added it in case you'd prefer this anyways.

If you would like to do function like CountA for text using the last text value in a column you could use.

=COUNTIF(C6:INDEX($C:$C,MATCH(REPT("Z",255),$C:$C)),"T")

you could also use other combinations like:

=Sum($C$6:$C$65536) 

or

=CountIF($C$6:$C$65536,"T") 

The above would do what you ask in Excel 2003 and lower

=Sum($C$6:$C$1048576) 

or

=CountIF($C$6:$C$1048576,"T")

Would both work for Excel 2007+

All above functions would simply ignore all the blank values under the last value.

Show Hide div if, if statement is true

from php you can invoke jquery like this but my 2nd method is much cleaner and better for php

if($switchView) :?>
 <script>$('.container').hide();</script>
 <script>$('.confirm').show();</script>
<?php endif;

another way is to initiate your class and dynamically invoke the condition like this

$registerForm ='block'; 

then in your html use this

<div class="col" style="display: <?= $registerForm?>">

now you can play with the view with if and else easily without having a messed code example

if($condition)  registerForm = 'none'; 

Make sure you use 'block' to show and 'none' to hide. This is far the easiest way with php

Prevent redirect after form is submitted

You can use as below

e.preventDefault() 

If this method is called, the default action of the event will not be triggered.

Also if I may suggest read this: .prop() vs .attr()

I hope it will help you,

code example:

$('a').click(function(event){
    event.preventDefault();
    //do what you want
  } 

What is the meaning of {...this.props} in Reactjs

You will use props in your child component

for example

if your now component props is

{
   booking: 4,
   isDisable: false
}

you can use this props in your child compoenet

 <div {...this.props}> ... </div>

in you child component, you will receive all your parent props.

What is lazy loading in Hibernate?

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used

Wikipedia

Link of Lazy Loading from hibernate.org

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you wrap each template in a script tag, eg:

<script id="about.html" type="text/ng-template">
<div>
    <h3>About</h3>
    This is the About page
    Its cool!
</div>
</script>

Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials - it adds a right click menu to create an HTML Bundle.

Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works: Vojta Jina's Gist

Its the $http.get that should be changed to use your bundle file:

allTplPromise = $http.get('templates/templateBundle.min.html').then(

Your routes templateUrl should look like this:

        $routeProvider.when(
            "/about", {
                controller: "",
                templateUrl: "about.html"
            }
        );

NULL vs nullptr (Why was it replaced?)

Here is Bjarne Stroustrup's wordings,

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

What are the differences between Mustache.js and Handlebars.js?

One more subtle difference is the treatment of falsy values in {{#property}}...{{/property}} blocks. Most mustache implementations will just obey JS falsiness here, not rendering the block if property is '' or '0'.

Handlebars will render the block for '' and 0, but not other falsy values. This can cause some trouble when migrating templates.

Generating a drop down list of timezones with PHP

Here's one that creates a multidimensional array sorted by offset and niceified name:

function timezones() {
    $timezones = [];

    foreach (timezone_identifiers_list() as $timezone) {
        $datetime = new \DateTime('now', new DateTimeZone($timezone));
        $timezones[] = [
            'sort' => str_replace(':', '', $datetime->format('P')),
            'offset' => $datetime->format('P'),
            'name' => str_replace('_', ' ', implode(', ', explode('/', $timezone))),
            'timezone' => $timezone,
        ];
    }

    usort($timezones, function($a, $b) {
        return $a['sort'] - $b['sort'] ?: strcmp($a['name'], $b['name']);
    });

    return $timezones;
}

foreach (timezones() as $timezone) {
    echo '(UTC '.$timezone['offset'].') '.$timezone['name'].'<br>';
}

Echos:

(UTC -11:00) Pacific, Midway
(UTC -11:00) Pacific, Niue
(UTC -11:00) Pacific, Pago Pago
(UTC -10:00) Pacific, Honolulu
(UTC -10:00) Pacific, Johnston
(UTC -10:00) Pacific, Rarotonga
(UTC -10:00) Pacific, Tahiti
(UTC -09:30) Pacific, Marquesas
(UTC -09:00) America, Adak
(UTC -09:00) Pacific, Gambier
(UTC -08:00) America, Anchorage
(UTC -08:00) America, Juneau
...

How can I find the dimensions of a matrix in Python?

If you are using NumPy arrays, shape can be used. For example

  >>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
  >>> a
  array([[[ 1,  2,  3],
         [ 1,  2,  3]],

         [[12,  3,  4],
         [ 2,  1,  3]]])
 >>> a.shape
 (2, 2, 3)

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

process.env.NODE_ENV is adding a white space do this

process.env.NODE_ENV.trim() == 'production'

Open URL in Java to get the content

Following code should work,

URL url = new URL("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de");
InputStream is = url.openConnection().getInputStream();

BufferedReader reader = new BufferedReader( new InputStreamReader( is )  );

String line = null;
while( ( line = reader.readLine() ) != null )  {
   System.out.println(line);
}
reader.close();

Get the current date and time

DateTimePicker1.value = Format(Date.Now)

c# - How to get sum of the values from List?

You can use the Sum function, but you'll have to convert the strings to integers, like so:

int total = monValues.Sum(x => Convert.ToInt32(x));

Angular 2: How to access an HTTP response body?

This is work for me 100% :

let data:Observable<any> = this.http.post(url, postData);
  data.subscribe((data) => {

  let d = data.json();
  console.log(d);
  console.log("result = " + d.result);
  console.log("url = " + d.image_url);      
  loader.dismiss();
});

psycopg2: insert multiple rows with one query

The cursor.copyfrom solution as provided by @jopseph.sheedy (https://stackoverflow.com/users/958118/joseph-sheedy) above (https://stackoverflow.com/a/30721460/11100064) is indeed lightning fast.

However, the example he gives are not generically usable for a record with any number of fields and it took me while to figure out how to use it correctly.

The IteratorFile needs to be instantiated with tab-separated fields like this (r is a list of dicts where each dict is a record):

    f = IteratorFile("{0}\t{1}\t{2}\t{3}\t{4}".format(r["id"],
        r["type"],
        r["item"],
        r["month"],
        r["revenue"]) for r in records)

To generalise for an arbitrary number of fields we will first create a line string with the correct amount of tabs and field placeholders : "{}\t{}\t{}....\t{}" and then use .format() to fill in the field values : *list(r.values())) for r in records:

        line = "\t".join(["{}"] * len(records[0]))

        f = IteratorFile(line.format(*list(r.values())) for r in records)

complete function in gist here.

Linux find and grep command together

You are looking for -H option in gnu grep.

find . -name '*bills*' -exec grep -H "put" {} \;

Here is the explanation

    -H, --with-filename
      Print the filename for each match.

Excel concatenation quotes

You can also use this syntax: (in column D to concatenate A, B, and C)

=A2 & " """ & B2 & """ " & C2

Excel formula to concatenate with quotes

Undefined reference to sqrt (or other mathematical functions)

I suppose you have imported math.h with #include <math.h>

So the only other reason I can see is a missing linking information. You must link your code with the -lm option.

If you're simply trying to compile one file with gcc, just add -lm to your command line, otherwise, give some informations about your building process.

How do I use this JavaScript variable in HTML?

You can create a <p> element:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <script>_x000D_
  var name = prompt("What's your name?");_x000D_
  var lengthOfName = name.length_x000D_
  p = document.createElement("p");_x000D_
  p.innerHTML = "Your name is "+lengthOfName+" characters long.";_x000D_
  document.body.appendChild(p);_x000D_
  </script>_x000D_
  <body>_x000D_
  </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

With Spring can I make an optional path variable?

Spring 5 / Spring Boot 2 examples:

blocking

@GetMapping({"/dto-blocking/{type}", "/dto-blocking"})
public ResponseEntity<Dto> getDtoBlocking(
        @PathVariable(name = "type", required = false) String type) {
    if (StringUtils.isEmpty(type)) {
        type = "default";
    }
    return ResponseEntity.ok().body(dtoBlockingRepo.findByType(type));
}

reactive

@GetMapping({"/dto-reactive/{type}", "/dto-reactive"})
public Mono<ResponseEntity<Dto>> getDtoReactive(
        @PathVariable(name = "type", required = false) String type) {
    if (StringUtils.isEmpty(type)) {
        type = "default";
    }
    return dtoReactiveRepo.findByType(type).map(dto -> ResponseEntity.ok().body(dto));
}

How do I search within an array of hashes by hash values in ruby?

this will return first match

@fathers.detect {|f| f["age"] > 35 }

Console.log(); How to & Debugging javascript

I like to add these functions in the head.

window.log=function(){if(this.console){console.log(Array.prototype.slice.call(arguments));}};
jQuery.fn.log=function (msg){console.log("%s: %o", msg,this);return this;};

Now log won't break IE I can enable it or disable it in one place I can log inline

$(".classname").log(); //show an array of all elements with classname class

Laravel Blade html image

In Laravel 5.x, you can also do like this .

<img class="img-responsive" src="{{URL::to('/')}}/img/stuvi-logo.png" alt=""/>

Android: Force EditText to remove focus?

You can make cursor and focus disappear by

edittext.clearFocus();

But detect when the key board hide is a hard work.

"could not find stored procedure"

I had the same problem. Eventually I found why. I used a code from web to test output of my procedure. At the end it had a call to Drop(procedure) so I deleted it myself.

Javascript code for showing yesterday's date and todays date

Yesterday's date can be calculated as,

var prev_date = new Date();
prev_date.setDate(prev_date.getDate() - 1);

How to convert a string to character array in c (or) how to extract a single char form string?

In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

Therefore, to extract a character c at index i from string your_string, just use

char c = your_string[i];

Index is base 0 (first character is your_string[0], second is your_string[1]...).

Save the plots into a PDF

Never mind got the way to do it.

def plotGraph(X,Y):
     fignum = random.randint(0,sys.maxint)
     fig = plt.figure(fignum)
     ### Plotting arrangements ###
     return fig

------ plotting module ------

----- mainModule ----

 import matplotlib.pyplot as plt
 ### tempDLStats, tempDLlabels are the argument
 plot1 = plotGraph(tempDLstats, tempDLlabels)
 plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
 plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
 plt.show()
 plot1.savefig('plot1.png')
 plot2.savefig('plot2.png')
 plot3.savefig('plot3.png')

----- mainModule -----

Cookies on localhost with explicit domain

I had much better luck testing locally using 127.0.0.1 as the domain. I'm not sure why, but I had mixed results with localhost and .localhost, etc.

grep --ignore-case --only

I'd suggest that the -i means it does match "ABC", but the difference is in the output. -i doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.

The output of echo "ABC" | grep -i abc is ABC, the -o shows output matching "abc" so nothing shows:

Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC

How to create a cron job using Bash automatically without the interactive editor?

For a nice quick and dirty creation/replacement of a crontab from with a BASH script, I used this notation:

crontab <<EOF
00 09 * * 1-5 echo hello
EOF

angularjs getting previous route path

Use the $locationChangeStart or $locationChangeSuccess events, 3rd parameter:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('start', evt, absNewUrl, absOldUrl);
});
$scope.$on('$locationChangeSuccess',function(evt, absNewUrl, absOldUrl) {
   console.log('success', evt, absNewUrl, absOldUrl);
});

How to set the margin or padding as percentage of height of parent container?

This can be achieved with the writing-mode property. If you set an element's writing-mode to a vertical writing mode, such as vertical-lr, its descendants' percentage values for padding and margin, in both dimensions, become relative to height instead of width.

From the spec:

. . . percentages on the margin and padding properties, which are always calculated with respect to the containing block width in CSS2.1, are calculated with respect to the inline size of the containing block in CSS3.

The definition of inline size:

A measurement in the inline dimension: refers to the physical width (horizontal dimension) in horizontal writing modes, and to the physical height (vertical dimension) in vertical writing modes.

Example, with a resizable element, where horizontal margins are relative to width and vertical margins are relative to height.

_x000D_
_x000D_
.resize {_x000D_
  width: 400px;_x000D_
  height: 200px;_x000D_
  resize: both;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.outer {_x000D_
  height: 100%;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.middle {_x000D_
  writing-mode: vertical-lr;_x000D_
  margin: 0 10%;_x000D_
  width: 80%;_x000D_
  height: 100%;_x000D_
  background-color: yellow;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  writing-mode: horizontal-tb;_x000D_
  margin: 10% 0;_x000D_
  width: 100%;_x000D_
  height: 80%;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="resize">_x000D_
  <div class="outer">_x000D_
    <div class="middle">_x000D_
      <div class="inner"></div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using a vertical writing mode can be particularly useful in circumstances where you want the aspect ratio of an element to remain constant, but want its size to scale in correlation to its height instead of width.

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

An alternative to the already provided ways is to simply filter on the column like so

df = df.where(F.col('columnNameHere').isNull())

This has the added benefit that you don't have to add another column to do the filtering and it's quick on larger data sets.

How long will my session last?

In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start was called!). But PHP’s session handling is a little bit more complicated.

Because the session data is removed by a garbage collector that is only called by session_start with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.

Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.

Calculating distance between two geographic locations

distanceTo will give you the distance in meters between the two given location ej target.distanceTo(destination).

distanceBetween give you the distance also but it will store the distance in a array of float( results[0]). the doc says If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]

hope that this helps

i've used distanceTo to get the distance from point A to B i think that is the way to go.

How can I search Git branches for a file or directory?

git log + git branch will find it for you:

% git log --all -- somefile

commit 55d2069a092e07c56a6b4d321509ba7620664c63
Author: Dustin Sallings <[email protected]>
Date:   Tue Dec 16 14:16:22 2008 -0800

    added somefile


% git branch -a --contains 55d2069
  otherbranch

Supports globbing, too:

% git log --all -- '**/my_file.png'

The single quotes are necessary (at least if using the Bash shell) so the shell passes the glob pattern to git unchanged, instead of expanding it (just like with Unix find).

How to send data to COM PORT using JAVA?

This question has been asked and answered many times:

Read file from serial port using Java

Reading serial port in Java

Reading file from serial port in Java

Is there Java library or framework for accessing Serial ports?

Java Serial Communication on Windows

to reference a few.

Personally I recommend SerialPort from http://serialio.com - it's not free, but it's well worth the developer (no royalties) licensing fee for any commercial project. Sadly, it is no longer royalty free to deploy, and SerialIO.com seems to have remade themselves as a hardware seller; I had to search for information on SerialPort.

From personal experience, I strongly recommend against the Sun, IBM and RxTx implementations, all of which were unstable in 24/7 use. Refer to my answers on some of the aforementioned questions for details. To be perfectly fair, RxTx may have come a long way since I tried it, though the Sun and IBM implementations were essentially abandoned, even back then.

A newer free option that looks promising and may be worth trying is jSSC (Java Simple Serial Connector), as suggested by @Jodes comment.

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

I'm a little late to this party, but I think I have something useful to add.

Kekoa's answer is great but, as RonLugge mentions, it can make the button no longer respect sizeToFit or, more importantly, can cause the button to clip its content when it is intrinsically sized. Yikes!

First, though,

A brief explanation of how I believe imageEdgeInsets and titleEdgeInsets work:

The docs for imageEdgeInsets have the following to say, in part:

Use this property to resize and reposition the effective drawing rectangle for the button image. You can specify a different value for each of the four insets (top, left, bottom, right). A positive value shrinks, or insets, that edge—moving it closer to the center of the button. A negative value expands, or outsets, that edge.

I believe that this documentation was written imagining that the button has no title, just an image. It makes a lot more sense thought of this way, and behaves how UIEdgeInsets usually do. Basically, the frame of the image (or the title, with titleEdgeInsets) is moved inwards for positive insets and outwards for negative insets.

OK, so what?

I'm getting there! Here's what you have by default, setting an image and a title (the button border is green just to show where it is):

Starting image; no space between title and image.

When you want spacing between an image and a title, without causing either to be crushed, you need to set four different insets, two on each of the image and title. That's because you don't want to change the sizes of those elements' frames, but just their positions. When you start thinking this way, the needed change to Kekoa's excellent category becomes clear:

@implementation UIButton(ImageTitleCentering)

- (void)centerButtonAndImageWithSpacing:(CGFloat)spacing {
    CGFloat insetAmount = spacing / 2.0;
    self.imageEdgeInsets = UIEdgeInsetsMake(0, -insetAmount, 0, insetAmount);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, -insetAmount);
}

@end

But wait, you say, when I do that, I get this:

Spacing is good, but the image and title are outside the view's frame.

Oh yeah! I forgot, the docs warned me about this. They say, in part:

This property is used only for positioning the image during layout. The button does not use this property to determine intrinsicContentSize and sizeThatFits:.

But there is a property that can help, and that's contentEdgeInsets. The docs for that say, in part:

The button uses this property to determine intrinsicContentSize and sizeThatFits:.

That sounds good. So let's tweak the category once more:

@implementation UIButton(ImageTitleCentering)

- (void)centerButtonAndImageWithSpacing:(CGFloat)spacing {
    CGFloat insetAmount = spacing / 2.0;
    self.imageEdgeInsets = UIEdgeInsetsMake(0, -insetAmount, 0, insetAmount);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, -insetAmount);
    self.contentEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, insetAmount);
}

@end

And what do you get?

Spacing and frame are now correct.

Looks like a winner to me.


Working in Swift and don't want to do any thinking at all? Here's the final version of the extension in Swift:

extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount, bottom: 0, right: insetAmount)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: -insetAmount)
        contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}

iPhone keyboard, Done button and resignFirstResponder

From the documentation (any version):

It is your application’s responsibility to dismiss the keyboard at the time of your choosing. You might dismiss the keyboard in response to a specific user action, such as the user tapping a particular button in your user interface. You might also configure your text field delegate to dismiss the keyboard when the user presses the “return” key on the keyboard itself. To dismiss the keyboard, send the resignFirstResponder message to the text field that is currently the first responder. Doing so causes the text field object to end the current editing session (with the delegate object’s consent) and hide the keyboard.

So, you have to send resignFirstResponder somehow. But there is a possibility that textfield loses focus another way during processing of textFieldShouldReturn: message. This also will cause keyboard to disappear.

Can you remove elements from a std::list while iterating through it?

If you think of the std::list like a queue, then you can dequeue and enqueue all the items that you want to keep, but only dequeue (and not enqueue) the item you want to remove. Here's an example where I want to remove 5 from a list containing the numbers 1-10...

std::list<int> myList;

int size = myList.size(); // The size needs to be saved to iterate through the whole thing

for (int i = 0; i < size; ++i)
{
    int val = myList.back()
    myList.pop_back() // dequeue
    if (val != 5)
    {
         myList.push_front(val) // enqueue if not 5
    }
}

myList will now only have numbers 1-4 and 6-10.

AngularJS: Service vs provider vs factory

Factory: The factory you actually create an object inside of the factory and return it.
service: The service you just have a standard function that uses the this keyword to define function.
provider: The provider there’s a $get you define and it can be used to get the object that returns the data.

What causes a TCP/IP reset (RST) flag to be sent?

A 'router' could be doing anything - particularly NAT, which might involve any amount of bug-ridden messing with traffic...

One reason a device will send a RST is in response to receiving a packet for a closed socket.

It's hard to give a firm but general answer, because every possible perversion has been visited on TCP since its inception, and all sorts of people might be inserting RSTs in an attempt to block traffic. (Some 'national firewalls' work like this, for example.)