Programs & Examples On #Fluentvalidation 2.0

jQuery: Change button text on click

This should work for you:

    $('.SeeMore2').click(function(){
        var $this = $(this);
        $this.toggleClass('SeeMore2');
        if($this.hasClass('SeeMore2')){
            $this.text('See More');         
        } else {
            $this.text('See Less');
        }
});

How to mock void methods with Mockito

In your example you should mock Listener item and use Mockito.verify to check interactions with it

How to modify existing, unpushed commit messages?

As already mentioned, git commit --amend is the way to overwrite the last commit. One note: if you would like to also overwrite the files, the command would be

git commit -a --amend -m "My new commit message"

How to sort pandas data frame using values from several columns?

DataFrame.sort is deprecated; use DataFrame.sort_values.

>>> df.sort_values(['c1','c2'], ascending=[False,True])
   c1   c2
0   3   10
3   2   15
1   2   30
4   2  100
2   1   20
>>> df.sort(['c1','c2'], ascending=[False,True])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ampawake/anaconda/envs/pseudo/lib/python2.7/site-packages/pandas/core/generic.py", line 3614, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'sort'

How to Convert date into MM/DD/YY format in C#

Look into using the ToString() method with a specified format.

How to output a multiline string in Bash?

If you use the solution from @jorge and find that everything is on the same line, make sure you enclose the variable in quotes:

echo $__usage

will print everything on one line whereas

echo "$__usage"

will retain the newlines.

Bootstrap 4 - Inline List?

.list-inline class in bootstrap is a Inline Unordered List.

If you want to create a horizontal menu using ordered or unordered list you need to place all list items in a single line i.e. side by side. You can do this by simply applying the class

<div class="list-inline">
    <a href="#" class="list-inline-item">First item</a>
    <a href="#" class="list-inline-item">Secound item</a>
    <a href="#" class="list-inline-item">Third item</a>
  </div>

git still shows files as modified after adding to .gitignore

  1. Git add .

  2. Git status //Check file that being modified

    // git reset HEAD --- replace to which file you want to ignore

  3. git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!

  4. git commit -m ''

  5. git push

NULL value for int in Update statement

Assuming the column is set to support NULL as a value:

UPDATE YOUR_TABLE
   SET column = NULL

Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:

UPDATE YOUR_TABLE
   SET column = CAST(NULL AS DATETIME)

...assuming column is a DATETIME data type in the example above.

How do I dump an object's fields to the console?

You might find a use for the methods method which returns an array of methods for an object. It's not the same as print_r, but still useful at times.

>> "Hello".methods.sort
=> ["%", "*", "+", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", "[]=", "__id__", "__send__", "all?", "any?", "between?", "capitalize", "capitalize!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clone", "collect", "concat", "count", "crypt", "delete", "delete!", "detect", "display", "downcase", "downcase!", "dump", "dup", "each", "each_byte", "each_line", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "find", "find_all", "freeze", "frozen?", "grep", "gsub", "gsub!", "hash", "hex", "id", "include?", "index", "inject", "insert", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "intern", "is_a?", "is_binary_data?", "is_complex_yaml?", "kind_of?", "length", "ljust", "lstrip", "lstrip!", "map", "match", "max", "member?", "method", "methods", "min", "next", "next!", "nil?", "object_id", "oct", "partition", "private_methods", "protected_methods", "public_methods", "reject", "replace", "respond_to?", "reverse", "reverse!", "rindex", "rjust", "rstrip", "rstrip!", "scan", "select", "send", "singleton_methods", "size", "slice", "slice!", "sort", "sort_by", "split", "squeeze", "squeeze!", "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "swapcase!", "taguri", "taguri=", "taint", "tainted?", "to_a", "to_f", "to_i", "to_s", "to_str", "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", "tr!", "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto", "zip"]

Is there any way to install Composer globally on Windows?

you can install it using this command line

 echo @php "%~dp0composer.phar" %* > composer.bat

Regular expression for address field validation

Regex is a very bad choice for this kind of task. Try to find a web service or an address database or a product which can clean address data instead.

Related:

Git: How to rebase to a specific commit?

You can even take a direct approach:

git checkout topic
git rebase <commitB>

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Context provides information about the Actvity or Application to newly created components.

Relevant Context should be provided to newly created components (whether application context or activity context)

Since Activity is a subclass of Context, one can use this to get that activity's context

Transfer files to/from session I'm logged in with PuTTY

This is probably not a direct answer to what you're asking, but when I need to transfer files over a SSH session I use WinSCP, which is an excellent file transfer program over SCP or SFTP. Of course this assumes you're on Windows.

What is the minimum length of a valid international phone number?

EDIT 2015-06-27: Minimum is actually 8, including country code. My bad.

Original post

The minimum phone number that I use is 10 digits. International users should always be putting their country code, and as far as I know there are no countries with fewer than ten digits if you count country code.

More info here: https://en.wikipedia.org/wiki/Telephone_numbering_plan

Regular Expression for any number greater than 0?

You can use the below expression:

(^\d*\.?\d*[1-9]+\d*$)|(^[1-9]+\.?\d*$)                  

Valid entries: 1 1. 1.1 1.0 all positive real numbers

Invalid entries: all negative real numbers and 0 and 0.0

I need to learn Web Services in Java. What are the different types in it?

  1. SOAP Web Services are standard-based and supported by almost every software platform: They rely heavily in XML and have support for transactions, security, asynchronous messages and many other issues. It’s a pretty big and complicated standard, but covers almost every messaging situation. On the other side, RESTful services relies of HTTP protocol and verbs (GET, POST, PUT, DELETE) to interchange messages in any format, preferable JSON and XML. It’s a pretty simple and elegant architectural approach.
  2. As in every topic in the Java World, there are several libraries to build/consume Web Services. In the SOAP Side you have the JAX-WS standard and Apache Axis, and in REST you can use Restlets or Spring REST Facilities among other libraries.

With question 3, this article states that RESTful Services are appropiate in this scenarios:

  • If you have limited bandwidth
  • If your operations are stateless: No information is preserved from one invocation to the next one, and each request is treated independently.
  • If your clients require caching.

While SOAP is the way to go when:

  • If you require asynchronous processing
  • If you need formal contract/Interfaces
  • In your service operations are stateful: For example, you store information/data on a request and use that stored data on the next one.

Select all elements with a "data-xxx" attribute without using jQuery

While not as pretty as querySelectorAll (which has a litany of issues), here's a very flexible function that recurses the DOM and should work in most browsers (old and new). As long as the browser supports your condition (ie: data attributes), you should be able to retrieve the element.

To the curious: Don't bother testing this vs. QSA on jsPerf. Browsers like Opera 11 will cache the query and skew the results.

Code:

function recurseDOM(start, whitelist)
{
    /*
    *    @start:        Node    -    Specifies point of entry for recursion
    *    @whitelist:    Object  -    Specifies permitted nodeTypes to collect
    */

    var i = 0, 
    startIsNode = !!start && !!start.nodeType, 
    startHasChildNodes = !!start.childNodes && !!start.childNodes.length,
    nodes, node, nodeHasChildNodes;
    if(startIsNode && startHasChildNodes)
    {       
        nodes = start.childNodes;
        for(i;i<nodes.length;i++)
        {
            node = nodes[i];
            nodeHasChildNodes = !!node.childNodes && !!node.childNodes.length;
            if(!whitelist || whitelist[node.nodeType])
            {
                //condition here
                if(!!node.dataset && !!node.dataset.foo)
                {
                    //handle results here
                }
                if(nodeHasChildNodes)
                {
                    recurseDOM(node, whitelist);
                }
            }
            node = null;
            nodeHasChildNodes = null;
        }
    }
}

You can then initiate it with the following:

recurseDOM(document.body, {"1": 1}); for speed, or just recurseDOM(document.body);

Example with your specification: http://jsbin.com/unajot/1/edit

Example with differing specification: http://jsbin.com/unajot/2/edit

jQuery "blinking highlight" effect on div?

I use different predefined colors like so:

theme = {
    whateverFlashColor: '#ffffaa',
    whateverElseFlashColor: '#bbffaa',
    whateverElseThenFlashColor: '#ffffff',
};

and use them like this

$('#element').effect("highlight", {color:theme.whateverFlashColor}, 1000);

easy :)

How to get size of mysql database?

Go into the mysql data directory and run du -h --max-depth=1 | grep databasename

Undefined or null for AngularJS

I asked the same question of the lodash maintainers a while back and they replied by mentioning the != operator can be used here:

if(newVal != null) {
  // newVal is defined
}

This uses JavaScript's type coercion to check the value for undefined or null.

If you are using JSHint to lint your code, add the following comment blocks to tell it that you know what you are doing - most of the time != is considered bad.

/* jshint -W116 */ 
if(newVal != null) {
/* jshint +W116 */
  // newVal is defined
}

java.text.ParseException: Unparseable date

Check your Pattern (DD-MMM-YYYY) and the input for the parse("29-11-2018") method. Input to the parse method should follow : DD-MMM-YYYY i,e. 21-AUG-2019

In My Code:

