Programs & Examples On #Reverse lookup

Many programming languages feature data structures where unique indexes are associated with a value. Reverse lookup is retrieving the index with which a given value is accessed.

Using Python's list index() method on a list of tuples or objects?

I would place this as a comment to Triptych, but I can't comment yet due to lack of rating:

Using the enumerator method to match on sub-indices in a list of tuples. e.g.

li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'),
        ('aa','bb','cc','dd'), ('aaa','bbb','ccc','ddd')]

# want pos of item having [22,44] in positions 1 and 3:

def getIndexOfTupleWithIndices(li, indices, vals):

    # if index is a tuple of subindices to match against:
    for pos,k in enumerate(li):
        match = True
        for i in indices:
            if k[i] != vals[i]:
                match = False
                break;
        if (match):
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

idx = [1,3]
vals = [22,44]
print getIndexOfTupleWithIndices(li,idx,vals)    # = 1
idx = [0,1]
vals = ['a','b']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 3
idx = [2,1]
vals = ['cc','bb']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 4

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

Please note that adding the get_author function would slow the list_display in the admin, because showing each person would make a SQL query.

To avoid this, you need to modify get_queryset method in PersonAdmin, for example:

def get_queryset(self, request):
    return super(PersonAdmin,self).get_queryset(request).select_related('book')

Before: 73 queries in 36.02ms (67 duplicated queries in admin)

After: 6 queries in 10.81ms

Remove the last character in a string in T-SQL?

Get the last character

Right(@string, len(@String) - (len(@String) - 1))

CMD command to check connected USB devices

You can use the wmic command:

wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

What is the "-->" operator in C/C++?

while( x-- > 0 )

is how that's parsed.

How to find the nearest parent of a Git branch?

If you use Source Tree look at your commit details > Parents > then you'll see commit numbers underlined (links)

Rmi connection refused with localhost

It seems to work when I replace the

Runtime.getRuntime().exec("rmiregistry 2020");

by

LocateRegistry.createRegistry(2020);

anyone an idea why? What's the difference?

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

Old thread, but the question is still relevant, so...

(1) The example in your question now DOES work in Firefox. However in addition to calling the event handler (which displays an alert), it ALSO clicks on the link, causing navigation (once the alert is dismissed).

(2) To JUST call the event handler (without triggering navigation) merely replace:

document.getElementById('linkid').click();

with

document.getElementById('linkid').onclick();

Hot deploy on JBoss - how do I make JBoss "see" the change?

Start the server in debug mode and It will track changes inside methods. Other changes It will ask to restart the module.

SQLite UPSERT / UPDATE OR INSERT

The problem with all presented answers it complete lack of taking triggers (and probably other side effects) into account. Solution like

INSERT OR IGNORE ...
UPDATE ...

leads to both triggers executed (for insert and then for update) when row does not exist.

Proper solution is

UPDATE OR IGNORE ...
INSERT OR IGNORE ...

in that case only one statement is executed (when row exists or not).

Splitting string into multiple rows in Oracle

A couple of more examples of the same:

SELECT trim(regexp_substr('Err1, Err2, Err3', '[^,]+', 1, LEVEL)) str_2_tab
  FROM dual
CONNECT BY LEVEL <= regexp_count('Err1, Err2, Err3', ',')+1
/

SELECT trim(regexp_substr('Err1, Err2, Err3', '[^,]+', 1, LEVEL)) str_2_tab
  FROM dual
CONNECT BY LEVEL <= length('Err1, Err2, Err3') - length(REPLACE('Err1, Err2, Err3', ',', ''))+1
/

Also, may use DBMS_UTILITY.comma_to_table & table_to_comma: http://www.oracle-base.com/articles/9i/useful-procedures-and-functions-9i.php#DBMS_UTILITY.comma_to_table

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

What is the purpose of the word 'self'?

When objects are instantiated, the object itself is passed into the self parameter.

enter image description here

Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.

enter image description here

The Object is passed into the self parameter so that the object can keep hold of its own data.

Although this may not be wholly accurate, think of the process of instantiating an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as a general template and would not be referenced to (belong to) the object. So by passing the object's name into the self parameter it means that if 100 objects are instantiated from the one class, they can all keep track of their own data and methods.

See the illustration below:

enter image description here

login to remote using "mstsc /admin" with password

the command posted by Milad and Sandy did not work for me with mstsc. i had to add TERMSRV to the /generic switch. i found this information here: https://gist.github.com/jdforsythe/48a022ee22c8ec912b7e

cmdkey /generic:TERMSRV/<server> /user:<username> /pass:<password>

i could then use mstsc /v:<server> without getting prompted for the login.

How to replace a character from a String in SQL?

This will replace all ? with ':

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
WHERE city LIKE '%?%'

If you need to update more than one column, you can either change city each time you execute to a different column name, or list the columns like so:

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
      ,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'

Swift: declare an empty dictionary

Use this will work.

var emptyDict = [String: String]()

How to set the JDK Netbeans runs on?

It does not exactly answer your question, but to get around the problem,

  1. you can either create a .cmd file with following content:

    start netbeans --jdkhome c:\path\to\jdk

  2. or in the shortcut of Netbeans set the above option.

How to remove duplicate values from a multi-dimensional array in PHP

If "remove duplicates" means "remove duplicates, but let one there", a solution might be to apply the array_unique(...) on the "identifier column" first and then to remove in the original array all the keys, that have been removed from the column array:

$array = [
    [
        'id' => '123',
        'foo' => 'aaa',
        'bar' => 'bbb'
    ],
    [
        'id' => '123',
        'foo' => 'ccc',
        'bar' => 'ddd'
    ],
    [
        'id' => '567',
        'foo' => 'eee',
        'bar' => 'fff'
    ]
];

$ids = array_column($array, 'id');
$ids = array_unique($ids);
$array = array_filter($array, function ($key, $value) use ($ids) {
    return in_array($value, array_keys($ids));
}, ARRAY_FILTER_USE_BOTH);

The result is:

Array
(
    [0] => Array
        (
            [id] => 123
            [foo] => aaa
            [bar] => bbb
        )

    [2] => Array
        (
            [id] => 567
            [foo] => eee
            [bar] => fff
        )

)

Does Python SciPy need BLAS?

I guess you are talking about installation in Ubuntu. Just use:

apt-get install python-numpy python-scipy

That should take care of the BLAS libraries compiling as well. Else, compiling the BLAS libraries is very difficult.

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

The correct answer is the following:

import numpy 
numpy.shape(a)

Replace first occurrence of string in Python

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

Sublime text 3. How to edit multiple lines?

Select multiple lines by clicking first line then holding shift and clicking last line. Then press:

CTRL+SHIFT+L

or on MAC: CMD+SHIFT+L (as per comments)

Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.

Now you can edit multiple lines, move cursors etc. for all selected lines.

Remove element of a regular array

Not exactly the way to go about this, but if the situation is trivial and you value your time, you can try this for nullable types.

Foos[index] = null

and later check for null entries in your logic..

Remove a specific string from an array of string

You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.

You'd be better off with a List<String>, e.g. an ArrayList<String>:

List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3

list.remove("apple");
System.out.println(list.size()); // 2

Collections like this are generally much more flexible than working with arrays directly.

EDIT: For removal:

void removeRandomElement(List<?> list, Random random)
{
    int index = random.nextInt(list.size());
    list.remove(index);
}

Check if a string contains an element from a list (of strings)

There were a number of suggestions from an earlier similar question "Best way to test for existing string against a large list of comparables".

Regex might be sufficient for your requirement. The expression would be a concatenation of all the candidate substrings, with an OR "|" operator between them. Of course, you'll have to watch out for unescaped characters when building the expression, or a failure to compile it because of complexity or size limitations.

Another way to do this would be to construct a trie data structure to represent all the candidate substrings (this may somewhat duplicate what the regex matcher is doing). As you step through each character in the test string, you would create a new pointer to the root of the trie, and advance existing pointers to the appropriate child (if any). You get a match when any pointer reaches a leaf.

C# winforms combobox dynamic autocomplete

Take 2. My answer below didn't get me all the way to the desired result, but it may still be useful to somebody. The auto-select feature of the ComboBox was causing me major pain. This one uses a TextBox sitting over the top of a ComboBox, allowing me to ignore whatever appears in the ComboBox itself and just respond to the selection changed event.

  1. Create Form
  2. Add ComboBox
    • Set desired size and location
    • Set DropDownStyle to DropDown
    • Set TabStop to false
    • Set DisplayMember to Value (I'm using a list of KeyValuePairs)
    • Set ValueMember to Key
  3. Add Panel
    • Set to same size as ComboBox
    • Cover ComboBox with the Panel (This accounts for the standard ComboBox being taller than the standard TextBox)
  4. Add TextBox
    • Place TextBox over the top of the Panel
    • Align bottom of the TextBox with the bottom of Panel/ComboBox

Code behind

public partial class TestForm : Form
{
    // Custom class for managing calls to an external address finder service
    private readonly AddressFinder _addressFinder;

    // Events for handling async calls to address finder service
    private readonly AddressSuggestionsUpdatedEventHandler _addressSuggestionsUpdated;
    private delegate void AddressSuggestionsUpdatedEventHandler(object sender, AddressSuggestionsUpdatedEventArgs e);

    public TestForm()
    {
        InitializeComponent();

        _addressFinder = new AddressFinder(new AddressFinderConfigurationProvider());
        _addressSuggestionsUpdated += AddressSuggestions_Updated;
    }

    private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.Tab)
        {
            comboBox1_SelectionChangeCommitted(sender, e);
            comboBox1.DroppedDown = false;
        }
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Up)
        {
            if (comboBox1.Items.Count > 0)
            {
                if (comboBox1.SelectedIndex > 0)
                {
                    comboBox1.SelectedIndex--;
                }
            }

            e.Handled = true;
        }
        else if (e.KeyCode == Keys.Down)
        {
            if (comboBox1.Items.Count > 0)
            {
                if (comboBox1.SelectedIndex < comboBox1.Items.Count - 1)
                {
                    comboBox1.SelectedIndex++;
                }
            }

            e.Handled = true;
        }
        else if (e.KeyCode == Keys.Enter)
        {
            comboBox1_SelectionChangeCommitted(sender, e);
            comboBox1.DroppedDown = false;

            textBox1.SelectionStart = textBox1.TextLength;

            e.Handled = true;
        }
    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == '\r')  // Enter key
        {
            e.Handled = true;
            return;
        }

        if (char.IsControl(e.KeyChar) && e.KeyChar != '\b') // Backspace key
        {
            return;
        }

        if (textBox1.Text.Length > 1)
        {
            Task.Run(() => GetAddressSuggestions(textBox1.Text));
        }
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        if (comboBox1.Items.Count > 0 &&
            comboBox1.SelectedItem.IsNotNull() &&
            comboBox1.SelectedItem is KeyValuePair<string, string>)
        {
            var selectedItem = (KeyValuePair<string, string>)comboBox1.SelectedItem;

            textBox1.Text = selectedItem.Value;

            // Do Work with selectedItem
        }
    }

    private async Task GetAddressSuggestions(string searchString)
    {
        var addressSuggestions = await _addressFinder.CompleteAsync(searchString).ConfigureAwait(false);

        if (_addressSuggestionsUpdated.IsNotNull())
        {
            _addressSuggestionsUpdated.Invoke(this, new AddressSuggestionsUpdatedEventArgs(addressSuggestions));
        }
    }

    private void AddressSuggestions_Updated(object sender, AddressSuggestionsUpdatedEventArgs eventArgs)
    {
        try
        {
            ThreadingHelper.BeginUpdate(comboBox1);

            ThreadingHelper.ClearItems(comboBox1);

            if (eventArgs.AddressSuggestions.Count > 0)
            {
                foreach (var addressSuggestion in eventArgs.AddressSuggestions)
                {
                    var item = new KeyValuePair<string, string>(addressSuggestion.Key, addressSuggestion.Value.ToUpper());
                    ThreadingHelper.AddItem(comboBox1, item);
                }

                ThreadingHelper.SetDroppedDown(comboBox1, true);
                ThreadingHelper.SetVisible(comboBox1, true);
            }
            else
            {
                ThreadingHelper.SetDroppedDown(comboBox1, false);
            }
        }
        finally
        {
            ThreadingHelper.EndUpdate(comboBox1);
        }
    }

    private class AddressSuggestionsUpdatedEventArgs : EventArgs
    {
        public IList<KeyValuePair<string, string>> AddressSuggestions { get; }

        public AddressSuggestionsUpdatedEventArgs(IList<KeyValuePair<string, string>> addressSuggestions)
        {
            AddressSuggestions = addressSuggestions;
        }
    }
}