String pattern = "DD-MMM-YYYY";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

    try {
        startDate = simpleDateFormat.parse("29-11-2018");// here no pattern match 
        endDate = simpleDateFormat.parse("28-AUG-2019");// Ok 
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Collection was modified; enumeration operation may not execute in ArrayList

One way is to add the item(s) to be deleted to a new list. Then go through and delete those items.

Serialize an object to string

I was unable to use the JSONConvert method suggested by xhafan

In .Net 4.5 even after adding the "System.Web.Extensions" assembly reference I was still unable to access the JSONConvert.

However, once you add the reference you can get the same string print out using:

JavaScriptSerializer js = new JavaScriptSerializer();
string jsonstring = js.Serialize(yourClassObject);

Android: How can I get the current foreground activity (from a service)?

Use ActivityManager

If you only want to know the application containing the current activity, you can do so using ActivityManager. The technique you can use depends on the version of Android:

Benefits

  • Should work in all Android versions to-date.

Disadvantages

  • Doesn't work in Android 5.1+ (it only returns your own app)
  • The documentation for these APIs says they're only intended for debugging and management user interfaces.
  • If you want real-time updates, you need to use polling.
  • Relies on a hidden API: ActivityManager.RunningAppProcessInfo.processState
  • This implementation doesn't pick up the app switcher activity.

Example (based on KNaito's code)

public class CurrentApplicationPackageRetriever {

    private final Context context;

    public CurrentApplicationPackageRetriever(Context context) {
        this.context = context;
    }

    public String get() {
        if (Build.VERSION.SDK_INT < 21)
            return getPreLollipop();
        else
            return getLollipop();
    }

    private String getPreLollipop() {
        @SuppressWarnings("deprecation")
        List<ActivityManager.RunningTaskInfo> tasks =
            activityManager().getRunningTasks(1);
        ActivityManager.RunningTaskInfo currentTask = tasks.get(0);
        ComponentName currentActivity = currentTask.topActivity;
        return currentActivity.getPackageName();
    }

    private String getLollipop() {
        final int PROCESS_STATE_TOP = 2;

        try {
            Field processStateField = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");

            List<ActivityManager.RunningAppProcessInfo> processes =
                activityManager().getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo process : processes) {
                if (
                    // Filters out most non-activity processes
                    process.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    &&
                    // Filters out processes that are just being
                    // _used_ by the process with the activity
                    process.importanceReasonCode == 0
                ) {
                    int state = processStateField.getInt(process);

                    if (state == PROCESS_STATE_TOP) {
                        String[] processNameParts = process.processName.split(":");
                        String packageName = processNameParts[0];

                        /*
                         If multiple candidate processes can get here,
                         it's most likely that apps are being switched.
                         The first one provided by the OS seems to be
                         the one being switched to, so we stop here.
                         */
                        return packageName;
                    }
                }
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        return null;
    }

    private ActivityManager activityManager() {
        return (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    }

}

Manifest

Add the GET_TASKS permission to AndroidManifest.xml:

<!--suppress DeprecatedClassUsageInspection -->
<uses-permission android:name="android.permission.GET_TASKS" />

Get current AUTO_INCREMENT value for any table

you can also use this if you know the name of the primary key

SELECT
    MAX(primary_key_name) + 1
FROM
    TABLE_NAME

How to force composer to reinstall a library?

As user @aaracrr pointed out in a comment on another answer probably the best answer is to re-require the package with the same version constraint.

ie.

composer require vendor/package

or specifying a version constraint

composer require vendor/package:^1.0.0

jQuery ui dialog change title after load-callback

Using dialog methods:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

Or directly, hacky though:

$("span.ui-dialog-title").text('My New Title'); 

For future reference, you can skip google with jQuery. The jQuery API will answer your questions most of the time. In this case, the Dialog API page. For the main library: http://api.jquery.com

How to round up the result of integer division?

The integer math solution that Ian provided is nice, but suffers from an integer overflow bug. Assuming the variables are all int, the solution could be rewritten to use long math and avoid the bug:

int pageCount = (-1L + records + recordsPerPage) / recordsPerPage;

If records is a long, the bug remains. The modulus solution does not have the bug.

ReactJS and images in public folder

You Could also use this.. it works assuming 'yourimage.jpg' is in your public folder.

<img src={'./yourimage.jpg'}/>

Convert Decimal to Varchar

If you are using SQL Server 2012, 2014 or newer, use the Format Function instead:

select Format( decimalColumnName ,'FormatString','en-US' )

Review the Microsoft topic and .NET format syntax for how to define the format string.

An example for this question would be:

select Format( MyDecimalColumn ,'N','en-US' )

How to allow Cross domain request in apache2

Ubuntu Apache2 solution that worked for me .htaccess edit did not work for me I had to modify the conf file.

nano /etc/apache2/sites-available/mydomain.xyz.conf

my config that worked to allow CORS Support

<IfModule mod_ssl.c>
    <VirtualHost *:443>

        ServerName mydomain.xyz
        ServerAlias www.mydomain.xyz

        ServerAdmin [email protected]
        DocumentRoot /var/www/mydomain.xyz/public

        ### following three lines are for CORS support
        Header add Access-Control-Allow-Origin "*"
        Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
        Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        SSLCertificateFile /etc/letsencrypt/live/mydomain.xyz/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.xyz/privkey.pem

    </VirtualHost>
</IfModule>

then type the following command

a2enmod headers

make sure cache is clear before trying

Why is 22 the default port number for SFTP?

From Wikipedia:

Applications implementing common services often use specifically reserved, well-known port numbers for receiving service requests from client hosts. This process is known as listening and involves the receipt of a request on the well-known port and reestablishing one-to-one server-client communications on another private port, so that other clients may also contact the well-known service port. The well-known ports are defined by convention overseen by the Internet Assigned Numbers Authority (IANA).

Source

So as others mentioned, it's a convention.

Cloning a private Github repo

If the newly used computer has different credentials running this command

git clone https://github.com/username/reponame.git

directly will not work. Git will attempt to use the stored credentials and will not prompt you for the username and the password. Since the credentials mismatch, git will output Repository not found and the clone operation fails. The way I solved it was by deleting the old credentials, since I don't use them anymore, and ran the the above mentioned command again and entered the required username and password and cloned the private repo.

Find the most frequent number in a NumPy array

While most of the answers above are useful, in case you: 1) need it to support non-positive-integer values (e.g. floats or negative integers ;-)), and 2) aren't on Python 2.7 (which collections.Counter requires), and 3) prefer not to add the dependency of scipy (or even numpy) to your code, then a purely python 2.6 solution that is O(nlogn) (i.e., efficient) is just this:

from collections import defaultdict

a = [1,2,3,1,2,1,1,1,3,2,2,1]

d = defaultdict(int)
for i in a:
  d[i] += 1
most_frequent = sorted(d.iteritems(), key=lambda x: x[1], reverse=True)[0]

How do you write to a folder on an SD card in Android?

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");

FileOutputStream f = new FileOutputStream(file);
...

HTML img scaling

Adding max-width: 100%; to the img tag works for me.

how to compare two elements in jquery

You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.

Assuming:

<div id="a" class="a"></div>

this:

$('div.a')[0] == $('div#a')[0]

returns true.

c++ parse int from string

There is no "right way". If you want a universal (but suboptimal) solution you can use a boost::lexical cast.

A common solution for C++ is to use std::ostream and << operator. You can use a stringstream and stringstream::str() method for conversion to string.

If you really require a fast mechanism (remember the 20/80 rule) you can look for a "dedicated" solution like C++ String Toolkit Library

Best Regards,
Marcin

Difference between Iterator and Listiterator?

The differences are listed in the Javadoc for ListIterator

You can

  • iterate backwards
  • obtain the iterator at any point.
  • add a new value at any point.
  • set a new value at that point.

What happens to a declared, uninitialized variable in C? Does it have a value?

That depends. If that definition is global (outside any function) then num will be initialized to zero. If it's local (inside a function) then its value is indeterminate. In theory, even attempting to read the value has undefined behavior -- C allows for the possibility of bits that don't contribute to the value, but have to be set in specific ways for you to even get defined results from reading the variable.

Android: keeping a background service alive (preventing process death)

I'm working on an app and face issue of killing my service by on app kill. I researched on google and found that I have to make it foreground. following is the code:

public class UpdateLocationAndPrayerTimes extends Service {

 Context context;
@Override
public void onCreate() {
    super.onCreate();
    context = this;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    StartForground();
    return START_STICKY;
}

@Override
public void onDestroy() {


    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}


private void StartForground() {
    LocationChangeDetector locationChangeDetector = new LocationChangeDetector(context);
    locationChangeDetector.getLatAndLong();
    Notification notification = new NotificationCompat.Builder(this)
            .setOngoing(false)
            .setSmallIcon(android.R.color.transparent)

            //.setSmallIcon(R.drawable.picture)
            .build();
    startForeground(101,  notification);

    }
}

hops that it may helps!!!!

How to add a response header on nginx when using proxy_pass?

add_header works as well with proxy_pass as without. I just today set up a configuration where I've used exactly that directive. I have to admit though that I've struggled as well setting this up without exactly recalling the reason, though.

Right now I have a working configuration and it contains the following (among others):

server {
    server_name  .myserver.com
    location / {
        proxy_pass  http://mybackend;
        add_header  X-Upstream  $upstream_addr;
    }
}

Before nginx 1.7.5 add_header worked only on successful responses, in contrast to the HttpHeadersMoreModule mentioned by Sebastian Goodman in his answer.

Since nginx 1.7.5 you can use the keyword always to include custom headers even in error responses. For example:

add_header X-Upstream $upstream_addr always;

Limitation: You cannot override the server header value using add_header.

How do I truncate a .NET string?

For the sake of (over)complexity I'll add my overloaded version which replaces the last 3 characters with an ellipsis in respect with the maxLength parameter.

public static string Truncate(this string value, int maxLength, bool replaceTruncatedCharWithEllipsis = false)
{
    if (replaceTruncatedCharWithEllipsis && maxLength <= 3)
        throw new ArgumentOutOfRangeException("maxLength",
            "maxLength should be greater than three when replacing with an ellipsis.");

    if (String.IsNullOrWhiteSpace(value)) 
        return String.Empty;

    if (replaceTruncatedCharWithEllipsis &&
        value.Length > maxLength)
    {
        return value.Substring(0, maxLength - 3) + "...";
    }

    return value.Substring(0, Math.Min(value.Length, maxLength)); 
}

Converting a generic list to a CSV string

The problem with String.Join is that you are not handling the case of a comma already existing in the value. When a comma exists then you surround the value in Quotes and replace all existing Quotes with double Quotes.

String.Join(",",{"this value has a , in it","This one doesn't", "This one , does"});

See CSV Module

How to clear a textbox once a button is clicked in WPF?

When you run your form and you want showing text in textbox is clear so you put the code : -

textBox1.text = String.Empty;

Where textBox1 is your textbox name.

How do I install PyCrypto on Windows?

I had Pycharm for python.

  1. Go to pycharm -> file -> setting -> project interpreter

  2. Click on +

  3. Search for "pycrypto" and install the package

Note: If you don't have "Microsoft Visual C++ Compiler for Python 2.7" installed then it will prompt for installation, once installation finished try the above steps it should work fine.

Firefox setting to enable cross domain Ajax request

For modern browsers, you may try the following approach:

https://developer.mozilla.org/en/HTTP_access_control

In short, you need to add the following into the SERVER response header (the following allows access from foo.example):

Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER
Access-Control-Max-Age: 1728000

Note that the X-PINGOTHER is the custom header that is inserted by JavaScript, and should differ from site to site.

If you want any site access your server in Ajax, use * instead.


Edit:

When I first answered the question by 2009, I actually hit the same problem, and I worked around it using the server side config.

There was no plugin on FF or Chrome by then.

However, now we do have alternatives using the browser side plugin, please check the answer of tsds

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

How to modify STYLE attribute of element with known ID using JQuery

Not sure I completely understand the question but:

$(":button.brown").click(function() {
  $(":button.brown.selected").removeClass("selected");
  $(this).addClass("selected");
});

seems to be along the lines of what you want.

I would certainly recommend using classes instead of directly setting CSS, which is problematic for several reasons (eg removing styles is non-trivial, removing classes is easy) but if you do want to go that way:

$("...").css("background", "brown");

But when you want to reverse that change, what do you set it to?

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

ng: command not found while creating new project using angular-cli

If you have zsh installed add alias to .zshrc file in home directory as well.

mongodb service is not starting up

This can also happen if your file permissions get changed somehow. Removing the lock file didn't help, and we were getting errors in the log file like:

2016-01-20T09:14:58.210-0800 [initandlisten] warning couldn't write to / rename file /var/lib/mongodb/journal/prealloc.0: couldn't open file    /var/lib/mongodb/journal/prealloc.0 for writing errno:13 Permission denied
2016-01-20T09:14:58.288-0800 [initandlisten] couldn't open /var/lib/mongodb/local.ns errno:13 Permission denied
2016-01-20T09:14:58.288-0800 [initandlisten] error couldn't open file /var/lib/mongodb/local.ns terminating

So, went to check permissions:

ls -l /var/lib/mongodb

total 245780
drwxr-xr-x 2 mongodb mongodb     4096 Jan 20 09:14 journal
drwxr-xr-x 2 root    root        4096 Jan 20 09:11 local
-rw------- 1 root    root    67108864 Jan 20 09:11 local.0
-rw------- 1 root    root    16777216 Jan 20 09:11 local.ns
-rwxr-xr-x 1 mongodb nogroup        0 Jan 20 09:14 mongod.lock

To fix:

# chown -R mongodb:mongodb /var/lib/mongodb

Remove the lock file if it's still there:

# rm /var/lib/mongodb/mongod.lock

Start mongodb

# service mongodb start

Tail the log and you should see at the end of it:

tail -f /var/log/mongodb/mongodb.log
2016-01-20T09:16:02.025-0800 [initandlisten] waiting for connections on port 27017

How to create PDF files in Python

fpdf works well for me. Much simpler than ReportLab and really free. Works with UTF-8.

How do I detect "shift+enter" and generate a new line in Textarea?

This works for me!

$("#your_textarea").on('keydown', function(e){
    if(e.keyCode === 13 && !e.shiftKey) 
    {

          $('form').submit();

    }
});

Is there a way to perform "if" in python's lambda

what you need exactly is

def fun():
    raise Exception()
f = lambda x:print x if x==2 else fun()

now call the function the way you need

f(2)
f(3)

Can't push to GitHub because of large file which I already deleted

You can use

git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch <file/dir>' HEAD

This will delete everything in the history of that file. The problem is that the file is present in the history.

This command changes the hashes of your commits which can be a real problem, especially on shared repositories. It should not be performed without understanding the consequences.

MySQL convert date string to Unix timestamp

Here's an example of how to convert DATETIME to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))

Here's an example of how to change date format:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')

Documentation: UNIX_TIMESTAMP, FROM_UNIXTIME

Get the current script file name

Here is a list what I've found recently searching an answer:

//self name with file extension
echo basename(__FILE__) . '<br>';
//self name without file extension
echo basename(__FILE__, '.php') . '<br>';
//self full url with file extension
echo __FILE__ . '<br>';

//parent file parent folder name
echo basename($_SERVER["REQUEST_URI"]) . '<br>';
//parent file parent folder name with //s
echo $_SERVER["REQUEST_URI"] . '<br>';

// parent file name without file extension
echo basename($_SERVER['PHP_SELF'], ".php") . '<br>';
// parent file name with file extension
echo basename($_SERVER['PHP_SELF']) . '<br>';
// parent file relative url with file etension
echo $_SERVER['PHP_SELF'] . '<br>';