You may or may not have issues with setting the DroppedDown property of the ComboBox. I eventually just wrapped it up in a try block with an empty catch block. Not a great solution, but it works.

Please see my other answer below for info on ThreadingHelpers.

Enjoy.

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit.

I was getting this Error due to incorrect syntax using in the terminal. I was using java - version. But its actually is java -version. there is no space between - and version. you can also cross check by using java -help.

i hope this will help.

Replace transparency in PNG images with white background

I needed either: both -alpha background and -flatten, or -fill.

I made a new PNG with a transparent background and a red dot in the middle.

convert image.png -background green -alpha off green.png failed: it produced an image with black background

convert image.png -background green -alpha background -flatten green.png produced an image with the correct green background.

Of course, with another file that I renamed image.png, it failed to do anything. For that file, I found that the color of the transparent pixels was "#d5d5d5" so I filled that color with green:

convert image.png -fill green -opaque "#d5d5d5" green.png replaced the transparent pixels with the correct green.

How to scroll the window using JQuery $.scrollTo() function

Actually something like

function scrollTo(prop){
    $('html,body').animate({scrollTop: $("#"+prop).offset().top +
 parseInt($("#"+prop).css('padding-top'),10) },'slow');
}

will work nicely and support padding. You can also support margins easily - for completion see below

function scrollTo(prop){
    $('html,body').animate({scrollTop: $("#"+prop).offset().top 
+ parseInt($("#"+prop).css('padding-top'),10) 
+ parseInt($("#"+prop).css('margin-top'),10) +},'slow');
}

Does svn have a `revert-all` command?

You could do:

svn revert -R .

This will not delete any new file not under version control. But you can easily write a shell script to do that like:

for file in `svn status|grep "^ *?"|sed -e 's/^ *? *//'`; do rm $file ; done

Efficiently sorting a numpy array in descending order?

Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.

x=np.sort(array)
y=np.fliplr(x)

np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!

Hope it helps you out!

I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.

PYTHONPATH on Linux

PYTHONPATH is an environment variable those content is added to the sys.path where Python looks for modules. You can set it to whatever you like.

However, do not mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…

I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.

Regarding C++ Include another class

you need to forward declare the name of the class if you don't want a header:

class ClassTwo;

Important: This only works in some cases, see Als's answer for more information..

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.

How do I open an .exe from another C++ .exe?

Provide the full path of the file openfile.exe and remember not to put forward slash / in the path such as c:/users/username/etc.... instead of that use c:\\Users\\username\etc (for windows)

May be this will help you.

Windows command prompt log to a file

You can redirect the output of a cmd prompt to a file using > or >> to append to a file.

i.e.

echo Hello World >C:\output.txt
echo Hello again! >>C:\output.txt

or

mybatchfile.bat >C:\output.txt

Note that using > will automatically overwrite the file if it already exists.

You also have the option of redirecting stdin, stdout and stderr.

See here for a complete list of options.

check if variable is dataframe

Use the built-in isinstance() function.

import pandas as pd

def f(var):
    if isinstance(var, pd.DataFrame):
        print("do stuff")

Make a simple fade in animation in Swift?

If you want repeatable fade animation you can do that by using CABasicAnimation like below :

First create handy UIView extension :

extension UIView {

    enum AnimationKeyPath: String {
        case opacity = "opacity"
    }

    func flash(animation: AnimationKeyPath ,withDuration duration: TimeInterval = 0.5, repeatCount: Float = 5){
        let flash = CABasicAnimation(keyPath: animation.rawValue)
        flash.duration = duration
        flash.fromValue = 1 // alpha
        flash.toValue = 0 // alpha
        flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        flash.autoreverses = true
        flash.repeatCount = repeatCount

        layer.add(flash, forKey: nil)
    }
}

How to use it:

    // You can use it with all kind of UIViews e.g. UIButton, UILabel, UIImage, UIImageView, ...
    imageView.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
    titleLabel.flash(animation: .opacity, withDuration: 1, repeatCount: 5)

How to set 24-hours format for date on java?

Try this...

Calendar calendar = Calendar.getInstance();
String currentDate24Hrs = (String) DateFormat.format(
            "MM/dd/yyyy kk:mm:ss", calendar.getTime());
Log.i("DEBUG_TAG", "24Hrs format date: " + currentDate24Hrs);

How to create CSV Excel file C#?

If anyone would like I converted this to an extension method on IEnumerable:

public static class ListExtensions
{
    public static string ExportAsCSV<T>(this IEnumerable<T> listToExport, bool includeHeaderLine, string delimeter)
    {
        StringBuilder sb = new StringBuilder();

        IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();

        if (includeHeaderLine)
        {
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                sb.Append(propertyInfo.Name).Append(",");
            }
            sb.Remove(sb.Length - 1, 1).AppendLine();
        }

        foreach (T obj in listToExport)
        {
            T localObject = obj;

            var line = String.Join(delimeter, propertyInfos.Select(x => SanitizeValuesForCSV(x.GetValue(localObject, null), delimeter)));

            sb.AppendLine(line);
        }

        return sb.ToString();
    }

    private static string SanitizeValuesForCSV(object value, string delimeter)
    {
        string output;

        if (value == null) return "";

        if (value is DateTime)
        {
            output = ((DateTime)value).ToLongDateString();
        }
        else
        {
            output = value.ToString();                
        }

        if (output.Contains(delimeter) || output.Contains("\""))
            output = '"' + output.Replace("\"", "\"\"") + '"';

        output = output.Replace("\n", " ");
        output = output.Replace("\r", "");

        return output;
    }
}

List of IP addresses/hostnames from local network in Python

If by "local" you mean on the same network segment, then you have to perform the following steps:

  1. Determine your own IP address
  2. Determine your own netmask
  3. Determine the network range
  4. Scan all the addresses (except the lowest, which is your network address and the highest, which is your broadcast address).
  5. Use your DNS's reverse lookup to determine the hostname for IP addresses which respond to your scan.

Or you can just let Python execute nmap externally and pipe the results back into your program.

rand() returns the same number each time the program is run

You need to "seed" the generator. Check out this short video, it will clear things up.

https://www.thenewboston.com/videos.php?cat=16&video=17503

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

What is the difference between pull and clone in git?

git clone means you are making a copy of the repository in your system.

git fork means you are copying the repository to your Github account.

git pull means you are fetching the last modified repository.

git push means you are returning the repository after modifying it.

In layman's term:

git clone is downloading and git pull is refreshing.

Parsing jQuery AJAX response

calling

var parsed_data = JSON.parse(data);

should result in the ability to access the data like you want.

console.log(parsed_data.success);

should now show '1'

How to do SVN Update on my project using the command line

If you want to update your project using SVN then first of all:

  1. Go to the path on which your project is stored through command prompt.

  2. Use the command SVN update

That's it.

How can I write an anonymous function in Java?

Anonymous inner classes implementing or extending the interface of an existing type has been done in other answers, although it is worth noting that multiple methods can be implemented (often with JavaBean-style events, for instance).

A little recognised feature is that although anonymous inner classes don't have a name, they do have a type. New methods can be added to the interface. These methods can only be invoked in limited cases. Chiefly directly on the new expression itself and within the class (including instance initialisers). It might confuse beginners, but it can be "interesting" for recursion.

private static String pretty(Node node) {
    return "Node: " + new Object() {
        String print(Node cur) {
            return cur.isTerminal() ?
                cur.name() :
                ("("+print(cur.left())+":"+print(cur.right())+")");
        }
    }.print(node);
}

(I originally wrote this using node rather than cur in the print method. Say NO to capturing "implicitly final" locals?)

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

In my case I was deploying my webapp inside a docker: I was setting

ENV AWS_ACCESS_KEY_ID=blahblah%&/(
ENV AWS_SECRET_ACCESS_KEY=supersecret%&/(

but I still got errors, I got fixed this by adding

cloud.aws.credentials.useDefaultAwsCredentialsChain=true

inside application.properties

Unable to create Genymotion Virtual Device

Disadvantage of deleting the deployed and .ova files is obvious i.e. you have to download the massive 200mb image again. A better choice is to :

  • Open genymotion and open settings --> virtualBox --> virtual devices browse and set the path to a folder which can be completely accessed without administrative pivileges e.g. for ubuntu set virtual devices path to any folder in your home directory for example /home/user/deployed and for windows you can use a folder like C://deployed.

That's it . Now you can use your already existing .ova file again to deploy image to new locatioin without any problem.

Easier way to debug a Windows service

Here is the simple method which I used to test the service, without any additional "Debug" methods and with integrated VS Unit Tests.

[TestMethod]
public void TestMyService()
{
    MyService fs = new MyService();

    var OnStart = fs.GetType().BaseType.GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

    OnStart.Invoke(fs, new object[] { null });
}

// As an extension method
public static void Start(this ServiceBase service, List<string> parameters)
{
     string[] par = parameters == null ? null : parameters.ToArray();

     var OnStart = service.GetType().GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

     OnStart.Invoke(service, new object[] { par });
}

Aborting a stash pop in Git

Try using if tracked file.

git rm <path to file>
git reset  <path to file>
git checkout <path to file>

Powershell get ipv4 address into a variable

Here is what I ended up using

$ipaddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])

which breaks down as

  • execute ipconfig command - get all the network interface information
  • use powershell's where filter with a regular expression
  • regular expression finds the line with "IPv4" and a set of 4 blocks each with 1-3 digits separated by periods, i.e. a v4 IP address
  • disregard the output by piping it to null
  • finally get the first matched group as defined by the brackets in the regular expression.
  • catch that output in $ipaddress for later use.

Print Html template in Angular 2 (ng-print in Angular 2)

That's how I've done it in angular2 (it is similar to that plunkered solution) In your HTML file:

<div id="print-section">
  // your html stuff that you want to print
</div>
<button (click)="print()">print</button>

and in your TS file :

print(): void {
    let printContents, popupWin;
    printContents = document.getElementById('print-section').innerHTML;
    popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    popupWin.document.open();
    popupWin.document.write(`
      <html>
        <head>
          <title>Print tab</title>
          <style>
          //........Customized style.......
          </style>
        </head>
    <body onload="window.print();window.close()">${printContents}</body>
      </html>`
    );
    popupWin.document.close();
}

UPDATE:

You can also shortcut the path and use merely ngx-print library for less inconsistent coding (mixing JS and TS) and more out-of-the-box controllable and secured printing cases.

array.select() in javascript

Underscore.js is a good library for these sorts of operations - it uses the builtin routines such as Array.filter if available, or uses its own if not.

http://documentcloud.github.com/underscore/

The docs will give an idea of use - the javascript lambda syntax is nowhere near as succinct as ruby or others (I always forget to add an explicit return statement for example) and scope is another easy way to get caught out, but you can do most things quite easily with the exception of constructs such as lazy list comprehensions.

From the docs for .select() (.filter() is an alias for the same)

Looks through each value in the list, returning an array of all the values that pass a truth test (iterator). Delegates to the native filter method, if it exists.

  var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  => [2, 4, 6]

Define global variable with webpack

There are several way to approach globals:

  1. Put your variables in a module.

Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js and export an object of all your globals then you can import './globals' and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js. Then it will execute entry.js. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?

config.js

export default {
    FOO: 'bar'
}

somefile.js

import CONFIG from './config.js'
console.log(`FOO: ${CONFIG.FOO}`)