// parent file name without file extension
echo basename($_SERVER["SCRIPT_FILENAME"], '.php') . '<br>';
// parent file name with file extension
echo basename($_SERVER["SCRIPT_FILENAME"]) . '<br>';
// parent file full url with file extension
echo $_SERVER["SCRIPT_FILENAME"] . '<br>';

//self name without file extension
echo pathinfo(__FILE__, PATHINFO_FILENAME) . '<br>';
//self file extension
echo pathinfo(__FILE__, PATHINFO_EXTENSION) . '<br>';

// parent file name with file extension
echo basename($_SERVER['SCRIPT_NAME']);

Don't forget to remove :)

<br>

Java associative-array

Thinking more about it, I would like to throw out tuples as a more general-purpose way of dealing with this problem. While tuples are not native to Java, I use Javatuples to provide me the same functionality which would exist in other languages. An example of how to deal with the question asked is

Map<Pair<Integer, String>, String> arr = new HashMap<Pair<Integer, String>, String>();
Pair p1 = new Pair(0, "name");
arr.put(p1, "demo");

I like this approach because it can be extended to triples and other higher ordered groupings with api provided classes and methods.

Read file data without saving it in Flask

I was trying to do the exact same thing, open a text file (a CSV for Pandas actually). Don't want to make a copy of it, just want to open it. The form-WTF has a nice file browser, but then it opens the file and makes a temporary file, which it presents as a memory stream. With a little work under the hood,

form = UploadForm() 
 if form.validate_on_submit(): 
      filename = secure_filename(form.fileContents.data.filename)  
      filestream =  form.fileContents.data 
      filestream.seek(0)
      ef = pd.read_csv( filestream  )
      sr = pd.DataFrame(ef)  
      return render_template('dataframe.html',tables=[sr.to_html(justify='center, classes='table table-bordered table-hover')],titles = [filename], form=form) 

Differences Between vbLf, vbCrLf & vbCr Constants

 Constant   Value               Description
 ----------------------------------------------------------------
 vbCr       Chr(13)             Carriage return
 vbCrLf     Chr(13) & Chr(10)   Carriage return–linefeed combination
 vbLf       Chr(10)             Line feed
  • vbCr : - return to line beginning
    Represents a carriage-return character for print and display functions.

  • vbCrLf : - similar to pressing Enter
    Represents a carriage-return character combined with a linefeed character for print and display functions.

  • vbLf : - go to next line
    Represents a linefeed character for print and display functions.


Read More from Constants Class

How to iterate over each string in a list of strings and operate on it's elements

c=0
words = ['challa','reddy','challa']

for idx, word in enumerate(words):
    if idx==0:
        firstword=word
        print(firstword)
    elif idx == len(words)-1:
        lastword=word
        print(lastword)
        if firstword==lastword:
            c=c+1
            print(c)

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

Java 8 stream map on entry set

Here is a shorter solution by AbacusUtil

Stream.of(input).toMap(e -> e.getKey().substring(subLength), 
                       e -> AttributeType.GetByName(e.getValue()));

Open Facebook Page in Facebook App (if installed) on Android

"fb://page/ does not work with newer versions of the FB app. You should use fb://facewebmodal/f?href= for newer versions.

This is a full fledged working code currently live in one of my apps:

public static String FACEBOOK_URL = "https://www.facebook.com/YourPageName";
public static String FACEBOOK_PAGE_ID = "YourPageName";

//method to get the right URL to use in the intent
public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
            if (versionCode >= 3002850) { //newer versions of fb app
                return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
            } else { //older versions of fb app
                return "fb://page/" + FACEBOOK_PAGE_ID;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL; //normal web url
        }
    }

This method will return the correct url for app if installed or web url if app is not installed.

Then start an intent as follows:

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
String facebookUrl = getFacebookPageURL(this);
facebookIntent.setData(Uri.parse(facebookUrl));
startActivity(facebookIntent);

That's all you need.

ImportError: cannot import name

This can also happen if you've been working on your scripts and functions and have been moving them around (i.e. changed the location of the definition) which could have accidentally created a looping reference.

You may find that the situation is solved if you just reset the iPython kernal to clear any old assignments:

%reset

or menu->restart terminal

Debugging Stored Procedure in SQL Server 2008

Well the answer was sitting right in front of me the whole time.

In SQL Server Management Studio 2008 there is a Debug button in the toolbar. Set a break point in a query window to step through.

I dismissed this functionality at the beginning because I didn't think of stepping INTO the stored procedure, which you can do with ease.

SSMS basically does what FinnNK mentioned with the MSDN walkthrough but automatically.

So easy! Thanks for your help FinnNK.

Edit: I should add a step in there to find the stored procedure call with parameters I used SQL Profiler on my database.

What's the most efficient way to check if a record exists in Oracle?

SELECT 'Y' REC_EXISTS             
FROM SALES                       
WHERE SALES_TYPE = 'Accessories'

The result will either be 'Y' or NULL. Simply test against 'Y'

Types in MySQL: BigInt(20) vs Int(20)

The number in parentheses in a type declaration is display width, which is unrelated to the range of values that can be stored in a data type. Just because you can declare Int(20) does not mean you can store values up to 10^20 in it:

[...] This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. ...

The display width does not constrain the range of values that can be stored in the column, nor the number of digits that are displayed for values having a width exceeding that specified for the column. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range allowed by three characters are displayed using more than three characters.

For a list of the maximum and minimum values that can be stored in each MySQL datatype, see here.

Setting a max character length in CSS

There is a CSS 'length value' of ch.

From MDN

This unit represents the width, or more precisely the advance measure, of the glyph '0' (zero, the Unicode character U+0030) in the element's font.

This may approximate what you are after.

_x000D_
_x000D_
p {_x000D_
  overflow: hidden;_x000D_
  max-width: 75ch;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt rem odit quis quaerat. In dolorem praesentium velit ea esse consequuntur cum fugit sequi voluptas ut possimus voluptatibus deserunt nisi eveniet!Lorem ipsum dolor sit amet, consectetur_x000D_
  adipisicing elit. Dolorem voluptates vel dolorum autem ex repudiandae iste quasi. Minima explicabo qui necessitatibus porro nihil aliquid deleniti ullam repudiandae dolores corrupti eaque.</p>
_x000D_
_x000D_
_x000D_

Composer update memory limit

In my case it needed higher permissions along with this memory limit increase.

sudo COMPOSER_MEMORY_LIMIT=2G php /opt/bitnami/php/bin/composer.phar update

How to center an image horizontally and align it to the bottom of the container?

have you tried:

.image_block{
text-align: center;
vertical-align: bottom;
}

Cassandra cqlsh - connection refused

cqlsh --cqlversion="3.4.0" Connected to Test Cluster at 127.0.0.1:9042. [cqlsh 5.0.1 | Cassandra 3.0.9 | CQL spec 3.4.0 | Native protocol v4]

try the above command. It works for me.

Maven and adding JARs to system scope

I don't know the real reason but Maven pushes developers to install all libraries (custom too) into some maven repositories, so scope:system is not well liked, A simple workaround is to use maven-install-plugin

follow the usage:

write your dependency in this way

<dependency>
    <groupId>com.mylib</groupId>
    <artifactId>mylib-core</artifactId>
    <version>0.0.1</version>
</dependency>

then, add maven-install-plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-install-plugin</artifactId>
    <version>2.5.2</version>
    <executions>
        <execution>
            <id>install-external</id>
            <phase>clean</phase>
            <configuration>
                <file>${basedir}/lib/mylib-core-0.0.1.jar</file>
                <repositoryLayout>default</repositoryLayout>
                <groupId>com.mylib</groupId>
                <artifactId>mylib-core</artifactId>
                <version>0.0.1</version>
                <packaging>jar</packaging>
                <generatePom>true</generatePom>
            </configuration>
            <goals>
                <goal>install-file</goal>
            </goals>
        </execution>
    </executions>
</plugin>

pay attention to phase:clean, to install your custom library into your repository, you have to run mvn clean and then mvn install

How to Update Multiple Array Elements in mongodb

This does in fact relate to the long standing issue at http://jira.mongodb.org/browse/SERVER-1243 where there are in fact a number of challenges to a clear syntax that supports "all cases" where mutiple array matches are found. There are in fact methods already in place that "aid" in solutions to this problem, such as Bulk Operations which have been implemented after this original post.

It is still not possible to update more than a single matched array element in a single update statement, so even with a "multi" update all you will ever be able to update is just one mathed element in the array for each document in that single statement.

The best possible solution at present is to find and loop all matched documents and process Bulk updates which will at least allow many operations to be sent in a single request with a singular response. You can optionally use .aggregate() to reduce the array content returned in the search result to just those that match the conditions for the update selection:

db.collection.aggregate([
    { "$match": { "events.handled": 1 } },
    { "$project": {
        "events": {
            "$setDifference": [
               { "$map": {
                   "input": "$events",
                   "as": "event",
                   "in": {
                       "$cond": [
                           { "$eq": [ "$$event.handled", 1 ] },
                           "$$el",
                           false
                       ]
                   }
               }},
               [false]
            ]
        }
    }}
]).forEach(function(doc) {
    doc.events.forEach(function(event) {
        bulk.find({ "_id": doc._id, "events.handled": 1  }).updateOne({
            "$set": { "events.$.handled": 0 }
        });
        count++;

        if ( count % 1000 == 0 ) {
            bulk.execute();
            bulk = db.collection.initializeOrderedBulkOp();
        }
    });
});

if ( count % 1000 != 0 )
    bulk.execute();

The .aggregate() portion there will work when there is a "unique" identifier for the array or all content for each element forms a "unique" element itself. This is due to the "set" operator in $setDifference used to filter any false values returned from the $map operation used to process the array for matches.

If your array content does not have unique elements you can try an alternate approach with $redact:

db.collection.aggregate([
    { "$match": { "events.handled": 1 } },
    { "$redact": {
        "$cond": {
            "if": {
                "$eq": [ { "$ifNull": [ "$handled", 1 ] }, 1 ]
            },
            "then": "$$DESCEND",
            "else": "$$PRUNE"
        }
    }}
])

Where it's limitation is that if "handled" was in fact a field meant to be present at other document levels then you are likely going to get unexepected results, but is fine where that field appears only in one document position and is an equality match.

Future releases ( post 3.1 MongoDB ) as of writing will have a $filter operation that is simpler:

db.collection.aggregate([
    { "$match": { "events.handled": 1 } },
    { "$project": {
        "events": {
            "$filter": {
                "input": "$events",
                "as": "event",
                "cond": { "$eq": [ "$$event.handled", 1 ] }
            }
        }
    }}
])

And all releases that support .aggregate() can use the following approach with $unwind, but the usage of that operator makes it the least efficient approach due to the array expansion in the pipeline:

db.collection.aggregate([
    { "$match": { "events.handled": 1 } },
    { "$unwind": "$events" },
    { "$match": { "events.handled": 1 } },
    { "$group": {
        "_id": "$_id",
        "events": { "$push": "$events" }
    }}        
])

In all cases where the MongoDB version supports a "cursor" from aggregate output, then this is just a matter of choosing an approach and iterating the results with the same block of code shown to process the Bulk update statements. Bulk Operations and "cursors" from aggregate output are introduced in the same version ( MongoDB 2.6 ) and therefore usually work hand in hand for processing.

In even earlier versions then it is probably best to just use .find() to return the cursor, and filter out the execution of statements to just the number of times the array element is matched for the .update() iterations:

db.collection.find({ "events.handled": 1 }).forEach(function(doc){ 
    doc.events.filter(function(event){ return event.handled == 1 }).forEach(function(event){
        db.collection.update({ "_id": doc._id },{ "$set": { "events.$.handled": 0 }});
    });
});

If you are aboslutely determined to do "multi" updates or deem that to be ultimately more efficient than processing multiple updates for each matched document, then you can always determine the maximum number of possible array matches and just execute a "multi" update that many times, until basically there are no more documents to update.

A valid approach for MongoDB 2.4 and 2.2 versions could also use .aggregate() to find this value:

var result = db.collection.aggregate([
    { "$match": { "events.handled": 1 } },
    { "$unwind": "$events" },
    { "$match": { "events.handled": 1 } },
    { "$group": {
        "_id": "$_id",
        "count": { "$sum": 1 }
    }},
    { "$group": {
        "_id": null,
        "count": { "$max": "$count" }
    }}
]);

var max = result.result[0].count;

while ( max-- ) {
    db.collection.update({ "events.handled": 1},{ "$set": { "events.$.handled": 0 }},{ "multi": true })
}

Whatever the case, there are certain things you do not want to do within the update:

  1. Do not "one shot" update the array: Where if you think it might be more efficient to update the whole array content in code and then just $set the whole array in each document. This might seem faster to process, but there is no guarantee that the array content has not changed since it was read and the update is performed. Though $set is still an atomic operator, it will only update the array with what it "thinks" is the correct data, and thus is likely to overwrite any changes occurring between read and write.

  2. Do not calculate index values to update: Where similar to the "one shot" approach you just work out that position 0 and position 2 ( and so on ) are the elements to update and code these in with and eventual statement like:

    { "$set": {
        "events.0.handled": 0,
        "events.2.handled": 0
    }}
    

    Again the problem here is the "presumption" that those index values found when the document was read are the same index values in th array at the time of update. If new items are added to the array in a way that changes the order then those positions are not longer valid and the wrong items are in fact updated.

So until there is a reasonable syntax determined for allowing multiple matched array elements to be processed in single update statement then the basic approach is to either update each matched array element in an indvidual statement ( ideally in Bulk ) or essentially work out the maximum array elements to update or keep updating until no more modified results are returned. At any rate, you should "always" be processing positional $ updates on the matched array element, even if that is only updating one element per statement.

Bulk Operations are in fact the "generalized" solution to processing any operations that work out to be "multiple operations", and since there are more applications for this than merely updating mutiple array elements with the same value, then it has of course been implemented already, and it is presently the best approach to solve this problem.

When do you use varargs in Java?

I use varargs frequently for outputting to the logs for purposes of debugging.

Pretty much every class in my app has a method debugPrint():

private void debugPrint(Object... msg) {
    for (Object item : msg) System.out.print(item);
    System.out.println();
}

Then, within methods of the class, I have calls like the following:

debugPrint("for assignment ", hwId, ", student ", studentId, ", question ",
    serialNo, ", the grade is ", grade);

When I'm satisfied that my code is working, I comment out the code in the debugPrint() method so that the logs will not contain too much extraneous and unwanted information, but I can leave the individual calls to debugPrint() uncommented. Later, if I find a bug, I just uncomment the debugPrint() code, and all my calls to debugPrint() are reactivated.

Of course, I could just as easily eschew varargs and do the following instead:

private void debugPrint(String msg) {
    System.out.println(msg);
}

debugPrint("for assignment " + hwId + ", student " + studentId + ", question "
    + serialNo + ", the grade is " + grade);

However, in this case, when I comment out the debugPrint() code, the server still has to go through the trouble of concatenating all the variables in every call to debugPrint(), even though nothing is done with the resulting string. If I use varargs, however, the server only has to put them in an array before it realizes that it doesn't need them. Lots of time is saved.

How to filter array when object key value is in array

You can do it with Array.prototype.filter(),

var data = { records : [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] }
var empIds = [1,4,5]
var filteredArray = data.records.filter(function(itm){
  return empIds.indexOf(itm.empid) > -1;
});

filteredArray = { records : filteredArray };

If? the ?callBack? returns a ?true? value, then the ?itm? passed to that particular callBack will be filtered out. You can read more about it here.??????

Laravel, sync() - how to sync an array and also pass additional pivot fields?

In order to sync multiple models along with custom pivot data, you need this:

$user->roles()->sync([ 
    1 => ['expires' => true],
    2 => ['expires' => false],
    ...
]);

Ie.

sync([
    related_id => ['pivot_field' => value],
    ...
]);

edit

Answering the comment:

$speakers  = (array) Input::get('speakers'); // related ids
$pivotData = array_fill(0, count($speakers), ['is_speaker' => true]);
$syncData  = array_combine($speakers, $pivotData);

$user->roles()->sync($syncData);

How to set a cron job to run at a exact time?

check out

http://www.thesitewizard.com/general/set-cron-job.shtml

for the specifics of setting your crontab directives.

 45 10 * * *

will run in the 10th hour, 45th minute of every day.

for midnight... maybe

 0 0 * * *

Good ways to sort a queryset? - Django

What about

import operator

auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))

In Django 1.4 and newer you can order by providing multiple fields.
Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

order_by(*fields)

By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.

Example:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

The result above will be ordered by score descending, then by last_name ascending. The negative sign in front of "-score" indicates descending order. Ascending order is implied.

Get input value from TextField in iOS alert in Swift

Updated for Swift 3 and above:

//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.text = "Some default text"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.present(alert, animated: true, completion: nil)

Swift 2.x

Assuming you want an action alert on iOS:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

How to print VARCHAR(MAX) using Print Statement?

I know it's an old question, but what I did is not mentioned here.

For me the following worked.

DECLARE @info NVARCHAR(MAX)

--SET @info to something big

PRINT CAST(@info AS NTEXT)

R dplyr: Drop multiple columns

We can try

iris %>% 
      select_(.dots= setdiff(names(.),drop.cols))

How to "Open" and "Save" using java

Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.

Get current cursor position

You get the cursor position by calling GetCursorPos.

POINT p;
if (GetCursorPos(&p))
{
    //cursor position now in p.x and p.y
}

This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.

if (ScreenToClient(hwnd, &p))
{
    //p.x and p.y are now relative to hwnd's client area
}

You hide and show the cursor with ShowCursor.

ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again

You must ensure that every call to hide the cursor is matched by one that shows it again.

How do I get the old value of a changed cell in Excel VBA?

Using Static will solve your problem (with some other stuff to initialize old_value properly:

Private Sub Worksheet_Change(ByVal Target As Range)
    Static old_value As String
    Dim inited as Boolean 'Used to detect first call and fill old_value
    Dim new_value As String
    If Not Intersect(cell, Range("cell_of_interest")) Is Nothing Then
         new_value = Range("cell_of_interest").Value
         If Not inited Then
             inited = True
         Else
            Call DoFoo (old_value, new_value)
        End If
        old_value = new_value
    Next cell
End Sub

In workbook code, force call of Worksheet_change to fill old_value:

Private Sub Private Sub Workbook_Open()
     SheetX.Worksheet_Change SheetX.Range("cell_of_interest")
End Sub

Note, however, that ANY solution based in VBA variables (including dictionary and another more sophisticate methods) will fail if you stop (Reset) running code (eg. while creating new macros, debugging some code, ...). To avoid such, consider using alternative storage methods (hidden worksheet, for example).

Linq to Sql: Multiple left outer joins

I think you should be able to follow the method used in this post. It looks really ugly, but I would think you could do it twice and get the result you want.

I wonder if this is actually a case where you'd be better off using DataContext.ExecuteCommand(...) instead of converting to linq.

Nullable type as a generic parameter possible?

This may be a dead thread, but I tend to use the following:

public static T? GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : struct 
{
    return reader[columnName] as T?;
}

access denied for user @ 'localhost' to database ''

You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

In my case, heredoc caused the issue. There is no problem with PHP version 7.3 up. Howerver, it error with PHP 7.0.33 if you use heredoc with space.

My example code

$rexpenditure = <<<Expenditure
                  <tr>
                      <td>$row->payment_referencenumber</td>
                      <td>$row->payment_requestdate</td>
                      <td>$row->payment_description</td>
                      <td>$row->payment_fundingsource</td>
                      <td>$row->payment_agencyulo</td>
                      <td>$row->payment_agencyproject</td>
                      <td>$$row->payment_disbustment</td>
                      <td>$row->payment_payeename</td>
                      <td>$row->payment_processpayment</td>
                  </tr>
Expenditure;

It will error if there is a space on PHP 7.0.33.

Delete all the records

When the table is very large, it's better to delete table itself with drop table TableName and recreate it, if one has create table query; rather than deleting records one by one, using delete from statement because that can be time consuming.

How to call a function within class?

That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).

Generate unique random numbers between 1 and 100

Another approach is to generate an 100 items array with ascending numbers and sort it randomly. This leads actually to a really short and (in my opinion) simple snippet.

_x000D_
_x000D_
const numbers = Array(100).fill().map((_, index) => index + 1);_x000D_
numbers.sort(() => Math.random() - 0.5);_x000D_
console.log(numbers.slice(0, 8));
_x000D_
_x000D_
_x000D_

Java ArrayList - how can I tell if two lists are equal, order not mattering?

Probably the easiest way for any list would be:

listA.containsAll(listB) && listB.containsAll(listA)

Getting the text that follows after the regex match

You just need to put "group(1)" instead of "group()" in the following line and the return will be the one you expected:

System.out.println("I found the text: " + matcher.group(**1**).toString());

Collection was modified; enumeration operation may not execute

I had the same issue, and it was solved when I used a for loop instead of foreach.

// foreach (var item in itemsToBeLast)
for (int i = 0; i < itemsToBeLast.Count; i++)
{
    var matchingItem = itemsToBeLast.FirstOrDefault(item => item.Detach);

   if (matchingItem != null)
   {
      itemsToBeLast.Remove(matchingItem);
      continue;
   }
   allItems.Add(itemsToBeLast[i]);// (attachDetachItem);
}

cast class into another class or convert class to another

By using following code you can copy any class object to another class object for same name and same type of properties.

public class CopyClass
{
    /// <summary>
    /// Copy an object to destination object, only matching fields will be copied
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sourceObject">An object with matching fields of the destination object</param>
    /// <param name="destObject">Destination object, must already be created</param>
    public static void CopyObject<T>(object sourceObject, ref T destObject)
    {
        //  If either the source, or destination is null, return
        if (sourceObject == null || destObject == null)
            return;

        //  Get the type of each object
        Type sourceType = sourceObject.GetType();
        Type targetType = destObject.GetType();

        //  Loop through the source properties
        foreach (PropertyInfo p in sourceType.GetProperties())
        {
            //  Get the matching property in the destination object
            PropertyInfo targetObj = targetType.GetProperty(p.Name);
            //  If there is none, skip
            if (targetObj == null)
                continue;

            //  Set the value in the destination
            targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
        }
    }
}

Call Method Like,

ClassA objA = new ClassA();
ClassB objB = new ClassB();

CopyClass.CopyObject(objOfferMast, ref objB);

It will copy objA into objB.

How to set default value for column of new created table from select statement in 11g

You will need to alter table abc modify (salary default 0);

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

A solution for me:

$old_ErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if((Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) -eq $null) {
   WriteTraceForTrans "The session configuration MyShellUri is already unregistered."
}
else {        
   #Unregister-PSSessionConfiguration -Name "MyShellUri" -Force -ErrorAction Ignore
}
$ErrorActionPreference = $old_ErrorActionPreference 

Or use try-catch

try { 

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)

} 
catch {

}