Note: If you want the instance to be new each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()

  1. Webpack's ProvidePlugin

Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo' again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).

Step 1) Create any module. For example, a global set of utilities would be handy:

utils.js

export function sayHello () {
  console.log('hello')
}

Step 2) Alias the module and add to ProvidePlugin:

webpack.config.js

var webpack = require("webpack");
var path = require("path");

// ...

module.exports = {

  // ...

  resolve: {
    extensions: ['', '.js'],
    alias: {
      'utils': path.resolve(__dirname, './utils')  // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
    }
  },

  plugins: [

    // ...

    new webpack.ProvidePlugin({
      'utils': 'utils'
    })
  ]  

}

Now just call utils.sayHello() in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.

Note: Don't forget to tell your linter about the global, so it won't complain. For example, see my answer for ESLint here.

  1. Use Webpack's DefinePlugin

If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:

new webpack.DefinePlugin({
  PRODUCTION: JSON.stringify(true),
  VERSION: JSON.stringify("5fa3b9"),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: "1+1",
  "typeof window": JSON.stringify("object")
})

Use it like:

console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");
  1. Use the global window object (or Node's global)

window.foo = 'bar'  // For SPA's, browser environment.
global.foo = 'bar'  // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/

You'll see this commonly used for polyfills, for example: window.Promise = Bluebird

  1. Use a package like dotenv

(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.

// As early as possible in your application, require and configure dotenv.    
require('dotenv').config()

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

That's it.

process.env now has the keys and values you defined in your .env file.

var db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

Notes:

Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).

UEFA/FIFA scores API

http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.

Counting Number of Letters in a string variable

What is wrong with using string.Length?

// len will be 5
int len = "Hello".Length;

How to pause a vbscript execution?

Script snip below creates a pause sub that displayes the pause text in a string and waits for the Enter key. z can be anything. Great if multilple user intervention required pauses are needed. I just keep it in my standard script template.

Pause("Press Enter to continue")

Sub Pause(strPause)
     WScript.Echo (strPause)
     z = WScript.StdIn.Read(1)
End Sub

Use jQuery to hide a DIV when the user clicks outside of it

Updated the solution to:

  • use mouseenter and mouseleave instead
  • of hover use live event binding

var mouseOverActiveElement = false;

$('.active').live('mouseenter', function(){
    mouseOverActiveElement = true; 
}).live('mouseleave', function(){ 
    mouseOverActiveElement = false; 
});
$("html").click(function(){ 
    if (!mouseOverActiveElement) {
        console.log('clicked outside active element');
    }
});

Stop Visual Studio from mixing line endings in files

In Visual Studio 2015 (this still holds in 2019 for the same value), check the setting:

Tools > Options > Environment > Documents > Check for consistent line endings on load

VS2015 will now prompt you to convert line endings when you open a file where they are inconsistent, so all you need to do is open the files, select the desired option from the prompt and save them again.

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

Rails: How to list database tables/objects using the Rails console?

Run this:

Rails.application.eager_load! 

Then

ActiveRecord::Base.descendants

To return a list of models/tables

writing integer values to a file using out.write()

i = Your_int_value

Write bytes value like this for example:

the_file.write(i.to_bytes(2,"little"))

Depend of you int value size and the bit order your prefer

How do you turn a Mongoose document into a plain object?

Another way to do this is to tell Mongoose that all you need is a plain JavaScript version of the returned doc by using lean() in the query chain. That way Mongoose skips the step of creating the full model instance and you directly get a doc you can modify:

MyModel.findOne().lean().exec(function(err, doc) {
    doc.addedProperty = 'foobar';
    res.json(doc);
});

Print page numbers on pages when printing html

   **@page {
            margin-top:21% !important; 
            @top-left{
            content: element(header);

            }

            @bottom-left {
            content: element(footer
 }
 div.header {

            position: running(header);

            }
            div.footer {

            position: running(footer);
            border-bottom: 2px solid black;


            }
           .pagenumber:before {
            content: counter(page);
            }
            .pagecount:before {
            content: counter(pages);
            }      
 <div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
                <span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
            </div >**

composer laravel create project

No this step isn't equal to downloading the laravel.zip by using the command composer create-project laravel/laravel laravel you actually download the laravel project as well as dependent packages so its one step ahead.

If you are using windows environment you can solve the problem by deleting the composer environment variable you created to install the composer. And this command will run properly.

How can I get stock quotes using Google Finance API?

The Google stock quote API has gone away. However, Investor's Exchange offers an API that's very easy to use for quote data.

Laravel Mail::send() sending to multiple to or bcc addresses

I've tested it using the following code:

$emails = ['[email protected]', '[email protected]','[email protected]'];

Mail::send('emails.welcome', [], function($message) use ($emails)
{    
    $message->to($emails)->subject('This is test e-mail');    
});
var_dump( Mail:: failures());
exit;

Result - empty array for failures.

But of course you need to configure your app/config/mail.php properly. So first make sure you can send e-mail just to one user and then test your code with many users.

Moreover using this simple code none of my e-mails were delivered to free mail accounts, I got only emails to inboxes that I have on my paid hosting accounts, so probably they were caught by some filters (it's maybe simple topic/content issue but I mentioned it just in case you haven't received some of e-mails) .

Creating a mock HttpServletRequest out of a url string?

Spring has MockHttpServletRequest in its spring-test module.

If you are using maven you may need to add the appropriate dependency to your pom.xml. You can find spring-test at mvnrepository.com.

Read MS Exchange email in C#

It's a mess. MAPI or CDO via a .NET interop DLL is officially unsupported by Microsoft--it will appear to work fine, but there are problems with memory leaks due to their differing memory models. You could use CDOEX, but that only works on the Exchange server itself, not remotely; useless. You could interop with Outlook, but now you've just made a dependency on Outlook; overkill. Finally, you could use Exchange 2003's WebDAV support, but WebDAV is complicated, .NET has poor built-in support for it, and (to add insult to injury) Exchange 2007 nearly completely drops WebDAV support.

What's a guy to do? I ended up using AfterLogic's IMAP component to communicate with my Exchange 2003 server via IMAP, and this ended up working very well. (I normally seek out free or open-source libraries, but I found all of the .NET ones wanting--especially when it comes to some of the quirks of 2003's IMAP implementation--and this one was cheap enough and worked on the first try. I know there are others out there.)

If your organization is on Exchange 2007, however, you're in luck. Exchange 2007 comes with a SOAP-based Web service interface that finally provides a unified, language-independent way of interacting with the Exchange server. If you can make 2007+ a requirement, this is definitely the way to go. (Sadly for me, my company has a "but 2003 isn't broken" policy.)

If you need to bridge both Exchange 2003 and 2007, IMAP or POP3 is definitely the way to go.

How to show current user name in a cell?

The simplest way is to create a VBA macro that wraps that function, like so:

Function UserNameWindows() As String
    UserName = Environ("USERNAME")
End Function

Then call it from the cell:

=UserNameWindows()

See this article for more details, and other ways.

iFrame Height Auto (CSS)

According to this post

You need to add the !important css modifier to your height percentages.

Hope this helps.

Excel to JSON javascript code?

@Kwang-Chun Kang Thanks Kang a lot! I found the solution is working and very helpful, it really save my day. For me I am trying to create a React.js component that convert *.xlsx to json object when user upload the excel file to a html input tag. First I need to install XLSX package with:

npm install xlsx --save

Then in my component code, import with:

import XLSX from 'xlsx'

The component UI should look like this:

<input
  accept=".xlsx"
  type="file"
  onChange={this.fileReader}
/>

It calls a function fileReader(), which is exactly same as the solution provided. To learn more about fileReader API, I found this blog to be helpful: https://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

Setting Environment Variables for Node to retrieve

I highly recommend looking into the dotenv package.

https://github.com/motdotla/dotenv

It's kind of similar to the library suggested within the answer from @Benxamin, but it's a lot cleaner and doesn't require any bash scripts. Also worth noting that the code base is popular and well maintained.

Basically you need a .env file (which I highly recommend be ignored from your git/mercurial/etc):

FOO=bar
BAZ=bob

Then in your application entry file put the following line in as early as possible:

require('dotenv').config();

Boom. Done. 'process.env' will now contain the variables above:

console.log(process.env.FOO);
// bar

The '.env' file isn't required so you don't need to worry about your app falling over in it's absence.

What is the difference between Class.getResource() and ClassLoader.getResource()?

All these answers around here, as well as the answers in this question, suggest that loading absolute URLs, like "/foo/bar.properties" treated the same by class.getResourceAsStream(String) and class.getClassLoader().getResourceAsStream(String). This is NOT the case, at least not in my Tomcat configuration/version (currently 7.0.40).

MyClass.class.getResourceAsStream("/foo/bar.properties"); // works!  
MyClass.class.getClassLoader().getResourceAsStream("/foo/bar.properties"); // does NOT work!

Sorry, I have absolutely no satisfying explanation, but I guess that tomcat does dirty tricks and his black magic with the classloaders and cause the difference. I always used class.getResourceAsStream(String) in the past and haven't had any problems.

PS: I also posted this over here

Custom style to jquery ui dialogs

You can specify a custom class to the top element of the dialog via the option dialogClass

$("#success").dialog({
    ...
    dialogClass:"myClass",
    ...
});

Then you can target this class in CSS via .myClass.ui-dialog.

how to get the current working directory's absolute path from irb

File.expand_path File.dirname(__FILE__) will return the directory relative to the file this command is called from.

But Dir.pwd returns the working directory (results identical to executing pwd in your terminal)

Is div inside list allowed?

If you look at xhtml1-strict.dtd, you'll see

<!ELEMENT li %Flow;>
<!ENTITY % Flow "(#PCDATA | %block; | form | %inline; | %misc;)*">
<!ENTITY % block
     "p | %heading; | div | %lists; | %blocktext; | fieldset | table">

Thus div, p etc. can be inside li (according to XHTML 1.0 Strict DTD from w3.org).

How to view kafka message

On server where your admin run kafka find kafka-console-consumer.sh by command find . -name kafka-console-consumer.sh then go to that directory and run for read message from your topic

./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning --max-messages 10

note that in topic may be many messages in that case I use --max-messages key

Select mySQL based only on month and year

Yeah this is working, but it returns one row only while there is several rows to retrieve using selected columns only. Like SELECT Title,Date FROM mytable WHERE YEAR(Date)=2017 AND MONTH(Date)=09 returns only one row.

How do I mock a service that returns promise in AngularJS Jasmine unit test?

We can also write jasmine's implementation of returning promise directly by spy.

spyOn(myOtherService, "makeRemoteCallReturningPromise").andReturn($q.when({}));

For Jasmine 2:

spyOn(myOtherService, "makeRemoteCallReturningPromise").and.returnValue($q.when({}));

(copied from comments, thanks to ccnokes)

How to download a file from my server using SSH (using PuTTY on Windows)

You can use the WinSPC program. Its access to any server is pretty easy. The program gives its guide too. I hope it's helpfull.

R - argument is of length zero in if statement

I spent an entire day bashing my head against this, the solution turned out to be simple..

R isn't zero-index.

Every programming language that I've used before has it's data start at 0, R starts at 1. The result is an off-by-one error but in the opposite direction of the usual. going out of bounds on a data structure returns null and comparing null in an if statement gives the argument is of length zero error. The confusion started because the dataset doesn't contain any null, and starting at position [0] like any other pgramming language turned out to be out of bounds.

Perhaps starting at 1 makes more sense to people with no programming experience (the target market for R?) but for a programmer is a real head scratcher if you're unaware of this.

"unary operator expected" error in Bash if condition

Try assigning a value to $aug1 before use it in if[] statements; the error message will disappear afterwards.

npm command to uninstall or prune unused packages in Node.js

If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules and npm install again to rebuild the local modules.

ASP.NET Core Get Json Array using IConfiguration

In ASP.NET Core 2.2 and later we can inject IConfiguration anywhere in our application like in your case, you can inject IConfiguration in HomeController and use like this to get the array.

string[] array = _config.GetSection("MyArray").Get<string[]>();

How does lock work exactly?

The lock statement is translated to calls to the Enter and Exit methods of Monitor.

The lock statement will wait indefinitely for the locking object to be released.

PHP output showing little black diamonds with a question mark

Go to your phpmyadmin and select your database and just increase the length/value of that table's field to 500 or 1000 it will solve your problem.

Prevent Default on Form Submit jQuery

Hello sought a solution to make an Ajax form work with Google Tag Manager (GTM), the return false prevented the completion and submit the activation of the event in real time on google analytics solution was to change the return false by e.preventDefault (); that worked correctly follows the code:

 $("#Contact-Form").submit(function(e) {
    e.preventDefault();
   ...
});

How to scroll to the bottom of a UITableView on the iPhone before the view appears

In iOS this worked fine for me

CGFloat height = self.inputTableView.contentSize.height;
if (height > CGRectGetHeight(self.inputTableView.frame)) {
    height -= (CGRectGetHeight(self.inputTableView.frame) - CGRectGetHeight(self.navigationController.navigationBar.frame));
}
else {
    height = 0;
}
[self.inputTableView setContentOffset:CGPointMake(0, height) animated:animated];

It needs to be called from viewDidLayoutSubviews

window.print() not working in IE

add checking condition for onload

if (newWinObj.onload) {
    newWinObj.onload = function() {
        newWinObj.print();
        newWinObj.close();
    };
}
else {
    newWinObj.print();
    newWinObj.close();
}

What is sr-only in Bootstrap 3?

.sr-only is a class name specifically used for screen readers. You can use any class name, but .sr-only is pretty commonly used. If you don't care about developing with compliance in mind, then it can be removed. It will not affect UI in any way if removed because the CSS for this class is not visible to desktop and mobile device browsers.

There seems to be some information missing here about the use of .sr-only to explain its purpose and being for screen readers. First and foremost, it is very important to always keep impaired users in mind. Impairment is the purpose of 508 compliance: https://www.section508.gov/, and it is great that bootstrap takes this into consideration. However, the use of .sr-only is not all that needs to be taken into consideration for 508 compliance. You have the use of color, size of fonts, accessibility via navigation, descriptors, use of aria and so much more.

But as for .sr-only - what does the CSS actually do? There are several slightly different variants of the CSS used for .sr-only. One of the few I use is below:

.sr-only {
    position: absolute;
    margin: -1px 0 0 -1px;
    padding: 0;
    display: block;
    width: 1px;
    height: 1px;
    font-size: 1px;
    line-height: 1px;
    overflow: hidden;
    clip: rect(0,0,0,0);
    border: 0;
    outline: 0;
    }

The above CSS hides content in desktop and mobile browsers wrapped with this class, but is seen by a screen reader like JAWS: http://www.freedomscientific.com/Products/Blindness/JAWS. Example markup is as follows:

<a href="#" target="_blank">
    Click to Open Site
    <span class="sr-only">This is an external link</span>
</a>

Additionally, if a DOM element has a width and height of 0, the element is not seen by the DOM. This is why the above CSS uses width: 1px; height: 1px;. By using display: none and setting your CSS to height: 0 and width: 0, the element is not seen by the DOM and is thus problematic. The above CSS using width: 1px; height: 1px; is not all you do to make the content invisible to desktop and mobile browsers (without overflow: hidden, your content would still show on the screen), and visible to screen readers. Hiding the content from desktop and mobile browsers is done by adding an offset from width: 1px and height: 1px previously mentioned by using:

position: absolute;
margin: -1px 0 0 -1px; 
overflow: hidden;

Lastly, to have a very good idea of what a screen reader sees and relays to its impaired user, turn off page styling for your browser. For Firefox, you can do this by going to:

View > Page Style > No Style

I hope the information I provided here is of further use to someone in addition to the other responses.

How do I add the Java API documentation to Eclipse?

  1. Go to your JDK installation. (C:\Program Files\Java\jdk1.8.0_66 for me).

  2. Unzip the src.zip file (becomes C:\Program Files\Java\jdk1.8.0_66\src\ for me).

  3. In the Eclipse editor window: CTRL + Click on a java.lang library class. (something like String).

  4. Eclipse will complain Source not found and tell you that you don't have the source.

  5. Click Attach source -> External Location -> External Folder.

  6. Find your source folder (C:\Program Files\Java\jdk1.8.0_66\src\ for me).

  7. Click OK -> OK.

  8. Enjoy.

Write a function that returns the longest palindrome in a given string

_x000D_
_x000D_
#longest palindrome_x000D_
s='HYTBCABADEFGHABCDEDCBAGHTFYW123456789987654321ZWETYGDE'_x000D_
out1=[]_x000D_
def substring(x):_x000D_
    for i in range(len(x)):_x000D_
        a=x[i:]_x000D_
        b=x[:-i]_x000D_
        out1.append(a)_x000D_
        out1.append(b)_x000D_
        _x000D_
    return out1_x000D_
_x000D_
for i in range(len(s)):_x000D_
    substring(s[i:])    _x000D_
final=set([item for item in out1 if len(item)>2])_x000D_
final_x000D_
palind={item:len(item) for item in final if item==item[::-1]}_x000D_
print(palind)_x000D_
sorted(palind.items(),reverse=True, key=lambda x: x[1])[0]
_x000D_
_x000D_
_x000D_

{'DED': 3, '123456789987654321': 18, '67899876': 8, 'ABCDEDCBA': 9, '456789987654': 12, '34567899876543': 14, 'BCDEDCB': 7, 'ABA': 3, '5678998765': 10, '2345678998765432': 16, 'CDEDC': 5, '789987': 6, '8998': 4} ('123456789987654321', 18)

Read only the first line of a file?

fline=open("myfile").readline().rstrip()

Didn't Java once have a Pair class?

If you want a pair (not supposedly key-value pair) just to hold two generic data together neither of the solutions above really handy since first (or so called Key) cannot be changed (neither in Apache Commons Lang's Pair nor in AbstractMap.SimpleEntry). They have thier own reasons, but still you may need to be able to change both of the components. Here is a Pair class in which both elements can be set

public class Pair<First, Second> {
    private First first;
    private Second second;

    public Pair(First first, Second second) {
        this.first = first;
        this.second = second;
    }

    public void setFirst(First first) {
        this.first = first;
    }

    public void setSecond(Second second) {
        this.second = second;
    }

    public First getFirst() {
        return first;
    }

    public Second getSecond() {
        return second;
    }

    public void set(First first, Second second) {
        setFirst(first);
        setSecond(second);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Pair pair = (Pair) o;

        if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
        if (second != null ? !second.equals(pair.second) : pair.second != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = first != null ? first.hashCode() : 0;
        result = 31 * result + (second != null ? second.hashCode() : 0);
        return result;
    }
}

How do I merge my local uncommitted changes into another Git branch?

Stashing, temporary commits and rebasing may all be overkill. If you haven't added the changed files to the index, yet, then you may be able to just checkout the other branch.

git checkout branch2

This will work so long as no files that you are editing are different between branch1 and branch2. It will leave you on branch2 with you working changes preserved. If they are different then you can specify that you want to merge your local changes with the changes introduced by switching branches with the -m option to checkout.

git checkout -m branch2

If you've added changes to the index then you'll want to undo these changes with a reset first. (This will preserve your working copy, it will just remove the staged changes.)

git reset

MySQL Update Column +1?

How about:

update table
set columnname = columnname + 1
where id = <some id>

how to remove "," from a string in javascript

If U want to delete more than one characters, say comma and dots you can write

<script type="text/javascript">
  var mystring = "It,is,a,test.string,of.mine" 
  mystring = mystring.replace(/[,.]/g , ''); 
  alert( mystring);
</script>

How do I populate a JComboBox with an ArrayList?

Use the toArray() method of the ArrayList class and pass it into the constructor of the JComboBox

See the JavaDoc and tutorial for more info.

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

How to get a list of all valid IP addresses in a local network?

Try following steps:

  1. Type ipconfig (or ifconfig on Linux) at command prompt. This will give you the IP address of your own machine. For example, your machine's IP address is 192.168.1.6. So your broadcast IP address is 192.168.1.255.
  2. Ping your broadcast IP address ping 192.168.1.255 (may require -b on Linux)
  3. Now type arp -a. You will get the list of all IP addresses on your segment.

How to set dropdown arrow in spinner?

copy and paste this xml instead of your xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back1"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp" 
        android:background="@drawable/red">

        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dropDownWidth="fill_parent" 
            android:background="@android:drawable/btn_dropdown"
         />

    </LinearLayout>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignLeft="@+id/linearLayout1"
        android:layout_alignRight="@+id/linearLayout1"
        android:layout_below="@+id/linearLayout1"
        android:layout_marginTop="25dp"
        android:background="@drawable/red"
        android:ems="10"
        android:hint="enter card number" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignLeft="@+id/editText1"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="33dp"
        android:orientation="horizontal" 
        android:background="@drawable/red">

        <Spinner
            android:id="@+id/spinner3"
            android:layout_width="72dp"
            android:layout_height="wrap_content"
            android:background="@android:drawable/btn_dropdown"
             />

        <Spinner
            android:id="@+id/spinner2"
            android:layout_width="72dp"
            android:layout_height="wrap_content" 
            android:background="@android:drawable/btn_dropdown"
            />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="22dp"
            android:layout_height="match_parent"
            android:layout_weight="0.18"
            android:ems="10"
            android:hint="enter cvv" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/linearLayout2"
        android:layout_below="@+id/linearLayout2"
        android:layout_marginTop="26dp"
        android:orientation="vertical"
        android:background="@drawable/red" >
    </LinearLayout>

    <Spinner
        android:id="@+id/spinner4"
        android:layout_width="15dp"
        android:layout_height="18dp"
        android:layout_alignBottom="@+id/linearLayout3"
        android:layout_alignLeft="@+id/linearLayout3"
        android:layout_alignRight="@+id/linearLayout3"
        android:layout_alignTop="@+id/linearLayout3"
        android:background="@android:drawable/btn_dropdown"
      />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/linearLayout3"
        android:layout_marginTop="18dp"
        android:text="Add Amount" 
        android:background="@drawable/buttonsty"/>
</RelativeLayout>

Casting an int to a string in Python

You can use str() to cast it, or formatters:

"ME%d.txt" % (num,)

Removing an activity from the history stack

One way that works pre API 11 is to start ActivityGameMain first, then in the onCreate of that Activity start your ActivitySplashScreen activity. The ActivityGameMain won't appear as you call startActivity too soon for the splash.

Then you can clear the stack when starting ActivityGameMain by setting these flags on the Intent:

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

You also must add this to ActivitySplashScreen:

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

So that pressing back on that activity doesn't go back to your ActivityGameMain.

I assume you don't want the splash screen to be gone back to either, to achieve this I suggest setting it to noHistory in your AndroidManifest.xml. Then put the goBackPressed code in your ActivitySplashScreenSignUp class instead.

However I have found a few ways to break this. Start another app from a notification while ActivitySplashScreenSignUp is shown and the back history is not reset.

The only real way around this is in API 11:

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

Can a for loop increment/decrement by more than one?

for (var i = 0; i < myVar.length; i+=3) {
   //every three
}

additional

Operator   Example    Same As
  ++       X ++        x = x + 1
  --       X --        x = x - 1
  +=       x += y      x = x + y
  -=       x -= y      x = x - y
  *=       x *= y      x = x * y
  /=       x /= y      x = x / y
  %=       x %= y      x = x % y

Create pandas Dataframe by appending one row at a time

This will take care of adding an item to an empty DataFrame. The issue is that df.index.max() == nan for the first index:

df = pd.DataFrame(columns=['timeMS', 'accelX', 'accelY', 'accelZ', 'gyroX', 'gyroY', 'gyroZ'])

df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = [x for x in range(7)]

How to call a function after a div is ready?

inside your <div></div> element you can call the $(document).ready(function(){}); execute a command, something like

<div id="div1">
    <script>
        $(document).ready(function(){
         //do something
        });
    </script>
</div>

and you can do the same to other divs that you have. this was suitable if you loading your div via partial view

Draw a line in a div

No need for css, you can just use the HR tag from HTML

<hr />

Does List<T> guarantee insertion order?

If you will change the order of operations, you will avoid the strange behavior: First insert the value to the right place in the list, and then delete it from his first position. Make sure you delete it by his index, because if you will delete it by reference, you might delete them both...

The AWS Access Key Id does not exist in our records

another thing that can cause this, even if everything is set up correctly, is running the command from a Makefile. for example, I had a rule:

awssetup:
        aws configure
        aws s3 sync s3://mybucket.whatever .

when I ran make awssetup I got the error: fatal error: An error occurred (InvalidAccessKeyId) when calling the ListObjects operation: The AWS Access Key Id you provided does not exist in our records.. but running it from the command line worked.

Difference between FetchType LAZY and EAGER in Java Persistence API?

EAGER loading of collections means that they are fetched fully at the time their parent is fetched. So if you have Course and it has List<Student>, all the students are fetched from the database at the time the Course is fetched.

LAZY on the other hand means that the contents of the List are fetched only when you try to access them. For example, by calling course.getStudents().iterator(). Calling any access method on the List will initiate a call to the database to retrieve the elements. This is implemented by creating a Proxy around the List (or Set). So for your lazy collections, the concrete types are not ArrayList and HashSet, but PersistentSet and PersistentList (or PersistentBag)

Disable Required validation attribute under certain circumstances

Client side For disabling validation for a form, multiple options based on my research is given below. One of them would would hopefully work for you.

Option 1

I prefer this, and this works perfectly for me.

(function ($) {
    $.fn.turnOffValidation = function (form) {
        var settings = form.validate().settings;

        for (var ruleIndex in settings.rules) {
            delete settings.rules[ruleIndex];
        }
    };
})(jQuery); 

and invoking it like

$('#btn').click(function () {
    $(this).turnOffValidation(jQuery('#myForm'));
});

Option 2

$('your selector here').data('val', false);
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");

Option 3

var settings = $.data($('#myForm').get(0), 'validator').settings;
settings.ignore = ".input";

Option 4

 $("form").get(0).submit();
 jQuery('#createForm').unbind('submit').submit();

Option 5

$('input selector').each(function () {
    $(this).rules('remove');
});

Server Side

Create an attribute and mark your action method with that attribute. Customize this to adapt to your specific needs.

[AttributeUsage(AttributeTargets.All)]
public class IgnoreValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var modelState = filterContext.Controller.ViewData.ModelState;

        foreach (var modelValue in modelState.Values)
        {
            modelValue.Errors.Clear();
        }
    }
}

A better approach has been described here Enable/Disable mvc server side validation dynamically

How do I prevent CSS inheritance?

You don't need the class reference for the lis. Instead of having CSS like

li.top-level-nav { color:black; }

you can write

ul#sidebar > li { color:black; }

This will apply the styling only to lis that immediately descend from the sidebar ul.

How do I import a .bak file into Microsoft SQL Server 2012?

.bak is a backup file generated in SQL Server.

Backup files importing means restoring a database, you can restore on a database created in SQL Server 2012 but the backup file should be from SQL Server 2005, 2008, 2008 R2, 2012 database.

You restore database by using following command...

RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH Recovery

You want to learn about how to restore .bak file follow the below link:

http://msdn.microsoft.com/en-us/library/ms186858(v=sql.90).aspx

sql delete statement where date is greater than 30 days

Although the DATEADD is probably the most transparrent way of doing this, it is worth noting that simply getdate()-30 will also suffice.

Also, are you looking for 30 days from now, i.e. including hours, minutes, seconds, etc? Or 30 days from midnight today (e.g. 12/06/2010 00:00:00.000). In which case, you might consider:

SELECT * 
FROM Results 
WHERE convert(varchar(8), [Date], 112) >= convert(varchar(8), getdate(), 112)

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How can I remove duplicate rows?

alter table MyTable add sno int identity(1,1)
    delete from MyTable where sno in
    (
    select sno from (
    select *,
    RANK() OVER ( PARTITION BY RowID,Col3 ORDER BY sno DESC )rank
    From MyTable
    )T
    where rank>1
    )

    alter table MyTable 
    drop  column sno

Efficiency of Java "Double Brace Initialization"?

There's generally nothing particularly inefficient about it. It doesn't generally matter to the JVM that you've made a subclass and added a constructor to it-- that's a normal, everyday thing to do in an object-oriented language. I can think of quite contrived cases where you could cause an inefficiency by doing this (e.g. you have a repeatedly-called method that ends up taking a mixture of different classes because of this subclass, whereas ordinary the class passed in would be totally predictable-- in the latter case, the JIT compiler could make optimisations that are not feasible in the first). But really, I think the cases where it'll matter are very contrived.

I'd see the issue more from the point of view of whether you want to "clutter things up" with lots of anonymous classes. As a rough guide, consider using the idiom no more than you'd use, say, anonymous classes for event handlers.

In (2), you're inside the constructor of an object, so "this" refers to the object you're constructing. That's no different to any other constructor.

As for (3), that really depends on who's maintaining your code, I guess. If you don't know this in advance, then a benchmark that I would suggest using is "do you see this in the source code to the JDK?" (in this case, I don't recall seeing many anonymous initialisers, and certainly not in cases where that's the only content of the anonymous class). In most moderately sized projects, I'd argue you're really going to need your programmers to understand the JDK source at some point or other, so any syntax or idiom used there is "fair game". Beyond that, I'd say, train people on that syntax if you have control of who's maintaining the code, else comment or avoid.

R: "Unary operator error" from multiline ggplot2 command

This is a well-known nuisance when posting multiline commands in R. (You can get different behavior when you source() a script to when you copy-and-paste the lines, both with multiline and comments)

Rule: always put the dangling '+' at the end of a line so R knows the command is unfinished:

ggplot(...) + geom_whatever1(...) +
  geom_whatever2(...) +
  stat_whatever3(...) +
  geom_title(...) + scale_y_log10(...)

Don't put the dangling '+' at the start of the line, since that tickles the error:

Error in "+ geom_whatever2(...) invalid argument to unary operator"

And obviously don't put dangling '+' at both end and start since that's a syntax error.

So, learn a habit of being consistent: always put '+' at end-of-line.

cf. answer to "Split code over multiple lines in an R script"

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

You are off slightly on a few things here, so hopefully the following helps.

Firstly, you don't need to select ranges to access their properties, you can just specify their address etc. Secondly, unless you are manipulating the values within the range, you don't actually need to set them to a variant. If you do want to manipulate the values, you can leave out the bounds of the array as it will be set when you define the range.

It's also good practice to use Option Explicit at the top of your modules to force variable declaration.

The following will do what you are after:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = Range("C4:G4").Value
    Next
End Sub

If you do want to manipulate the values within the array then do this:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer
    Dim anARRAY as Variant

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       anARRAY= Range("C4:G4").Value

       'You can loop through the array and manipulate it here

       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = anARRAY
    Next
End Sub

Resize image in PHP

ZF cake:

<?php

class FkuController extends Zend_Controller_Action {

  var $image;
  var $image_type;

  public function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {

    $target_dir = APPLICATION_PATH  . "/../public/1/";
    $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);

    //$image = new SimpleImage();
    $this->load($_FILES[$html_element_name]['tmp_name']);
    $this->resize($new_img_width, $new_img_height);
    $this->save($target_file);
    return $target_file; 
    //return name of saved file in case you want to store it in you database or show confirmation message to user



  public function load($filename) {

      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {

         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {

         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {

         $this->image = imagecreatefrompng($filename);
      }
   }
  public function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {

      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {

         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {

         imagepng($this->image,$filename);
      }
      if( $permissions != null) {

         chmod($filename,$permissions);
      }
   }
  public function output($image_type=IMAGETYPE_JPEG) {

      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {

         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {

         imagepng($this->image);
      }
   }
  public function getWidth() {

      return imagesx($this->image);
   }
  public function getHeight() {

      return imagesy($this->image);
   }
  public function resizeToHeight($height) {

      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }

  public function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }

  public function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }

  public function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }

  public function savepicAction() {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender();
    $this->_response->setHeader('Access-Control-Allow-Origin', '*');

    $this->db = Application_Model_Db::db_load();        
    $ouser = $_POST['ousername'];


      $fdata = 'empty';
      if (isset($_FILES['picture']) && $_FILES['picture']['size'] > 0) {
        $file_size = $_FILES['picture']['size'];
        $tmpName  = $_FILES['picture']['tmp_name'];  

        //Determine filetype
        switch ($_FILES['picture']['type']) {
            case 'image/jpeg': $ext = "jpg"; break;
            case 'image/png': $ext = "png"; break;
            case 'image/jpg': $ext = "jpg"; break;
            case 'image/bmp': $ext = "bmp"; break;
            case 'image/gif': $ext = "gif"; break;
            default: $ext = ''; break;
        }

        if($ext) {
          //if($file_size<400000) {  
            $img = $this->store_uploaded_image('picture', 90,82);
            //$fp      = fopen($tmpName, 'r');
            $fp = fopen($img, 'r');
            $fdata = fread($fp, filesize($tmpName));        
            $fdata = base64_encode($fdata);
            fclose($fp);

          //}
        }

      }

      if($fdata=='empty'){

      }
      else {
        $this->db->update('users', 
          array(
            'picture' => $fdata,             
          ), 
          array('username=?' => $ouser ));        
      }



  }  

Adding Only Untracked Files

git ls-files lists the files in the current directory. If you want to list untracked files from anywhere in the tree, this might work better:

git ls-files -o --exclude-standard $(git rev-parse --show-toplevel)

To add all untracked files in the tree:

git ls-files -o --exclude-standard $(git rev-parse --show-toplevel) | xargs git add

How to check if variable's type matches Type stored in a variable

You need to see if the Type of your instance is equal to the Type of the class. To get the type of the instance you use the GetType() method:

 u.GetType().Equals(t);

or

 u.GetType.Equals(typeof(User));

should do it. Obviously you could use '==' to do your comparison if you prefer.

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')

How to suppress Update Links warning?

UPDATE:

After all the details summarized and discussed, I spent 2 fair hours in checking the options, and this update is to dot all is.

Preparations

First of all, I performed a clean Office 2010 x86 install on Clean Win7 SP1 Ultimate x64 virtual machine powered by VMWare (this is usual routine for my everyday testing tasks, so I have many of them deployed).

Then, I changed only the following Excel options (i.e. all the other are left as is after installation):

  • Advanced > General > Ask to update automatic links checked:

Ask to update automatic links

  • Trust Center > Trust Center Settings... > External Content > Enable All... (although that one that relates to Data Connections is most likely not important for the case):

External Content

Preconditions

I prepared and placed to C:\ a workbook exactly as per @Siddharth Rout suggestions in his updated answer (shared for your convenience): https://www.dropbox.com/s/mv88vyc27eljqaq/Book1withLinkToBook2.xlsx Linked book was then deleted so that link in the shared book is unavailable (for sure).

Manual Opening

The above shared file shows on opening (having the above listed Excel options) 2 warnings - in the order of appearance:

WARNING #1

This workbook contains links to other data sources

After click on Update I expectedly got another:

WARNING #2

This workbook contains one or more links that cannot be updated

So, I suppose my testing environment is now pretty much similar to OP's) So far so good, we finally go to

VBA Opening

Now I'll try all possible options step by step to make the picture clear. I'll share only relevant lines of code for simplicity (complete sample file with code will be shared in the end).

1. Simple Application.Workbooks.Open

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"

No surprise - this produces BOTH warnings, as for manual opening above.

2. Application.DisplayAlerts = False

Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True

This code ends up with WARNING #1, and either option clicked (Update / Don't Update) produces NO further warnings, i.e. Application.DisplayAlerts = False suppresses WARNING #2.

3. Application.AskToUpdateLinks = False

Application.AskToUpdateLinks = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.AskToUpdateLinks = True

Opposite to DisplayAlerts, this code ends up with WARNING #2 only, i.e. Application.AskToUpdateLinks = False suppresses WARNING #1.

4. Double False

Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True

Apparently, this code ends up with suppressing BOTH WARNINGS.

5. UpdateLinks:=False

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=False

Finally, this 1-line solution (originally proposed by @brettdj) works the same way as Double False: NO WARNINGS are shown!

Conclusions

Except a good testing practice and very important solved case (I may face such issues everyday while sending my workbooks to 3rd party, and now I'm prepared), 2 more things learned:

  1. Excel options DO matter, regardless of version - especially when we come to VBA solutions.
  2. Every trouble has short and elegant solution - together with not obvious and complicated one. Just one more proof for that!)

Thanks very much to everyone who contributed to the solution, and especially OP who raised the question. Hope my investigations and thoroughly described testing steps were helpful not only for me)

Sample file with the above code samples is shared (many lines are commented deliberately): https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm

Original answer (tested for Excel 2007 with certain options):

This code works fine for me - it loops through ALL Excel files specified using wildcards in the InputFolder:

Sub WorkbookOpening2007()

Dim InputFolder As String
Dim LoopFileNameExt As String

InputFolder = "D:\DOCUMENTS\" 'Trailing "\" is required!

LoopFileNameExt = Dir(InputFolder & "*.xls?")
Do While LoopFileNameExt <> ""

Application.DisplayAlerts = False
Application.Workbooks.Open (InputFolder & LoopFileNameExt)
Application.DisplayAlerts = True

LoopFileNameExt = Dir
Loop

End Sub

I tried it with books with unavailable external links - no warnings.

Sample file: https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm

How does the data-toggle attribute work? (What's its API?)

I think you are a bit confused on the purpose of custom data attributes. From the w3 spec

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value".

In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.

Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".

  • Button Toggle

    Button.prototype.toggle = function () {
      var changed = true
      var $parent = this.$element.closest('[data-toggle="buttons"]')
    
      if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
          if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
          else $parent.find('.active').removeClass('active')
        }
        if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
      } else {
        this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
      }
    
      if (changed) this.$element.toggleClass('active')
    }
    

The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element.

From what I see these are the data-toggle options:

  • collapse
  • dropdown
  • modal
  • tab
  • pill
  • button(s)

You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

WCF - How to Increase Message Size Quota

You'll want something like this to increase the message size quotas, in the App.config or Web.config file:

<bindings>
    <basicHttpBinding>
        <binding name="basicHttp" allowCookies="true"
                 maxReceivedMessageSize="20000000" 
                 maxBufferSize="20000000"
                 maxBufferPoolSize="20000000">
            <readerQuotas maxDepth="32" 
                 maxArrayLength="200000000"
                 maxStringContentLength="200000000"/>
        </binding>
    </basicHttpBinding>
</bindings>

And use the binding name in your endpoint configuration e.g.

...
bindingConfiguration="basicHttp"
...

The justification for the values is simple, they are sufficiently large to accommodate most messages. You can tune that number to fit your needs. The low default value is basically there to prevent DOS type attacks. Making it 20000000 would allow for a distributed DOS attack to be effective, the default size of 64k would require a very large number of clients to overpower most servers these days.

How can I show data using a modal when clicking a table row (using bootstrap)?

The best practice is to ajax load the order information when click tr tag, and render the information html in $('#orderDetails') like this:

  $.get('the_get_order_info_url', { order_id: the_id_var }, function(data){
    $('#orderDetails').html(data);
  }, 'script')

Alternatively, you can add class for each td that contains the order info, and use jQuery method $('.class').html(html_string) to insert specific order info into your #orderDetails BEFORE you show the modal, like:

  <% @restaurant.orders.each do |order| %>
  <!-- you should add more class and id attr to help control the DOM -->
  <tr id="order_<%= order.id %>" onclick="orderModal(<%= order.id  %>);">
    <td class="order_id"><%= order.id %></td>
    <td class="customer_id"><%= order.customer_id %></td>
    <td class="status"><%= order.status %></td>
  </tr>
  <% end %>

js:

function orderModal(order_id){
  var tr = $('#order_' + order_id);
  // get the current info in html table 
  var customer_id = tr.find('.customer_id');
  var status = tr.find('.status');

  // U should work on lines here:
  var info_to_insert = "order: " + order_id + ", customer: " + customer_id + " and status : " + status + ".";
  $('#orderDetails').html(info_to_insert);

  $('#orderModal').modal({
    keyboard: true,
    backdrop: "static"
  });
};

That's it. But I strongly recommend you to learn sth about ajax on Rails. It's pretty cool and efficient.

Resetting Select2 value in dropdown with reset button

What I found works well is as follows:

if you have a placeholder option like 'All' or '-Select-' and its the first option and that's that you want to set the value to when you 'reset' you can use

$('#id').select2('val',0);

0 is essentially the option that you want to set it to on reset. If you want to set it to the last option then get the length of options and set it that length - 1. Basically use the index of whatever option you want to set the select2 value to on reset.

If you don't have a placeholder and just want no text to appear in the field use:

$('#id').select2('val','');

Get push notification while App in foreground iOS

Xcode 10 Swift 4.2

To show Push Notification when your app is in the foreground -

Step 1 : add delegate UNUserNotificationCenterDelegate in AppDelegate class.

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

Step 2 : Set the UNUserNotificationCenter delegate

let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self

Step 3 : This step will allow your app to show Push Notification even when your app is in foreground

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])

    }

Step 4 : This step is optional. Check if your app is in the foreground and if it is in foreground then show Local PushNotification.

func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler:@escaping (UIBackgroundFetchResult) -> Void) {

        let state : UIApplicationState = application.applicationState
        if (state == .inactive || state == .background) {
            // go to screen relevant to Notification content
            print("background")
        } else {
            // App is in UIApplicationStateActive (running in foreground)
            print("foreground")
            showLocalNotification()
        }
    }