CSS: How to align vertically a "label" and "input" inside a "div"?

a more modern approach would be to use css flex-box.

_x000D_
_x000D_
div {_x000D_
  height: 50px;_x000D_
  background: grey;_x000D_
  display: flex;_x000D_
  align-items: center_x000D_
}
_x000D_
<div>_x000D_
  <label for='name'>Name:</label>_x000D_
  <input type='text' id='name' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

a more complex example... if you have multible elements in the flex flow, you can use align-self to align single elements differently to the specified align...

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  align-items: center_x000D_
}_x000D_
_x000D_
* {_x000D_
  margin: 10px_x000D_
}_x000D_
_x000D_
label {_x000D_
  align-self: flex-start_x000D_
}
_x000D_
<div>_x000D_
  <img src="https://de.gravatar.com/userimage/95932142/195b7f5651ad2d4662c3c0e0dccd003b.png?size=50" />_x000D_
  <label>Text</label>_x000D_
  <input placeholder="Text" type="text" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

its also super easy to center horizontally and vertically:

_x000D_
_x000D_
div {_x000D_
  position:absolute;_x000D_
  top:0;left:0;right:0;bottom:0;_x000D_
  background: grey;_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content:center_x000D_
}
_x000D_
<div>_x000D_
  <label for='name'>Name:</label>_x000D_
  <input type='text' id='name' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Bootstrap Collapse not Collapsing

jQuery is required ;-)

DEMO

<html>
<head>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <!-- THIS LINE -->
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="panel-group" id="accordion">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                    Collapsible Group Item #1
                </a>
            </h4>
        </div>
        <div id="collapseOne" class="panel-collapse collapse in">
            <div class="panel-body">
                Anim pariatur cliche reprehenderit
            </div>
        </div>
    </div>
</div>

</body>
</html>

Find all files in a folder

A lot of these answers won't actually work, having tried them myself. Give this a go:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
{
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}

It will move all .txt files on the desktop to the folder TextFiles.

How to strip HTML tags from string in JavaScript?

var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World

That pretty much the best way of doing it, you're letting the browser do what it does best -- parse HTML.


Edit: As noted in the comments below, this is not the most cross-browser solution. The most cross-browser solution would be to recursively go through all the children of the element and concatenate all text nodes that you find. However, if you're using jQuery, it already does it for you:

alert($("<p>Hello, <b>World</b></p>").text());

Check out the text method.

Bootstrap Dropdown with Hover

The best way of doing it is to just trigger bootstraps click event with a hover. This way, it should still remain touch device friendly

$('.dropdown').hover(function(){ 
  $('.dropdown-toggle', this).trigger('click'); 
});

What's the fastest way to convert String to Number in JavaScript?

Here is simple way to do it: var num = Number(str); in this example str is the variable that contains the string. You can tested and see how it works open: Google chrome developer tools, then go to the console and paste the following code. read the comments to understand better how the conversion is done.

// Here Im creating my variable as a string
var str = "258";


// here im printing the string variable: str
console.log ( str );


// here Im using typeof , this tells me that the variable str is the type: string
console.log ("The variable str is type: " + typeof str);


// here is where the conversion happens
// Number will take the string in the parentesis and transform it to a variable num as type: number
var num = Number(str);
console.log ("The variable num is type: " + typeof num);

Find the number of employees in each department - SQL Oracle

SELECT d.DEPTNO
    , d.dname
    , COUNT(e.ename) AS count
FROM   emp e
      INNER JOIN dept d ON e.DEPTNO = d.deptno
GROUP BY d.deptno
      , d.dname;

How do I convert between ISO-8859-1 and UTF-8 in Java?

The easiest way to convert an ISO-8859-1 string to UTF-8 string.

private static String convertIsoToUTF8(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("ISO-8859-1"), "utf-8");
}

If we want to convert an UTF-8 string to ISO-8859-1 string.

private static String convertUTF8ToISO(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("utf-8"), "ISO-8859-1");
}

Moreover, a method that converts an ISO-8859-1 string to UTF-8 string without using the constructor of class String.

public static String convertISO_to_UTF8_personal(String strISO_8859_1) {
    String res = "";
    int i = 0;
    for (i = 0; i < strISO_8859_1.length() - 1; i++) {
        char ch = strISO_8859_1.charAt(i);
        char chNext = strISO_8859_1.charAt(i + 1);
        if (ch <= 127) {
            res += ch;
        } else if (ch == 194 && chNext >= 128 && chNext <= 191) {
            res += chNext;
        } else if(ch == 195 && chNext >= 128 && chNext <= 191){
            int resNum = chNext + 64;
            res += (char) resNum;
        } else if(ch == 194){
            res += (char) 173;
        } else if(ch == 195){
            res += (char) 224;
        }
    }
    char ch = strISO_8859_1.charAt(i);
    if (ch <= 127 ){
        res += ch;
    }
    return res;
}

}

That method is based on enconding utf-8 to iso-8859-1 of this website. Encoding utf-8 to iso-8859-1

How to send email by using javascript or jquery

The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:

Simple PHP mail script

Using a script like that, you'd POST the contents of your web form to the script, using a function like this:

jQuery.post

And then the script would take those values, plus a username and password for the mail server, and connect to the server to send the mail.

Handling Enter Key in Vue.js

You forget a '}' before the last line (to close the "methods {...").

This code works :