Local Notification function -

fileprivate func showLocalNotification() {

        //creating the notification content
        let content = UNMutableNotificationContent()

        //adding title, subtitle, body and badge
        content.title = "App Update"
        //content.subtitle = "local notification"
        content.body = "New version of app update is available."
        //content.badge = 1
        content.sound = UNNotificationSound.default()

        //getting the notification trigger
        //it will be called after 5 seconds
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)

        //getting the notification request
        let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)

        //adding the notification to notification center
        notificationCenter.add(request, withCompletionHandler: nil)
    }

grant remote access of MySQL database from any IP address

Open your mysql console and execute the following command (enter your database name,username and password):

GRANT ALL ON yourdatabasename.* TO admin@'%' IDENTIFIED BY 'yourRootPassword';

Then Execute:

FLUSH PRIVILEGES;

Open command line and open the file /etc/mysql/mysql.conf.d/mysqld.cnf using any editor with root privileges.

For example:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Then comment out the below line:

bind-address = 127.0.0.1

Restart mysql to reflect the changes using command:

sudo service mysql restart

Enjoy ;)

PHP - warning - Undefined property: stdClass - fix?

Depending on whether you're looking for a member or method, you can use either of these two functions to see if a member/method exists in a particular object:

http://php.net/manual/en/function.method-exists.php