_x000D_
_x000D_
Vue.config.keyCodes.atsign = 50;_x000D_
_x000D_
new Vue({_x000D_
  el: '#myApp',_x000D_
  data: {_x000D_
    emailAddress: '',_x000D_
    log: ''_x000D_
  },_x000D_
  methods: {_x000D_
  _x000D_
    onEnterClick: function() {_x000D_
     alert('Enter was pressed');_x000D_
    },_x000D_
    _x000D_
    onAtSignClick: function() {_x000D_
     alert('@ was pressed');_x000D_
    },_x000D_
    _x000D_
    postEmailAddress: function() {_x000D_
   this.log += '\n\nPosting';_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
html, body, #editor {_x000D_
  margin: 0;_x000D_
  height: 100%;_x000D_
  color: #333;_x000D_
}
_x000D_
<script src="https://vuejs.org/js/vue.min.js"></script>_x000D_
_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
_x000D_
  <input type="text" v-model="emailAddress" v-on:keyup.enter="onEnterClick" v-on:keyup.atsign="onAtSignClick" />_x000D_
  _x000D_
  <button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
  <br /><br />_x000D_
  _x000D_
  <textarea v-model="log" rows="4"></textarea>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to update Git clone

git pull origin master

this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.

How can I replace text with CSS?

Using a pseudo element, this method doesn't require knowledge of the original element and doesn't require any additional markup.

#someElement{
    color: transparent; /* You may need to change this color */
    position: relative;
}
#someElement:after { /* Or use :before if that tickles your fancy */
    content: "New text";
    color: initial;
    position: absolute;
    top: 0;
    left: 0;
}

Bootstrap collapse animation not smooth

Padding around the collapsing div must be 0

PHP Convert String into Float/Double

Surprisingly there is no accepted answer. The issue only exists in 32-bit PHP.

From the documentation,

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

In other words, the $string is first interpreted as INT, which cause overflow (The $string value 2968789218 exceeds the maximum value (PHP_INT_MAX) of 32-bit PHP, which is 2147483647.), then evaluated to float by (float) or floatval().

Thus, the solution is:

$string = "2968789218";
echo 'Original: ' . floatval($string) . PHP_EOL;
$string.= ".0";
$float = floatval($string);
echo 'Corrected: ' . $float . PHP_EOL;

which outputs:

Original: 2.00
Corrected: 2968789218

To check whether your PHP is 32-bit or 64-bit, you can:

echo PHP_INT_MAX;

If your PHP is 64-bit, it will print out 9223372036854775807, otherwise it will print out 2147483647.

How to define an empty object in PHP

to access data in a stdClass in similar fashion you do with an asociative array just use the {$var} syntax.

$myObj = new stdClass;
$myObj->Prop1 = "Something";
$myObj->Prop2 = "Something else";

// then to acces it directly

echo $myObj->{'Prop1'};
echo $myObj->{'Prop2'};

// or what you may want

echo $myObj->{$myStringVar};

How to iterate through range of Dates in Java?

public static final void generateRange(final Date dateFrom, final Date dateTo)
{
    final Calendar current = Calendar.getInstance();
    current.setTime(dateFrom);

    while (!current.getTime().after(dateTo))
    {
        // TODO

        current.add(Calendar.DATE, 1);
    }
}

ResourceDictionary in a separate assembly

Using XAML:

If you know the other assembly structure and want the resources in c# code, then use below code:

 ResourceDictionary dictionary = new ResourceDictionary();
 dictionary.Source = new Uri("pack://application:,,,/WpfControlLibrary1;Component/RD1.xaml", UriKind.Absolute);
 foreach (var item in dictionary.Values)
 {
    //operations
 }

Output: If we want to use ResourceDictionary RD1.xaml of Project WpfControlLibrary1 into StackOverflowApp project.

Structure of Projects:

Structure of Projects

Resource Dictionary: Resource Dictionary

Code Output:

Output

PS: All ResourceDictionary Files should have Build Action as 'Resource' or 'Page'.

Using C#:

If anyone wants the solution in purely c# code then see my this solution.

Optional Parameters in Go?

For arbitrary, potentially large number of optional parameters, a nice idiom is to use Functional options.

For your type Foobar, first write only one constructor:

func NewFoobar(options ...func(*Foobar) error) (*Foobar, error){
  fb := &Foobar{}
  // ... (write initializations with default values)...
  for _, op := range options{
    err := op(fb)
    if err != nil {
      return nil, err
    }
  }
  return fb, nil
}

where each option is a function which mutates the Foobar. Then provide convenient ways for your user to use or create standard options, for example :

func OptionReadonlyFlag(fb *Foobar) error {
  fb.mutable = false
  return nil
}

func OptionTemperature(t Celsius) func(*Foobar) error {
  return func(fb *Foobar) error {
    fb.temperature = t
    return nil
  }
}

Playground

For conciseness, you may give a name to the type of the options (Playground) :

type OptionFoobar func(*Foobar) error

If you need mandatory parameters, add them as first arguments of the constructor before the variadic options.

The main benefits of the Functional options idiom are :

  • your API can grow over time without breaking existing code, because the constuctor signature stays the same when new options are needed.
  • it enables the default use case to be its simplest: no arguments at all!
  • it provides fine control over the initialization of complex values.

This technique was coined by Rob Pike and also demonstrated by Dave Cheney.

Index of Currently Selected Row in DataGridView

Try the following:

int myIndex = MyDataGrid.SelectedIndex;

This will give the index of the row which is currently selected.

Hope this helps

Iteration ng-repeat only X times in AngularJs

Angular comes with a limitTo:limit filter, it support limiting first x items and last x items:

<div ng-repeat="item in items|limitTo:4">{{item}}</div>

Ruby value of a hash key?

I didn't understand your problem clearly but I think this is what you're looking for(Based on my understanding)

  person =   {"name"=>"BillGates", "company_name"=>"Microsoft", "position"=>"Chairman"}

  person.delete_if {|key, value| key == "name"} #doing something if the key == "something"

  Output: {"company_name"=>"Microsoft", "position"=>"Chairman"}

How can I change the default width of a Twitter Bootstrap modal box?

I've found this solution that works better for me. You can use this:

$('.modal').css({
  'width': function () { 
    return ($(document).width() * .9) + 'px';  
  },
  'margin-left': function () { 
    return -($(this).width() / 2); 
  }
});

or this depending your requirements:

$('.modal').css({
  width: 'auto',
  'margin-left': function () {
     return -($(this).width() / 2);
  }
});

See the post where I found that: https://github.com/twitter/bootstrap/issues/675

How to decode a QR-code image in (preferably pure) Python?

I'm answering only the part of the question about zbar installation.

I spent nearly half an hour a few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:

PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.

PS2: I just tested pyzbar with pip install pyzbar and it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

deleting folder from java

You're storing all (sub-) files and folder recursively in a list, but with your current code you store the parent folder before you store the children. And so you try to delete the folder before it is empty. Try this code:

   if(tempFile.isDirectory()) {
        // children first
        fetchCompleteList(filesList, folderList, tempFile.getAbsolutePath());
        // parent folder last
        folderList.add(tempFile.getAbsolutePath());
   }

Adding new files to a subversion repository

  • Checkout a working copy of the repository (or at least the subdirectory that you want to add the files to): svn checkout https://example.org/path/to/repo/bleh
  • Copy the files over there.
  • svn add file1 file2...
  • svn commit

I am not aware of a quicker option.

Note: if you are on the same machine as your Subversion repository, the URL can use the file: specifier with a path in place of https: in the svn checkout command. For example svn checkout file:///path/to/repo/bleh.

PS. as pointed out in the comments and other answers, you can use something like svn import . <URL> if you want to recursively import everything in the current directory. With this option, however, you can't skip over some of the files; it's all or nothing.

How to make a loop in x86 assembly language?

.model small
.stack 100h
.code 
Main proc
Mov cx , 30 ; //that number control the loop 30 means the loop will 
;excite 30 time 
Ioopfront:
Mov ah , 1
Int 21h 
Loop loopfront; 

this cod will take 30 character

How can a LEFT OUTER JOIN return more records than exist in the left table?

It isn't impossible. The number of records in the left table is the minimum number of records it will return. If the right table has two records that match to one record in the left table, it will return two records.

Iterating C++ vector from the end to the beginning

I like the backwards iterator at the end of Yakk - Adam Nevraumont's answer, but it seemed complicated for what I needed, so I wrote this:

template <class T>
class backwards {
    T& _obj;
public:
    backwards(T &obj) : _obj(obj) {}
    auto begin() {return _obj.rbegin();}
    auto end() {return _obj.rend();}
};

I'm able to take a normal iterator like this:

for (auto &elem : vec) {
    // ... my useful code
}

and change it to this to iterate in reverse:

for (auto &elem : backwards(vec)) {
    // ... my useful code
}

Open Source HTML to PDF Renderer with Full CSS Support

It's not open source, but you can at least get a free personal use license to Prince, which really does a lovely job.

How do you check "if not null" with Eloquent?

If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->

 $searchResultQuery = Users::query(); 
 $searchResultQuery->where('status_message', '<>', '', 'and'); // is not null
 $searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null 

Or with scope in model :

public function scopeNotNullOnly($query){

    return $query->where('status_message', '<>', '');
}

SQL Error: ORA-00936: missing expression

You did two mistakes . I think you misplace FROM and WHERE keywords.

SELECT DISTINCT Description, Date as treatmentDate
     FROM doothey.Patient P, doothey.Account A, doothey.AccountLine AL,  doothey.Item.I --Here you use "." operator to "I" alias 
  WHERE  -- WHERE should be located here. 
   P.PatientID = A.PatientID
    AND A.AccountNo = AL.AccountNo
    AND AL.ItemNo = I.ItemNo
    AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');

How to manually install an artifact in Maven 2?

I had to add packaging, so:

mvn install:install-file \
  -DgroupId=javax.transaction \
  -DartifactId=jta \
  -Dversion=1.0.1B \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true \
  -Dpackaging=jar

How can I drop all the tables in a PostgreSQL database?

If you have the PL/PGSQL procedural language installed you can use the following to remove everything without a shell/Perl external script.

DROP FUNCTION IF EXISTS remove_all();

CREATE FUNCTION remove_all() RETURNS void AS $$
DECLARE
    rec RECORD;
    cmd text;
BEGIN
    cmd := '';

    FOR rec IN SELECT
            'DROP SEQUENCE ' || quote_ident(n.nspname) || '.'
                || quote_ident(c.relname) || ' CASCADE;' AS name
        FROM
            pg_catalog.pg_class AS c
        LEFT JOIN
            pg_catalog.pg_namespace AS n
        ON
            n.oid = c.relnamespace
        WHERE
            relkind = 'S' AND
            n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
            pg_catalog.pg_table_is_visible(c.oid)
    LOOP
        cmd := cmd || rec.name;
    END LOOP;

    FOR rec IN SELECT
            'DROP TABLE ' || quote_ident(n.nspname) || '.'
                || quote_ident(c.relname) || ' CASCADE;' AS name
        FROM
            pg_catalog.pg_class AS c
        LEFT JOIN
            pg_catalog.pg_namespace AS n
        ON
            n.oid = c.relnamespace WHERE relkind = 'r' AND
            n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
            pg_catalog.pg_table_is_visible(c.oid)
    LOOP
        cmd := cmd || rec.name;
    END LOOP;

    FOR rec IN SELECT
            'DROP FUNCTION ' || quote_ident(ns.nspname) || '.'
                || quote_ident(proname) || '(' || oidvectortypes(proargtypes)
                || ');' AS name
        FROM
            pg_proc
        INNER JOIN
            pg_namespace ns
        ON
            (pg_proc.pronamespace = ns.oid)
        WHERE
            ns.nspname =
            'public'
        ORDER BY
            proname
    LOOP
        cmd := cmd || rec.name;
    END LOOP;

    EXECUTE cmd;
    RETURN;
END;
$$ LANGUAGE plpgsql;

SELECT remove_all();

Rather than type this in at the "psql" prompt I would suggest you copy it to a file and then pass the file as input to psql using the "--file" or "-f" options:

psql -f clean_all_pg.sql

Credit where credit is due: I wrote the function, but think the queries (or the first one at least) came from someone on one of the pgsql mailing lists years ago. Don't remember exactly when or which one.

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

How to semantically add heading to a list

Your first option is the good one. It's the least problematic one and you've already found the correct reasons why you couldn't use the other options.

By the way, your heading IS explicitly associated with the <ul> : it's right before the list! ;)

edit: Steve Faulkner, one of the editors of W3C HTML5 and 5.1 has sketched out a definition of an lt element. That's an unofficial draft that he'll discuss for HTML 5.2, nothing more yet.

How to add hyperlink in JLabel?

You can use this under an

actionListener ->  Runtime.getRuntime().exec("cmd.exe /c start chrome www.google.com")`

or if you want to use Internet Explorer or Firefox replace chrome with iexplore or firefox

How to find largest objects in a SQL Server database?

This query help to find largest table in you are connection.

SELECT  TOP 1 OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE index_id < 2
ORDER BY st.row_count DESC

How can I open a URL in Android's web browser from my application?

Simple Answer

You can see the official sample from Android Developer.

/**
 * Open a web page of a specified URL
 *
 * @param url URL to open
 */
public void openWebPage(String url) {
    Uri webpage = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

How it works

Please have a look at the constructor of Intent:

public Intent (String action, Uri uri)

You can pass android.net.Uri instance to the 2nd parameter, and a new Intent is created based on the given data url.

And then, simply call startActivity(Intent intent) to start a new Activity, which is bundled with the Intent with the given URL.

Do I need the if check statement?

Yes. The docs says:

If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity(). If the result is null, you should not use the intent and, if possible, you should disable the feature that invokes the intent.

Bonus

You can write in one line when creating the Intent instance like below:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

Security of REST authentication schemes

REST means working with the standards of the web, and the standard for "secure" transfer on the web is SSL. Anything else is going to be kind of funky and require extra deployment effort for clients, which will have to have encryption libraries available.

Once you commit to SSL, there's really nothing fancy required for authentication in principle. You can again go with web standards and use HTTP Basic auth (username and secret token sent along with each request) as it's much simpler than an elaborate signing protocol, and still effective in the context of a secure connection. You just need to be sure the password never goes over plain text; so if the password is ever received over a plain text connection, you might even disable the password and mail the developer. You should also ensure the credentials aren't logged anywhere upon receipt, just as you wouldn't log a regular password.

HTTP Digest is a safer approach as it prevents the secret token being passed along; instead, it's a hash the server can verify on the other end. Though it may be overkill for less sensitive applications if you've taken the precautions mentioned above. After all, the user's password is already transmitted in plain-text when they log in (unless you're doing some fancy JavaScript encryption in the browser), and likewise their cookies on each request.

Note that with APIs, it's better for the client to be passing tokens - randomly generated strings - instead of the password the developer logs into the website with. So the developer should be able to log into your site and generate new tokens that can be used for API verification.

The main reason to use a token is that it can be replaced if it's compromised, whereas if the password is compromised, the owner could log into the developer's account and do anything they want with it. A further advantage of tokens is you can issue multiple tokens to the same developers. Perhaps because they have multiple apps or because they want tokens with different access levels.

(Updated to cover implications of making the connection SSL-only.)

Is it possible to declare two variables of different types in a for loop?

You can't declare multiple types in the initialization, but you can assign to multiple types E.G.

{
   int i;
   char x;
   for(i = 0, x = 'p'; ...){
      ...
   }
}

Just declare them in their own scope.

How do I get the max ID with Linq to Entity?

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();

Use jquery to set value of div tag

To put text, use .text('text')

If you want to use .html(SomeValue), SomeValue should have html tags that can be inside a div it must work too.

Just check your script location, as farzad said.

Reference: .html and text

Reading integers from binary file in Python

When you read from a binary file, a data type called bytes is used. This is a bit like list or tuple, except it can only store integers from 0 to 255.

Try:

file_size = fin.read(4)
file_size0 = file_size[0]
file_size1 = file_size[1]
file_size2 = file_size[2]
file_size3 = file_size[3]

Or:

file_size = list(fin.read(4))

Instead of:

file_size = int(fin.read(4))

Setting an int to Infinity in C++

int min and max values

Int -2,147,483,648 / 2,147,483,647 Int 64 -9,223,372,036,854,775,808 / 9,223,372,036,854,775,807

i guess you could set a to equal 9,223,372,036,854,775,807 but it would need to be an int64

if you always want a to be grater that b why do you need to check it? just set it to be true always

Creating a copy of a database in PostgreSQL

For those still interested, I have come up with a bash script that does (more or less) what the author wanted. I had to make a daily business database copy on a production system, this script seems to do the trick. Remember to change the database name/user/pw values.

#!/bin/bash

if [ 1 -ne $# ]
then
  echo "Usage `basename $0` {tar.gz database file}"
  exit 65;
fi

if [ -f "$1" ]
then
  EXTRACTED=`tar -xzvf $1`
  echo "using database archive: $EXTRACTED";
else
  echo "file $1 does not exist"
  exit 1
fi


PGUSER=dbuser
PGPASSWORD=dbpw
export PGUSER PGPASSWORD

datestr=`date +%Y%m%d`


dbname="dbcpy_$datestr"
createdbcmd="CREATE DATABASE $dbname WITH OWNER = postgres ENCODING = 'UTF8' TABLESPACE = pg_default LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8' CONNECTION LIMIT = -1;"
dropdbcmp="DROP DATABASE $dbname"

echo "creating database $dbname"
psql -c "$createdbcmd"

rc=$?
if [[ $rc != 0 ]] ; then
  rm -rf "$EXTRACTED"
  echo "error occured while creating database $dbname ($rc)"
  exit $rc
fi


echo "loading data into database"
psql $dbname < $EXTRACTED > /dev/null

rc=$?

rm -rf "$EXTRACTED"

if [[ $rc != 0 ]] ; then
  psql -c "$dropdbcmd"
  echo "error occured while loading data to database $dbname ($rc)"
  exit $rc
fi


echo "finished OK"

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

In Tkinter is there any way to make a widget not visible?

For hiding a widget you can use function pack_forget() and to again show it you can use pack() function and implement them both in separate functions.

from Tkinter import *
root = Tk()
label=Label(root,text="I was Hidden")
def labelactive():
    label.pack()
def labeldeactive():
    label.pack_forget()
Button(root,text="Show",command=labelactive).pack()
Button(root,text="Hide",command=labeldeactive).pack()
root.mainloop()

Select method in List<t> Collection

I have used a script but to make a join, maybe I can help you

string Email = String.Join(", ", Emails.Where(i => i.Email != "").Select(i => i.Email).Distinct());

sql: check if entry in table A exists in table B

This also works

SELECT *
FROM tableB
WHERE ID NOT IN (
  SELECT ID FROM tableA
);

Is Java RegEx case-insensitive?

Yes, case insensitivity can be enabled and disabled at will in Java regex.

It looks like you want something like this:

    System.out.println(
        "Have a meRry MErrY Christmas ho Ho hO"
            .replaceAll("(?i)\\b(\\w+)(\\s+\\1)+\\b", "$1")
    );
    // Have a meRry Christmas ho

Note that the embedded Pattern.CASE_INSENSITIVE flag is (?i) not \?i. Note also that one superfluous \b has been removed from the pattern.

The (?i) is placed at the beginning of the pattern to enable case-insensitivity. In this particular case, it is not overridden later in the pattern, so in effect the whole pattern is case-insensitive.

It is worth noting that in fact you can limit case-insensitivity to only parts of the whole pattern. Thus, the question of where to put it really depends on the specification (although for this particular problem it doesn't matter since \w is case-insensitive.

To demonstrate, here's a similar example of collapsing runs of letters like "AaAaaA" to just "A".

    System.out.println(
        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("(?i)\\b([A-Z])\\1+\\b", "$1")
    ); // A e I O u

Now suppose that we specify that the run should only be collapsed only if it starts with an uppercase letter. Then we must put the (?i) in the appropriate place:

    System.out.println(
        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("\\b([A-Z])(?i)\\1+\\b", "$1")
    ); // A eeEeeE I O uuUuUuu

More generally, you can enable and disable any flag within the pattern as you wish.

See also

Related questions

Why do Sublime Text 3 Themes not affect the sidebar?

One simple way to do this is :
Go to Preferences -> Package Settings -> Your Theme Name -> Activation

In my case I installed Boxy Theme so the path will be
Preferences -> Package Settings -> Boxy Theme -> Activation

Then there will be a pop-up menu that will let you choose which type of the theme package you want to activate.
Use up and down arrow so choose then press enter or simply click the one you want to choose.

This is steps only applicable if the theme installed also customized the sublime text 3 sidebar.

Hope it help anyone!

How to deal with the URISyntaxException

You have to encode your parameters.

Something like this will do:

import java.net.*;
import java.io.*;

public class EncodeParameter { 

    public static void main( String [] args ) throws URISyntaxException ,
                                         UnsupportedEncodingException   { 

        String myQuery = "^IXIC";

        URI uri = new URI( String.format( 
                           "http://finance.yahoo.com/q/h?s=%s", 
                           URLEncoder.encode( myQuery , "UTF8" ) ) );

        System.out.println( uri );

    }
}

http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html

JSON array get length

Note: if you're using(importing) org.json.simple.JSONArray, you have to use JSONArray.size() to get the data you want. But use JSONArray.length() if you're using org.json.JSONArray.

IF function with 3 conditions

=if([Logical Test 1],[Action 1],if([Logical Test 2],[Action 1],if([Logical Test 3],[Action 3],[Value if all logical tests return false])))

Replace the components in the square brackets as necessary.

How to escape comma and double quote at same time for CSV file?

"cell one","cell "" two","cell "" ,three"

Save this to csv file and see the results, so double quote is used to escape itself

Important Note

"cell one","cell "" two", "cell "" ,three"

will give you a different result because there is a space after the comma, and that will be treated as "

Module 'tensorflow' has no attribute 'contrib'

tf.contrib has moved out of TF starting TF 2.0 alpha.
Take a look at these tf 2.0 release notes https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2 script https://www.tensorflow.org/alpha/guide/upgrade

Laravel orderBy on a relationship

Using sortBy... could help.

$users = User::all()->with('rated')->get()->sortByDesc('rated.rating');

what does "dead beef" mean?

Since IPv6-Adresses are written in Hex-notation you can use "Hexspeak" (numbers 0-9 and letters a-f) in Adresses.

There are a number of words you can use as valid adresses to better momorize them.

If you ping6 www.facebook.com -n you will get something like "2a03:2880:f01c:601:face:b00c:0:1".

Here are some examples:

  • :affe:: (Affe - German for Monkey - seen at a vlan for management board)
  • :1bad:babe:: (one bad babe - seen at a smtp-honeypot)
  • :badc:ab1e:: (bad cable - seen as subnet for a unsecure vlan)
  • :da7a:: (Data - seen for fileservers)
  • :d1a1:: (Dial - seen for VPN Dial-In)

Skip download if files exist in wget?

When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

So adding -nc will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.

See more info at GNU.

How to access the elements of a function's return array?

The underlying problem revolves around accessing the data within the array, as Felix Kling points out in the first response.

In the following code, I've accessed the values of the array with the print and echo constructs.

function data()
{

    $a = "abc";
    $b = "def";
    $c = "ghi";

    $array = array($a, $b, $c);

    print_r($array);//outputs the key/value pair

    echo "<br>";

    echo $array[0].$array[1].$array[2];//outputs a concatenation of the values

}

data();

PHP: Split string into array, like explode with no delimiter

$array = str_split("$string");

will actuall work pretty fine, BUT if you want to preserve the special characters in that string, and you want to do some manipulation with them, THAN I would use

do {
    $array[] = mb_substr( $string, 0, 1, 'utf-8' );
} while ( $string = mb_substr( $string, 1, mb_strlen( $string ), 'utf-8' ) );

because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

On Chrome's latest update (38.0.2125.104 m at the moment), Google added the option to know whether the files loaded to the website were newly downloaded from the server - or read from the local cache.

When an error like yours "hits" the console - you know the files were just downloaded from the server and not read from the local cache. You can recreate this error by clicking Ctrl + F5 (refresh and erase cache).

It fits your description where Firebug (or equivalents) doesn't fire any errors to the console - whilst Chrome does.

So, the bottom line is - your're just fine and you can ignore this error - it's merely an indicator.

jquery : focus to div is not working

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');

Remove scrollbars from textarea

Hide scroll bar, but while still being able to scroll using CSS

To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below:

    -webkit- (Chrome, Safari, newer versions of Opera):
    .element::-webkit-scrollbar { width: 0 !important }
    -moz- (Firefox):
    .element { overflow: -moz-scrollbars-none; }
    -ms- (Internet Explorer +10):
    .element { -ms-overflow-style: none; }

ref: https://www.geeksforgeeks.org/hide-scroll-bar-but-while-still-being-able-to-scroll-using-css/

Javascript onload not working

You can try use in javascript:

window.onload = function() {
 alert("let's go!");
}

Its a good practice separate javascript of html

Shortcut to Apply a Formula to an Entire Column in Excel

Select a range of cells (the entire column in this case), type in your formula, and hold down Ctrl while you press Enter. This places the formula in all selected cells.

How to change the default background color white to something else in twitter bootstrap

You have to override the bootstrap default by being a bit more specific. Try this for a black background:

html body {
    background-color: rgba(0,0,0,1.00);

}

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

What's the best practice to "git clone" into an existing folder?

git clone your_repo tmp && mv tmp/.git . && rm -rf tmp && git reset --mixed

Showing Difference between two datetime values in hours

WOW, I gotta say: keep it simple:

MessageBox.Show("Result: " + (DateTime.Now.AddDays(10) > DateTime.Now));

Result: True

and:

MessageBox.Show("Result: " + DateTime.Now.AddDays(10).Subtract(DateTime.Now));

Result: 10.00:00:00

The DateTime object has all the builtin logic to handle the Boolean result.

Change bullets color of an HTML list without using span

Building off @Marc's solution -- since the bullet character is rendered differently with different fonts and browsers, I used the following css3 technique with border-radius to make a bullet that I have more control over:

li:before {
    content: '';
    background-color: #898989;
    display: inline-block;
    position: relative;
    height: 12px;
    width: 12px;
    border-radius: 6px;
    -webkit-border-radius: 6px;
    -moz-border-radius: 6px;
    -moz-background-clip: padding;
    -webkit-background-clip: padding-box;
    background-clip: padding-box;
    margin-right: 4px;
    top: 2px;
}

Create text file and fill it using bash

Creating a text file in unix can be done through a text editor (vim, emacs, gedit, etc). But what you want might be something like this

echo "insert text here" > myfile.txt

That will put the text 'insert text here' into a file myfile.txt. To verify that this worked use the command 'cat'.

cat myfile.txt

If you want to append to a file use this

echo "append this text" >> myfile.txt

jQuery AJAX form data serialize using PHP

Change your code as follows -

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm");
$("#smt").click(function(){
$.ajax({
        type:"POST",
        url:form.attr("action"),
        data:form.serialize(),

        success: function(response){
        if(response == 1){
              $("#err").html("Hi Tony");//updated
        }  else {
            $("#err").html("I dont know you.");//updated
        }
        }
    });
});
});
</script>

PHP -

<?php
$user=$_POST['user'];
$pass=$_POST['pass'];

if($user=="tony")
{
    echo 1;   
}
else
{
    echo 0;    
}
?>

/usr/bin/codesign failed with exit code 1

Open the project path in terminal and enter the below commands in terminal

1) find . | xargs -0 xattr -c

2) xattr -rc .

This works for me.

Android Studio - Unable to find valid certification path to requested target

Here is my solution for key phrases of the messages: “unable to find valid certification path” and “PKIX path building failed“.

These phrases are shown when a SSL certification file can not be found.

Open https://jcenter.bintray.com/ in your browse and export the certificate in cer format.

Put the certificate in Android Studio’s cert folder

{your-home-directory}/.AndroidStudio3.0/system/tasks/cacerts

Then all went well.

How to fix homebrew permissions?

To resolve errors for Brew permissions on folder run

brew prune

This will resolve the issues & we don't have to chown any directories.

How to import an Excel file into SQL Server?

There are many articles about writing code to import an excel file, but this is a manual/shortcut version:

If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.

The quickest way to get your Excel file into SQL is by using the import wizard:

  1. Open SSMS (Sql Server Management Studio) and connect to the database where you want to import your file into.
  2. Import Data: in SSMS in Object Explorer under 'Databases' right-click the destination database, select Tasks, Import Data. An import wizard will pop up (you can usually just click 'Next' on the first screen).

enter image description here

  1. The next window is 'Choose a Data Source', select Excel:

    • In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).

    • Click the 'Browse' button to select the path to the Excel file you want to import.

    • Select the version of the excel file (97-2003 is usually fine for files with a .XLS extension, or use 2007 for newer files with a .XLSX extension)
    • Tick the 'First Row has headers' checkbox if your excel file contains headers.
    • Click next.

enter image description here

  1. On the 'Choose a Destination' screen, select destination database:
    • Select the 'Server name', Authentication (typically your sql username & password) and select a Database as destination. Click Next.

enter image description here

  1. On the 'Specify Table Copy or Query' window:

    • For simplicity just select 'Copy data from one or more tables or views', click Next.
  2. 'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.

enter image description here

  1. Click Finish.

How to set the text/value/content of an `Entry` widget using a button in tkinter

e= StringVar()
def fileDialog():
    filename = filedialog.askopenfilename(initialdir = "/",title = "Select A 
    File",filetype = (("jpeg","*.jpg"),("png","*.png"),("All Files","*.*")))
    e.set(filename)
la = Entry(self,textvariable = e,width = 30).place(x=230,y=330)
butt=Button(self,text="Browse",width=7,command=fileDialog).place(x=430,y=328)

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

Specifying Font and Size in HTML table

First, try omitting the quotes from 12 and 24. Worth a shot.

Second, it's better to do this in CSS. See also http://www.w3schools.com/css/css_font.asp . Here is an inline style for a table tag:

<table style='font-family:"Courier New", Courier, monospace; font-size:80%' ...>...</table>

Better still, use an external style sheet or a style tag near the top of your HTML document. See also http://www.w3schools.com/css/css_howto.asp .

Show current assembly instruction in GDB

There is a simple solution that consists in using stepi, which in turns moves forward by 1 asm instruction and shows the surrounding asm code.

How to set or change the default Java (JDK) version on OS X?

This tool will do the work for you:

http://www.guigarage.com/2013/02/change-java-version-on-mac-os/

It's a simple JavaOne that can be used to define the current Java Version. The version can be used in a shell that is opened after a version was selected in the tool.

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

My solution...

Ver en jsfiddle

//Fix modal mobile Boostrap 3
function Show(id){
    //Fix CSS
    $(".modal-footer").css({"padding":"19px 20px 20px","margin-top":"15px","text-align":"right","border-top":"1px solid #e5e5e5"});
    $(".modal-body").css("overflow-y","auto");
    //Fix .modal-body height
    $('#'+id).on('shown.bs.modal',function(){
        $("#"+id+">.modal-dialog>.modal-content>.modal-body").css("height","auto");
        h1=$("#"+id+">.modal-dialog").height();
        h2=$(window).height();
        h3=$("#"+id+">.modal-dialog>.modal-content>.modal-body").height();
        h4=h2-(h1-h3);      
        if($(window).width()>=768){
            if(h1>h2){
                $("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
            }
            $("#"+id+">.modal-dialog").css("margin","30px auto");
            $("#"+id+">.modal-dialog>.modal-content").css("border","1px solid rgba(0,0,0,0.2)");
            $("#"+id+">.modal-dialog>.modal-content").css("border-radius",6);               
            if($("#"+id+">.modal-dialog").height()+30>h2){
                $("#"+id+">.modal-dialog").css("margin-top","0px");
                $("#"+id+">.modal-dialog").css("margin-bottom","0px");
            }
        }
        else{
            //Fix full-screen in mobiles
            $("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
            $("#"+id+">.modal-dialog").css("margin",0);
            $("#"+id+">.modal-dialog>.modal-content").css("border",0);
            $("#"+id+">.modal-dialog>.modal-content").css("border-radius",0);   
        }
        //Aply changes on screen resize (example: mobile orientation)
        window.onresize=function(){
            $("#"+id+">.modal-dialog>.modal-content>.modal-body").css("height","auto");
            h1=$("#"+id+">.modal-dialog").height();
            h2=$(window).height();
            h3=$("#"+id+">.modal-dialog>.modal-content>.modal-body").height();
            h4=h2-(h1-h3);
            if($(window).width()>=768){
                if(h1>h2){
                    $("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
                }
                $("#"+id+">.modal-dialog").css("margin","30px auto");
                $("#"+id+">.modal-dialog>.modal-content").css("border","1px solid rgba(0,0,0,0.2)");
                $("#"+id+">.modal-dialog>.modal-content").css("border-radius",6);               
                if($("#"+id+">.modal-dialog").height()+30>h2){
                    $("#"+id+">.modal-dialog").css("margin-top","0px");
                    $("#"+id+">.modal-dialog").css("margin-bottom","0px");
                }
            }
            else{
                //Fix full-screen in mobiles
                $("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
                $("#"+id+">.modal-dialog").css("margin",0);
                $("#"+id+">.modal-dialog>.modal-content").css("border",0);
                $("#"+id+">.modal-dialog>.modal-content").css("border-radius",0);   
            }
        };
    });  
    //Free event listener
    $('#'+id).on('hide.bs.modal',function(){
        window.onresize=function(){};
    });  
    //Mobile haven't scrollbar, so this is touch event scrollbar implementation
    var y1=0;
    var y2=0;
    var div=$("#"+id+">.modal-dialog>.modal-content>.modal-body")[0];
    div.addEventListener("touchstart",function(event){
        y1=event.touches[0].clientY;
    });
    div.addEventListener("touchmove",function(event){
        event.preventDefault();
        y2=event.touches[0].clientY;
        var limite=div.scrollHeight-div.clientHeight;
        var diff=div.scrollTop+y1-y2;
        if(diff<0)diff=0;
        if(diff>limite)diff=limite;
        div.scrollTop=diff;
        y1=y2;
    });
    //Fix position modal, scroll to top.    
    $('html, body').scrollTop(0);
    //Show
    $("#"+id).modal('show');
}

Storyboard doesn't contain a view controller with identifier

While entering the identifier u have not selected proper view controller, just check once if done repeat the procedure once more.

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

Android Device not recognized by adb

Go to prompt command and type "adb devices". If it is empty, then make sure you allowed for "MTP Transfer" or similar and you enabled debugging on your phone.

To enable debugging, follow this tutorial: https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm

Then type "adb devices" again. If a device is listed in there, then it should work now.

How can I quantify difference between two images?

General idea

Option 1: Load both images as arrays (scipy.misc.imread) and calculate an element-wise (pixel-by-pixel) difference. Calculate the norm of the difference.

Option 2: Load both images. Calculate some feature vector for each of them (like a histogram). Calculate distance between feature vectors rather than images.

However, there are some decisions to make first.

Questions

You should answer these questions first:

  • Are images of the same shape and dimension?

    If not, you may need to resize or crop them. PIL library will help to do it in Python.

    If they are taken with the same settings and the same device, they are probably the same.

  • Are images well-aligned?

    If not, you may want to run cross-correlation first, to find the best alignment first. SciPy has functions to do it.

    If the camera and the scene are still, the images are likely to be well-aligned.

  • Is exposure of the images always the same? (Is lightness/contrast the same?)

    If not, you may want to normalize images.

    But be careful, in some situations this may do more wrong than good. For example, a single bright pixel on a dark background will make the normalized image very different.

  • Is color information important?

    If you want to notice color changes, you will have a vector of color values per point, rather than a scalar value as in gray-scale image. You need more attention when writing such code.

  • Are there distinct edges in the image? Are they likely to move?

    If yes, you can apply edge detection algorithm first (e.g. calculate gradient with Sobel or Prewitt transform, apply some threshold), then compare edges on the first image to edges on the second.

  • Is there noise in the image?

    All sensors pollute the image with some amount of noise. Low-cost sensors have more noise. You may wish to apply some noise reduction before you compare images. Blur is the most simple (but not the best) approach here.

  • What kind of changes do you want to notice?

    This may affect the choice of norm to use for the difference between images.

    Consider using Manhattan norm (the sum of the absolute values) or zero norm (the number of elements not equal to zero) to measure how much the image has changed. The former will tell you how much the image is off, the latter will tell only how many pixels differ.

Example

I assume your images are well-aligned, the same size and shape, possibly with different exposure. For simplicity, I convert them to grayscale even if they are color (RGB) images.

You will need these imports:

import sys

from scipy.misc import imread
from scipy.linalg import norm
from scipy import sum, average

Main function, read two images, convert to grayscale, compare and print results:

def main():
    file1, file2 = sys.argv[1:1+2]
    # read images as 2D arrays (convert to grayscale for simplicity)
    img1 = to_grayscale(imread(file1).astype(float))
    img2 = to_grayscale(imread(file2).astype(float))
    # compare
    n_m, n_0 = compare_images(img1, img2)
    print "Manhattan norm:", n_m, "/ per pixel:", n_m/img1.size
    print "Zero norm:", n_0, "/ per pixel:", n_0*1.0/img1.size

How to compare. img1 and img2 are 2D SciPy arrays here:

def compare_images(img1, img2):
    # normalize to compensate for exposure difference, this may be unnecessary
    # consider disabling it
    img1 = normalize(img1)
    img2 = normalize(img2)
    # calculate the difference and its norms
    diff = img1 - img2  # elementwise for scipy arrays
    m_norm = sum(abs(diff))  # Manhattan norm
    z_norm = norm(diff.ravel(), 0)  # Zero norm
    return (m_norm, z_norm)

If the file is a color image, imread returns a 3D array, average RGB channels (the last array axis) to obtain intensity. No need to do it for grayscale images (e.g. .pgm):

def to_grayscale(arr):
    "If arr is a color image (3D array), convert it to grayscale (2D array)."
    if len(arr.shape) == 3:
        return average(arr, -1)  # average over the last axis (color channels)
    else:
        return arr

Normalization is trivial, you may choose to normalize to [0,1] instead of [0,255]. arr is a SciPy array here, so all operations are element-wise:

def normalize(arr):
    rng = arr.max()-arr.min()
    amin = arr.min()
    return (arr-amin)*255/rng

Run the main function:

if __name__ == "__main__":
    main()

Now you can put this all in a script and run against two images. If we compare image to itself, there is no difference:

$ python compare.py one.jpg one.jpg
Manhattan norm: 0.0 / per pixel: 0.0
Zero norm: 0 / per pixel: 0.0

If we blur the image and compare to the original, there is some difference:

$ python compare.py one.jpg one-blurred.jpg 
Manhattan norm: 92605183.67 / per pixel: 13.4210411116
Zero norm: 6900000 / per pixel: 1.0

P.S. Entire compare.py script.

Update: relevant techniques

As the question is about a video sequence, where frames are likely to be almost the same, and you look for something unusual, I'd like to mention some alternative approaches which may be relevant:

  • background subtraction and segmentation (to detect foreground objects)
  • sparse optical flow (to detect motion)
  • comparing histograms or some other statistics instead of images

I strongly recommend taking a look at “Learning OpenCV” book, Chapters 9 (Image parts and segmentation) and 10 (Tracking and motion). The former teaches to use Background subtraction method, the latter gives some info on optical flow methods. All methods are implemented in OpenCV library. If you use Python, I suggest to use OpenCV = 2.3, and its cv2 Python module.

The most simple version of the background subtraction:

  • learn the average value µ and standard deviation s for every pixel of the background
  • compare current pixel values to the range of (µ-2s,µ+2s) or (µ-s,µ+s)

More advanced versions make take into account time series for every pixel and handle non-static scenes (like moving trees or grass).

The idea of optical flow is to take two or more frames, and assign velocity vector to every pixel (dense optical flow) or to some of them (sparse optical flow). To estimate sparse optical flow, you may use Lucas-Kanade method (it is also implemented in OpenCV). Obviously, if there is a lot of flow (high average over max values of the velocity field), then something is moving in the frame, and subsequent images are more different.

Comparing histograms may help to detect sudden changes between consecutive frames. This approach was used in Courbon et al, 2010:

Similarity of consecutive frames. The distance between two consecutive frames is measured. If it is too high, it means that the second frame is corrupted and thus the image is eliminated. The Kullback–Leibler distance, or mutual entropy, on the histograms of the two frames:

$$ d(p,q) = \sum_i p(i) \log (p(i)/q(i)) $$

where p and q are the histograms of the frames is used. The threshold is fixed on 0.2.

Is there a <meta> tag to turn off caching in all browsers?

Try using

    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Expires" CONTENT="-1">

Simple C example of doing an HTTP POST and consuming the response

Handle added.
Added Host header.
Added linux / windows support, tested (XP,WIN7).
WARNING: ERROR : "segmentation fault" if no host,path or port as argument.

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#ifdef __linux__ 
    #include <sys/socket.h> /* socket, connect */
    #include <netdb.h> /* struct hostent, gethostbyname */
    #include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#elif _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <windows.h>
    #pragma comment(lib,"ws2_32.lib") //Winsock Library

#else

#endif

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{

    int i;
    struct hostent *server;
    struct sockaddr_in serv_addr;
    int bytes, sent, received, total, message_size;
    char *message, response[4096];
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";
    char *path = strlen(argv[4])>0?argv[4]:"/";
    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
                printf("Process 1\n");
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(path);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
                printf("Process 2\n");
        message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(path);                            /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }
            printf("Allocating...\n");
    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,                                          /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"",host);            /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,host);                                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            path,host);                                        /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }
    printf("Processed\n");
    /* What are we going to send? */
    printf("Request:\n%s\n",message);
        /* lookup the ip address */

    total = strlen(message);
    /* create the socket */
    #ifdef _WIN32
WSADATA wsa;
SOCKET s;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");

server = gethostbyname(host);
serv_addr.sin_addr.s_addr = inet_addr(server->h_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
//Connect to remote server
if (connect(s , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
{
    printf("connect failed with error code : %d" , WSAGetLastError());
    return 1;
}

puts("Connected");
if( send(s , message , strlen(message) , 0) < 0)
{
    printf("Send failed with error code : %d" , WSAGetLastError());
    return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if((received = recv(s , response , 2000 , 0)) == SOCKET_ERROR)
{
    printf("recv failed with error code : %d" , WSAGetLastError());
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
response[received] = '\0';
puts(response);

closesocket(s);
WSACleanup();
    #endif
    #ifdef __linux__ 
    int sockfd;
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) error("ERROR opening socket");
        /* fill in the structure */
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(portno);
        memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
                /* connect the socket */
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
            error("ERROR connecting");
                /* send the request */

    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);
    /* receive the response */
    memset(response, 0, sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    printf("Response: \n");
    do {
       printf("%s", response);
       memset(response, 0, sizeof(response));
       bytes = recv(sockfd, response, 1024, 0);
        if (bytes < 0)
           printf("ERROR reading response from socket");
       if (bytes == 0)
           break;
       received+=bytes;
    } while (1);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);
    #endif


    free(message);

    return 0;
}

Creating CSS Global Variables : Stylesheet theme management

It's not possible using CSS, but using a CSS preprocessor like less or SASS.

Relay access denied on sending mail, Other domain outside of network

Set your SMTP auth to true if using the PHPmailer class:

$mail->SMTPAuth = true;

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

How to easily resize/optimize an image size with iOS?

To resize an image I have better (graphical) results by using this function in stead of DrawInRect:

- (UIImage*) reduceImageSize:(UIImage*) pImage newwidth:(float) pWidth
{
    float lScale = pWidth / pImage.size.width;
    CGImageRef cgImage = pImage.CGImage;
    UIImage   *lResult = [UIImage imageWithCGImage:cgImage scale:lScale
                            orientation:UIImageOrientationRight];
    return lResult;
}

Aspect ratio is taken care for automatically

How to "pretty" format JSON output in Ruby on Rails

If you are using RABL you can configure it as described here to use JSON.pretty_generate:

class PrettyJson
  def self.dump(object)
    JSON.pretty_generate(object, {:indent => "  "})
  end
end

Rabl.configure do |config|
  ...
  config.json_engine = PrettyJson if Rails.env.development?
  ...
end

A problem with using JSON.pretty_generate is that JSON schema validators will no longer be happy with your datetime strings. You can fix those in your config/initializers/rabl_config.rb with:

ActiveSupport::TimeWithZone.class_eval do
  alias_method :orig_to_s, :to_s
  def to_s(format = :default)
    format == :default ? iso8601 : orig_to_s(format)
  end
end

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

To try to debug this error, first go to your android terminal / console and execute this command:

ps | grep THE_ERROR_PID_YOU_GET_(IT_IS_A_NUMBER)

then if the output comes out as your app... it is your app causing the error. Try to look for empty Strings that you pass into the layout.

I had this exact same problem and it was my fault as I was passing an empty String into my layout. After changing the "" to " " this error went away.

If you don't get your app from the console output, then it is something else causing it (probably, as others said, the android keyboard)