http://php.net/manual/en/function.property-exists.php

More generally if you want all of them:

http://php.net/manual/en/function.get-object-vars.php

An Iframe I need to refresh every 30 seconds (but not the whole page)

Let's assume that your iframe id= myIframe

here is the code:

<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
 document.getElementById("myIframe").src="YOUR_PAGE_URL_HERE";
}
</script>

Plotting a fast Fourier transform in Python

There are already great solutions on this page, but all have assumed the dataset is uniformly/evenly sampled/distributed. I will try to provide a more general example of randomly sampled data. I will also use this MATLAB tutorial as an example:

Adding the required modules:

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
import scipy.signal

Generating sample data:

N = 600 # Number of samples
t = np.random.uniform(0.0, 1.0, N) # Assuming the time start is 0.0 and time end is 1.0
S = 1.0 * np.sin(50.0 * 2 * np.pi * t) + 0.5 * np.sin(80.0 * 2 * np.pi * t)
X = S + 0.01 * np.random.randn(N) # Adding noise

Sorting the data set:

order = np.argsort(t)
ts = np.array(t)[order]
Xs = np.array(X)[order]

Resampling:

T = (t.max() - t.min()) / N # Average period
Fs = 1 / T # Average sample rate frequency
f = Fs * np.arange(0, N // 2 + 1) / N; # Resampled frequency vector
X_new, t_new = scipy.signal.resample(Xs, N, ts)

Plotting the data and resampled data:

plt.xlim(0, 0.1)
plt.plot(t_new, X_new, label="resampled")
plt.plot(ts, Xs, label="org")
plt.legend()
plt.ylabel("X")
plt.xlabel("t")

Enter image description here

Now calculating the FFT:

Y = scipy.fftpack.fft(X_new)
P2 = np.abs(Y / N)
P1 = P2[0 : N // 2 + 1]
P1[1 : -2] = 2 * P1[1 : -2]

plt.ylabel("Y")
plt.xlabel("f")
plt.plot(f, P1)

Enter image description here

P.S. I finally got time to implement a more canonical algorithm to get a Fourier transform of unevenly distributed data. You may see the code, description, and example Jupyter notebook here.

Easily measure elapsed time

In answer to OP's three specific questions.

"What I don't understand is why the values in the before and after are the same?"

The first question and sample code shows that time() has a resolution of 1 second, so the answer has to be that the two functions execute in less than 1 second. But occasionally it will (apparently illogically) inform 1 second if the two timer marks straddle a one second boundary.

The next example uses gettimeofday() which fills this struct

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

and the second question asks: "How do I read a result of **time taken = 0 26339? Does that mean 26,339 nanoseconds = 26.3 msec?"

My second answer is the time taken is 0 seconds and 26339 microseconds, that is 0.026339 seconds, which bears out the first example executing in less than 1 second.

The third question asks: "What about **time taken = 4 45025, does that mean 4 seconds and 25 msec?"

My third answer is the time taken is 4 seconds and 45025 microseconds, that is 4.045025 seconds, which shows that OP has altered the tasks performed by the two functions which he previously timed.

How to get row number from selected rows in Oracle

I think using

select rownum st.Branch 
  from student st 
 where st.name like '%ram%'

is a simple way; you should add single quotes in the LIKE statement. If you use row_number(), you should add over (order by 'sort column' 'asc/desc'), for instance:

select st.branch, row_number() over (order by 'sort column' 'asc/desc')  
  from student st 
 where st.name like '%ram%'

Integrating CSS star rating into an HTML form

Here is how to integrate CSS star rating into an HTML form without using javascript (only html and css):

CSS:

.txt-center {
    text-align: center;
}
.hide {
    display: none;
}

.clear {
    float: none;
    clear: both;
}

.rating {
    width: 90px;
    unicode-bidi: bidi-override;
    direction: rtl;
    text-align: center;
    position: relative;
}

.rating > label {
    float: right;
    display: inline;
    padding: 0;
    margin: 0;
    position: relative;
    width: 1.1em;
    cursor: pointer;
    color: #000;
}

.rating > label:hover,
.rating > label:hover ~ label,
.rating > input.radio-btn:checked ~ label {
    color: transparent;
}

.rating > label:hover:before,
.rating > label:hover ~ label:before,
.rating > input.radio-btn:checked ~ label:before,
.rating > input.radio-btn:checked ~ label:before {
    content: "\2605";
    position: absolute;
    left: 0;
    color: #FFD700;
}

HTML:

<div class="txt-center">
    <form>
        <div class="rating">
            <input id="star5" name="star" type="radio" value="5" class="radio-btn hide" />
            <label for="star5">?</label>
            <input id="star4" name="star" type="radio" value="4" class="radio-btn hide" />
            <label for="star4">?</label>
            <input id="star3" name="star" type="radio" value="3" class="radio-btn hide" />
            <label for="star3">?</label>
            <input id="star2" name="star" type="radio" value="2" class="radio-btn hide" />
            <label for="star2">?</label>
            <input id="star1" name="star" type="radio" value="1" class="radio-btn hide" />
            <label for="star1">?</label>
            <div class="clear"></div>
        </div>
    </form>
</div>

Please check the demo

What does "collect2: error: ld returned 1 exit status" mean?

clrscr is not standard C function. According to internet, it used to be a thing in old Borland C.
Is clrscr(); a function in C++?

Parsing JSON in Excel VBA

If you want to build on top of ScriptControl, you can add a few helper method to get at the required information. The JScriptTypeInfo object is a bit unfortunate: it contains all the relevant information (as you can see in the Watch window) but it seems impossible to get at it with VBA. However, the Javascript engine can help us:

Option Explicit

Private ScriptEngine As ScriptControl

Public Sub InitScriptEngine()
    Set ScriptEngine = New ScriptControl
    ScriptEngine.Language = "JScript"
    ScriptEngine.AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "
    ScriptEngine.AddCode "function getKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj) { keys.push(i); } return keys; } "
End Sub

Public Function DecodeJsonString(ByVal JsonString As String)
    Set DecodeJsonString = ScriptEngine.Eval("(" + JsonString + ")")
End Function

Public Function GetProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Variant
    GetProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function

Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
    Set GetObjectProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function

Public Function GetKeys(ByVal JsonObject As Object) As String()
    Dim Length As Integer
    Dim KeysArray() As String
    Dim KeysObject As Object
    Dim Index As Integer
    Dim Key As Variant

    Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
    Length = GetProperty(KeysObject, "length")
    ReDim KeysArray(Length - 1)
    Index = 0
    For Each Key In KeysObject
        KeysArray(Index) = Key
        Index = Index + 1
    Next
    GetKeys = KeysArray
End Function


Public Sub TestJsonAccess()
    Dim JsonString As String
    Dim JsonObject As Object
    Dim Keys() As String
    Dim Value As Variant
    Dim j As Variant

    InitScriptEngine

    JsonString = "{""key1"": ""val1"", ""key2"": { ""key3"": ""val3"" } }"
    Set JsonObject = DecodeJsonString(CStr(JsonString))
    Keys = GetKeys(JsonObject)

    Value = GetProperty(JsonObject, "key1")
    Set Value = GetObjectProperty(JsonObject, "key2")
End Sub

A few notes:

  • If the JScriptTypeInfo instance refers to a Javascript object, For Each ... Next won't work. However, it does work if it refers to a Javascript array (see GetKeys function).
  • The access properties whose name is only known at run-time, use the functions GetProperty and GetObjectProperty.
  • The Javascript array provides the properties length, 0, Item 0, 1, Item 1 etc. With the VBA dot notation (jsonObject.property), only the length property is accessible and only if you declare a variable called length with all lowercase letters. Otherwise the case doesn't match and it won't find it. The other properties are not valid in VBA. So better use the GetProperty function.
  • The code uses early binding. So you have to add a reference to "Microsoft Script Control 1.0".
  • You have to call InitScriptEngine once before using the other functions to do some basic initialization.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

How to get the sizes of the tables of a MySQL database?

Calculate the total size of the database at the end:

(SELECT 
  table_name AS `Table`, 
  round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` 
  FROM information_schema.TABLES 
  WHERE table_schema = "$DB_NAME"
)
UNION ALL
(SELECT 
  'TOTAL:',
  SUM(round(((data_length + index_length) / 1024 / 1024), 2) )
  FROM information_schema.TABLES 
  WHERE table_schema = "$DB_NAME"
)

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

How to change a dataframe column from String type to Double type in PySpark?

Preserve the name of the column and avoid extra column addition by using the same name as input column:

changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))

Foreach loop in java for a custom object list

Using can also use Java 8 stream API and do the same thing in one line.

If you want to print any specific property then use this syntax:

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> System.out.println(room.getName()));

OR

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> {
    // here room is available
});

if you want to print all the properties of Java object then use this:

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(System.out::println);

Set Focus After Last Character in Text Box

you can set pointer on last position of textbox as per following.

temp=$("#txtName").val();
$("#txtName").val('');
$("#txtName").val(temp);
$("#txtName").focus();

How to find a text inside SQL Server procedures / triggers?

You can search within the definitions of all database objects using the following SQL:

SELECT 
    o.name, 
    o.id, 
    c.text,
    o.type
FROM 
    sysobjects o 
RIGHT JOIN syscomments c 
    ON o.id = c.id 
WHERE 
    c.text like '%text_to_find%'

How to display loading image while actual image is downloading

You can do something like this:

// show loading image
$('#loader_img').show();

// main image loaded ?
$('#main_img').on('load', function(){
  // hide/remove the loading image
  $('#loader_img').hide();
});

You assign load event to the image which fires when image has finished loading. Before that, you can show your loader image.

Angularjs error Unknown provider

bmleite has the correct answer about including the module.

If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.

Remember:

angular.module('ModuleName', [])   // creates a module.

angular.module('ModuleName')       // gets you a pre-existing module.

So if you are extending a existing module, remember not to overwrite when trying to fetch it.

Writing to an Excel spreadsheet

The easiest way to import the exact numbers is to add a decimal after the numbers in your l1 and l2. Python interprets this decimal point as instructions from you to include the exact number. If you need to restrict it to some decimal place, you should be able to create a print command that limits the output, something simple like:

print variable_example[:13]

Would restrict it to the tenth decimal place, assuming your data has two integers left of the decimal.

Mixing a PHP variable with a string literal

You can use {} arround your variable, to separate it from what's after:

echo "{$test}y"

As reference, you can take a look to the Variable parsing - Complex (curly) syntax section of the PHP manual.

What's the difference between VARCHAR and CHAR?

VARCHAR is variable-length.

CHAR is fixed length.

If your content is a fixed size, you'll get better performance with CHAR.

See the MySQL page on CHAR and VARCHAR Types for a detailed explanation (be sure to also read the comments).

How can I implement prepend and append with regular JavaScript?

If you want to insert a raw HTML string no matter how complex, you can use: insertAdjacentHTML, with appropriate first argument:

'beforebegin' Before the element itself. 'afterbegin' Just inside the element, before its first child. 'beforeend' Just inside the element, after its last child. 'afterend' After the element itself.

Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.

An example of usage:

document.getElementById("foo").insertAdjacentHTML("beforeBegin",
          "<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");

DEMO

Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.

Java string split with "." (dot)

The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:

final String extensionRemoved = filename.split("\\.")[0];

I hope this helps

Is there a way to make a DIV unselectable?

I wrote a simple jQuery extension to disable selection some time back: Disabling Selection in jQuery. You can invoke it through $('.button').disableSelection();

Alternately, using CSS (cross-browser):

.button {
        user-select: none;
        -moz-user-select: none;
        -khtml-user-select: none;
        -webkit-user-select: none;
        -o-user-select: none;
} 

Could you explain STA and MTA?

As my understanding, the 'Apartment' is used to protect the COM objects from multi-threading issues.

If a COM object is not thread-safe, it should declare it as a STA object. Then only the thread who creates it can access it. The creation thread should declare itself as a STA thread. Under the hood, the thread stores the STA information in its TLS(Thread Local Storage). We call this behavior as that the thread enters a STA apartment. When other threads want to access this COM object, it should marshal the access to the creation thread. Basically, the creation thread uses messages mechanism to process the in-bound calls.

If a COM object is thread-safe, it should declare it as a MTA object. The MTA object can be accessed by multi-threads.

How to use SQL LIKE condition with multiple values in PostgreSQL?

You might be able to use IN, if you don't actually need wildcards.

SELECT * from table WHERE column IN ('AAA', 'BBB', 'CCC')

Initializing a struct to 0

If the data is a static or global variable, it is zero-filled by default, so just declare it myStruct _m;

If the data is a local variable or a heap-allocated zone, clear it with memset like:

memset(&m, 0, sizeof(myStruct));

Current compilers (e.g. recent versions of gcc) optimize that quite well in practice. This works only if all zero values (include null pointers and floating point zero) are represented as all zero bits, which is true on all platforms I know about (but the C standard permits implementations where this is false; I know no such implementation).

You could perhaps code myStruct m = {}; or myStruct m = {0}; (even if the first member of myStruct is not a scalar).

My feeling is that using memset for local structures is the best, and it conveys better the fact that at runtime, something has to be done (while usually, global and static data can be understood as initialized at compile time, without any cost at runtime).

POST unchecked HTML checkboxes

function SubmitCheckBox(obj) {
     obj.value   = obj.checked ? "on" : "off";
     obj.checked = true;
     return obj.form.submit();
}

<input type=checkbox name="foo" onChange="return SubmitCheckBox(this);">

Browse and display files in a git repo without cloning

This is probably considered dirty by some, but a very practical solution in case of github repositories is just to make a script, e.g. "git-ls":

#!/bin/sh
remote_url=${1:? "$0 requires URL as argument"}
curl -s $remote_url | grep js-directory-link | sed "s/.* title=\"\(.*\)\".*/\1/"

Make it executable and reachable of course: chmod a+x git-ls; sudo cp git-ls /usr/local/bin. Now, you just run it as you wish:

git-ls https://github.com/mrquincle/aim-bzr
git-ls https://github.com/mrquincle/aim-bzr/tree/master/aim_modules

Also know that there is a git instaweb utility for your local files. To have the ability to show files and have a server like that does in my opinion not destroy any of the inherent decentralized characteristics of git.

Where's my invalid character (ORA-00911)

Of the top of my head, can you try to use the 'q' operator for the string literal

something like

insert all
  into domo_queries values (q'[select 
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = 'CHQ PeopleSoft FS']')
select * from dual;

Note that the single quotes of your predicate are not escaped, and the string sits between q'[...]'.

How to grant remote access permissions to mysql server for user?

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' 
    IDENTIFIED BY 'YOUR_PASS' 
    WITH GRANT OPTION;
FLUSH PRIVILEGES;  

*.* = DB.TABLE you can restrict user to specific database and specific table.

'root'@'%' you can change root with any user you created and % is to allow all IP. You can restrict it by changing %.168.1.1 etc too.


If that doesn't resolve, then also modify my.cnf or my.ini and comment these lines

bind-address = 127.0.0.1 to #bind-address = 127.0.0.1
and
skip-networking to #skip-networking

  • Restart MySQL and repeat above steps again.

Raspberry Pi, I found bind-address configuration under \etc\mysql\mariadb.conf.d\50-server.cnf

awk - concatenate two string variable and assign to a third

Concatenating strings in awk can be accomplished by the print command AWK manual page, and you can do complicated combination. Here I was trying to change the 16 char to A and used string concatenation:

echo    CTCTCTGAAATCACTGAGCAGGAGAAAGATT | awk -v w=15 -v BA=A '{OFS=""; print substr($0, 1, w), BA, substr($0,w+2)}'
Output: CTCTCTGAAATCACTAAGCAGGAGAAAGATT

I used the substr function to extract a portion of the input (STDIN). I passed some external parameters (here I am using hard-coded values) that are usually shell variable. In the context of shell programming, you can write -v w=$width -v BA=$my_charval. The key is the OFS which stands for Output Field Separate in awk. Print function take a list of values and write them to the STDOUT and glue them with the OFS. This is analogous to the perl join function.

It looks that in awk, string can be concatenated by printing variable next to each other:

echo xxx | awk -v a="aaa" -v b="bbb" '{ print a b $1 "string literal"}'
# will produce: aaabbbxxxstring literal

Change color of bootstrap navbar on hover link?

Target the element you wish to change and use !important to overwrite any existing styles that are assigned to that element. Be sure not to use the !important declaration when it is not absolutely necessary.

div.navbar div.navbar-inner ul.nav a:hover {
    color: #fff !important; 
}

How do I implement interfaces in python?

My understanding is that interfaces are not that necessary in dynamic languages like Python. In Java (or C++ with its abstract base class) interfaces are means for ensuring that e.g. you're passing the right parameter, able to perform set of tasks.

E.g. if you have observer and observable, observable is interested in subscribing objects that supports IObserver interface, which in turn has notify action. This is checked at compile time.

In Python, there is no such thing as compile time and method lookups are performed at runtime. Moreover, one can override lookup with __getattr__() or __getattribute__() magic methods. In other words, you can pass, as observer, any object that can return callable on accessing notify attribute.

This leads me to the conclusion, that interfaces in Python do exist - it's just their enforcement is postponed to the moment in which they are actually used

Flask SQLAlchemy query, specify column names

You can use Query.values, Query.values

session.query(SomeModel).values('id', 'user')

Singular matrix issue with Numpy

Use SVD or QR-decomposition to calculate exact solution in real or complex number fields:

numpy.linalg.svd numpy.linalg.qr

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Omit rows containing specific column of NA

Try this:

cc=is.na(DF$y)
m=which(cc==c("TRUE"))
DF=DF[-m,]

Generate a sequence of numbers in Python

Write a function that takes a number as an argument and prints the Fibonacci series till that number

def Series(n):  
    a = 0  
    b = 1  
    print(a)  
    print(b)  
    S = 0  
    for i in range(0,n):  
        if S <= n-1:  
            S = a + b  
            print(S)  
            a = b  
            b = S

How to print colored text to the terminal?

Here is a simple function I use to print a text message in color without having to remember ANSI codes but rather using standard RGB tuples to define the foreground and background colors.

def print_in_color(txt_msg, fore_tuple, back_tuple, ):
    # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
    # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
    rf,bf,gf = fore_tuple
    rb,gb,bb = back_tuple
    msg = '{0}' + txt_msg
    mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
    print(msg .format(mat))
    print('\33[0m') # Returns default print color to back to black

# Example of use using a message with variables
fore_color = 'cyan'
back_color = 'dark green'
msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255), (0,127,127))

Sort dataGridView columns in C# ? (Windows Form)

You can control the data returned from SQL database by ordering the data returned:

orderby [Name]

If you execute the SQL query from your application, order the data returned. For example, make a function that calls the procedure or executes the SQL and give it a parameter that gets the orderby criteria. Because if you ordered the data returned from database it will consume time but order it since it's executed as you say that you want it to be ordered not from the UI you want it to be ordered in the run time so order it when executing the SQL query.

How do I use CMake?

I don't know about Windows (never used it), but on a Linux system you just have to create a build directory (in the top source directory)

mkdir build-dir

go inside it

cd build-dir

then run cmake and point to the parent directory

cmake ..

and finally run make

make

Notice that make and cmake are different programs. cmake is a Makefile generator, and the make utility is governed by a Makefile textual file. See cmake & make wikipedia pages.

NB: On Windows, cmake might operate so could need to be used differently. You'll need to read the documentation (like I did for Linux)

iPhone App Development on Ubuntu

Many of the other solutions will work, but they all make use of the open-toolchain for the iPhone SDK. So, yes, you can write software for the iPhone on other platforms... BUT...

Since you specify that you want your app to end up on the App Store, then, no, there's not really any way to do this. There's certainly no time effective way to do this. Even if you only value your own time at $20/hr, it will be far more efficient to buy a used intel Mac, and download the free SDK.

How to read from stdin line by line in Node

process.stdin.pipe(process.stdout);

Can an interface extend multiple interfaces in Java?

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

for example, take a look here: http://www.tutorialspoint.com/java/java_interfaces.htm

Why does Git treat this text file as a binary file?

I had a similar issue as I pasted some text from a binary Kafka message, which inserted non-visible character and caused git to think the file is binary.

I found the offending characters by searching the file using regex [^ -~\n\r\t]+.

  • [ match characters in this set
  • ^ match characters not in this set
  • -~ matches all characters from ' ' (space) to '~'
  • \n newline
  • \r carriage return
  • \t tab
  • ] close set
  • + match one or more of these characters

How do I reference a cell within excel named range?

"Do you know if there's a way to make this work with relative selections, so that the formula can be "dragged down"/applied across several cells in the same column?"

To make such selection relative simply use ROW formula for a row number in INDEX formula and COLUMN formula for column number in INDEX formula. To make this clearer here is the example:

=INDEX(named_range,ROW(A1),COLUMN(A1))

Assuming the named range starts at A1 this formula simply indexes that range by row and column number of referenced cell and since that reference is relative it changes when you drag the the cell down or to the side, which makes it possible to create whole array of cells easily.

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

How can I update a row in a DataTable in VB.NET?

Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue

Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.

mySQL :: insert into table, data from another table?

for whole row

insert into xyz select * from xyz2 where id="1";

for selected column

insert into xyz(t_id,v_id,f_name) select t_id,v_id,f_name from xyz2 where id="1";

Host binding and Host listening

@HostListener is a decorator for the callback/event handler method, so remove the ; at the end of this line:

@HostListener('click', ['$event.target']);

Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick() method on the same line for clarity:

import {Component, HostListener, Directive} from 'angular2/core';

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

Host binding can also be used to listen to global events:

To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

Why is sed not recognizing \t as a tab?

@sedit was on the right path, but it's a bit awkward to define a variable.

Solution (bash specific)

The way to do this in bash is to put a dollar sign in front of your single quoted string.

$ echo -e '1\n2\n3'
1
2
3

$ echo -e '1\n2\n3' | sed 's/.*/\t&/g'
t1
t2
t3

$ echo -e '1\n2\n3' | sed $'s/.*/\t&/g'
    1
    2
    3

If your string needs to include variable expansion, you can put quoted strings together like so:

$ timestamp=$(date +%s)
$ echo -e '1\n2\n3' | sed "s/.*/$timestamp"$'\t&/g'
1491237958  1
1491237958  2
1491237958  3

Explanation

In bash $'string' causes "ANSI-C expansion". And that is what most of us expect when we use things like \t, \r, \n, etc. From: https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html#ANSI_002dC-Quoting

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded...

The expanded result is single-quoted, as if the dollar sign had not been present.

Solution (if you must avoid bash)

I personally think most efforts to avoid bash are silly because avoiding bashisms does NOT* make your code portable. (Your code will be less brittle if you shebang it to bash -eu than if you try to avoid bash and use sh [unless you are an absolute POSIX ninja].) But rather than have a religious argument about that, I'll just give you the BEST* answer.

$ echo -e '1\n2\n3' | sed "s/.*/$(printf '\t')&/g"
    1
    2
    3

* BEST answer? Yes, because one example of what most anti-bash shell scripters would do wrong in their code is use echo '\t' as in @robrecord's answer. That will work for GNU echo, but not BSD echo. That is explained by The Open Group at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html#tag_20_37_16 And this is an example of why trying to avoid bashisms usually fail.

Enabling WiFi on Android Emulator

As of now, with Revision 26.1.3 of the android emulator, it is finally possible on the image v8 of the API 25. If the emulator was created before you upgrade to the latest API 25 image, you need to wipe data or simply delete and recreate your image if you prefer.

Added support for Wi-Fi in some system images (currently only API level 25). An access point called "AndroidWifi" is available and Android automatically connects to it. Wi-Fi support can be disabled by running the emulator with the command line parameter -feature -Wifi.

from https://developer.android.com/studio/releases/emulator.html#26-1-3

How to SHA1 hash a string in Android?

final MessageDigest digest = MessageDigest.getInstance("SHA-1");
result = digest.digest(stringToHash.getBytes("UTF-8"));

// Another way to construct HEX, my previous post was only the method like your solution
StringBuilder sb = new StringBuilder();

for (byte b : result) // This is your byte[] result..
{
    sb.append(String.format("%02X", b));
}

String messageDigest = sb.toString();

Reverse a string in Python

def reverse_string(string):
    length = len(string)
    temp = ''
    for i in range(length):
        temp += string[length - i - 1]
    return temp

print(reverse_string('foo')) #prints "oof"

This works by looping through a string and assigning its values in reverse order to another string.

Java 8 Lambda function that throws exception?

Several of the offered solutions use a generic argument of E to pass in the type of the exception which gets thrown.

Take that one step further, and rather than passing in the type of the exception, pass in a Consumer of the type of exception, as in...

Consumer<E extends Exception>

You might create several re-usable variations of Consumer<Exception> which would cover the common exception handling needs of your application.

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

The problem is that you are calling ToString in a LINQ to Entities query. That means the parser is trying to convert the ToString call into its equivalent SQL (which isn't possible...hence the exception).

All you have to do is move the ToString call to a separate line:

var keyString = item.Key.ToString();

var pages = from p in context.entities
            where p.Serial == keyString
            select p;

HTML5 Pre-resize images before uploading

If you don't want to reinvent the wheel you may try plupload.com

"Could not find a valid gem in any repository" (rubygame and others)

This worked for me to bypass the proxy definitions:

1) become root

2) gem install -u gem_name gem_name

Hope you can work it out

How to get POSTed JSON in Flask?

First of all, the .json attribute is a property that delegates to the request.get_json() method, which documents why you see None here.

You need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None otherwise. See the Flask Request documentation:

This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see is_json()), otherwise it will be None.

You can tell request.get_json() to skip the content type requirement by passing it the force=True keyword argument.

Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

You may face this issue if you are running your app on Android's Marshmallow or later version (API level 23 or greater), because of the new Real-time Permissions model introduced in this.

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.

For getting permissions at runtime, you will have to request the user. You can do that in following way.

First request for permissions.

String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        requestPermissions(permissions, WRITE_REQUEST_CODE);

And then you can check the results in

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
       case WRITE_REQUEST_CODE:
         if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
           //Permission granted.
           //Continue with writing files...
         }
       else{
           //Permission denied.
         }
        break;
    }
}

Here is good learning source requesting-runtime-permissions-in-android-marshmallow/

How can I convert string date to NSDate?

To add String within Date Format in Swift, I did this

 var dataFormatter:NSDateFormatter = NSDateFormatter()
                dataFormatter.dateFormat = "dd-MMMM 'at' HH:mm a"

cell.timeStamplbl.text = dataFormatter.stringFromDate(object.createdAt)

Submit button doesn't work

I faced this problem today, and the issue was I was preventing event default action in document onclick:

document.onclick = function(e) {
    e.preventDefault();
}

Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:

document.onclick = function(e) {
    if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

You have to create dummy empty constructor in our model class.So while mapping json, it set by setter method.

Modifying a subset of rows in a pandas dataframe

Starting from pandas 0.20 ix is deprecated. The right way is to use df.loc

here is a working example

>>> import pandas as pd 
>>> import numpy as np 
>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN
>>> 

Explanation:

As explained in the doc here, .loc is primarily label based, but may also be used with a boolean array.

So, what we are doing above is applying df.loc[row_index, column_index] by:

  • Exploiting the fact that loc can take a boolean array as a mask that tells pandas which subset of rows we want to change in row_index
  • Exploiting the fact loc is also label based to select the column using the label 'B' in the column_index

We can use logical, condition or any operation that returns a series of booleans to construct the array of booleans. In the above example, we want any rows that contain a 0, for that we can use df.A == 0, as you can see in the example below, this returns a series of booleans.

>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df 
   A  B
0  0  2
1  1  0
2  0  5
>>> df.A == 0 
0     True
1    False
2     True
Name: A, dtype: bool
>>> 

Then, we use the above array of booleans to select and modify the necessary rows:

>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN

For more information check the advanced indexing documentation here.

How to select the first, second, or third element with a given class name?

Use CSS nth-child with the prefix class name

div.myclass:nth-child(1) {
  color: #000;
}

div.myclass:nth-child(2) {
  color: #FFF;
}

div.myclass:nth-child(3) {
  color: #006;
}

extract month from date in python

import datetime

a = '2010-01-31'

datee = datetime.datetime.strptime(a, "%Y-%m-%d")


datee.month
Out[9]: 1

datee.year
Out[10]: 2010

datee.day
Out[11]: 31