Programs & Examples On #Imap

Internet message application protocol (commonly known as IMAP) is one of the two most prevalent Internet standard protocols for e-mail retrieval, the other being the Post Office Protocol (POP).

using c# .net libraries to check for IMAP messages from gmail servers

I'd recommend looking at MailKit as it is probably the most robust mail library out there and it's Open Source (MIT).

One of the awesome things about MailKit is that all network APIs are cancelable (something I haven't seen available in any other IMAP library).

It's also the only library that I know of that supports threading of messages.

using System;
using System.Net;
using System.Threading;

using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using MimeKit;

namespace TestClient {
    class Program
    {
        public static void Main (string[] args)
        {
            using (var client = new ImapClient ()) {
                using (var cancel = new CancellationTokenSource ()) {
                    client.Connect ("imap.gmail.com", 993, true, cancel.Token);

                    // If you want to disable an authentication mechanism,
                    // you can do so by removing the mechanism like this:
                    client.AuthenticationMechanisms.Remove ("XOAUTH");

                    client.Authenticate ("joey", "password", cancel.Token);

                    // The Inbox folder is always available...
                    var inbox = client.Inbox;
                    inbox.Open (FolderAccess.ReadOnly, cancel.Token);

                    Console.WriteLine ("Total messages: {0}", inbox.Count);
                    Console.WriteLine ("Recent messages: {0}", inbox.Recent);

                    // download each message based on the message index
                    for (int i = 0; i < inbox.Count; i++) {
                        var message = inbox.GetMessage (i, cancel.Token);
                        Console.WriteLine ("Subject: {0}", message.Subject);
                    }

                    // let's try searching for some messages...
                    var query = SearchQuery.DeliveredAfter (DateTime.Parse ("2013-01-12"))
                        .And (SearchQuery.SubjectContains ("MailKit"))
                        .And (SearchQuery.Seen);

                    foreach (var uid in inbox.Search (query, cancel.Token)) {
                        var message = inbox.GetMessage (uid, cancel.Token);
                        Console.WriteLine ("[match] {0}: {1}", uid, message.Subject);
                    }

                    client.Disconnect (true, cancel.Token);
                }
            }
        }
    }
}

Accessing Imap in C#

I haven't tried it myself, but this is a free library you could try (I not so sure about the SSL part on this one):

http://www.codeproject.com/KB/IP/imaplibrary.aspx

Also, there is xemail, which has parameters for SSL:

http://xemail-net.sourceforge.net/

[EDIT] If you (or the client) have the money for a professional mail-client, this thread has some good recommendations:

Recommendations for a .NET component to access an email inbox

Fatal error: Call to undefined function imap_open() in PHP

To install IMAP on PHP 7.0.32 on Ubuntu 16.04. Go to the given link and based on your area select link. In my case, I select a link from the Asia section. Then a file will be downloaded. just click on the file to install IMAP .Then restart apache

https://packages.ubuntu.com/xenial/all/php-imap/download.

to check if IMAP is installed check phpinfo file.incase of successful installation IMAP c-Client Version 2007f will be shown.

HTML Upload MAX_FILE_SIZE does not appear to work

To anyone who had been wonderstruck about some files being easily uploaded and some not, it could be a size issue. I'm sharing this as I was stuck with my PHP code not uploading large files and I kept assuming it wasn't uploading any Excel files. So, if you are using PHP and you want to increase the file upload limit, go to the php.ini file and make the following modifications:

  • upload_max_filesize = 2M

to be changed to

  • upload_max_filesize = 10M

  • post_max_size = 10M

or the size required. Then restart the Apache server and the upload will start magically working. Hope this will be of help to someone.

SQL Server : fetching records between two dates?

try to use following query

select * 
from xxx 
where convert(date,dates) >= '2012-10-26' and convert(date,dates) <= '2012-10-27'

IIS URL Rewrite and Web.config

Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.

<rewrite>
  <rules>
    <rule name="enquiry" stopProcessing="true">
      <match url="^enquiry$" />
      <action type="Rewrite" url="/Enquiry.aspx" />
    </rule>
  </rules>
</rewrite>

How do I remove duplicates from a C# array?

This code 100% remove duplicate values from an array[as I used a[i]].....You can convert it in any OO language..... :)

for(int i=0;i<size;i++)
{
    for(int j=i+1;j<size;j++)
    {
        if(a[i] == a[j])
        {
            for(int k=j;k<size;k++)
            {
                 a[k]=a[k+1];
            }
            j--;
            size--;
        }
    }

}

String.replaceAll single backslashes with double backslashes

You'll need to escape the (escaped) backslash in the first argument as it is a regular expression. Replacement (2nd argument - see Matcher#replaceAll(String)) also has it's special meaning of backslashes, so you'll have to replace those to:

theString.replaceAll("\\\\", "\\\\\\\\");

Installing PIL with pip

For Ubuntu, PIL is not working any more. I always get:

No matching distribution found for PIL

So install python-imaging:

sudo apt-get install python-imaging

How to auto-format code in Eclipse?

Another option is to go to Window->Preferences->Java->Editor->SaveActions and check the Format source code option. Then your source code will be formatted truly automatically each time you save it.

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Sounds like you need to change the path to your java executable to match the newest version. Basically, installing the latest Java does not necessarily mean your machine is configured to use the latest version. You didn't mention any platform details, so that's all I can say.

Use of True, False, and None as return values in Python functions

The advice isn't that you should never use True, False, or None. It's just that you shouldn't use if x == True.

if x == True is silly because == is just a binary operator! It has a return value of either True or False, depending on whether its arguments are equal or not. And if condition will proceed if condition is true. So when you write if x == True Python is going to first evaluate x == True, which will become True if x was True and False otherwise, and then proceed if the result of that is true. But if you're expecting x to be either True or False, why not just use if x directly!

Likewise, x == False can usually be replaced by not x.

There are some circumstances where you might want to use x == True. This is because an if statement condition is "evaluated in Boolean context" to see if it is "truthy" rather than testing exactly against True. For example, non-empty strings, lists, and dictionaries are all considered truthy by an if statement, as well as non-zero numeric values, but none of those are equal to True. So if you want to test whether an arbitrary value is exactly the value True, not just whether it is truthy, when you would use if x == True. But I almost never see a use for that. It's so rare that if you do ever need to write that, it's worth adding a comment so future developers (including possibly yourself) don't just assume the == True is superfluous and remove it.


Using x is True instead is actually worse. You should never use is with basic built-in immutable types like Booleans (True, False), numbers, and strings. The reason is that for these types we care about values, not identity. == tests that values are the same for these types, while is always tests identities.

Testing identities rather than values is bad because an implementation could theoretically construct new Boolean values rather than go find existing ones, leading to you having two True values that have the same value, but they are stored in different places in memory and have different identities. In practice I'm pretty sure True and False are always reused by the Python interpreter so this won't happen, but that's really an implementation detail. This issue trips people up all the time with strings, because short strings and literal strings that appear directly in the program source are recycled by Python so 'foo' is 'foo' always returns True. But it's easy to construct the same string 2 different ways and have Python give them different identities. Observe the following:

>>> stars1 = ''.join('*' for _ in xrange(100))
>>> stars2 = '*' * 100
>>> stars1 is stars2
False
>>> stars1 == stars2
True

EDIT: So it turns out that Python's equality on Booleans is a little unexpected (at least to me):

>>> True is 1
False
>>> True == 1
True
>>> True == 2
False
>>> False is 0
False
>>> False == 0
True
>>> False == 0.0
True

The rationale for this, as explained in the notes when bools were introduced in Python 2.3.5, is that the old behaviour of using integers 1 and 0 to represent True and False was good, but we just wanted more descriptive names for numbers we intended to represent truth values.

One way to achieve that would have been to simply have True = 1 and False = 0 in the builtins; then 1 and True really would be indistinguishable (including by is). But that would also mean a function returning True would show 1 in the interactive interpreter, so what's been done instead is to create bool as a subtype of int. The only thing that's different about bool is str and repr; bool instances still have the same data as int instances, and still compare equality the same way, so True == 1.

So it's wrong to use x is True when x might have been set by some code that expects that "True is just another way to spell 1", because there are lots of ways to construct values that are equal to True but do not have the same identity as it:

>>> a = 1L
>>> b = 1L
>>> c = 1
>>> d = 1.0
>>> a == True, b == True, c == True, d == True
(True, True, True, True)
>>> a is b, a is c, a is d, c is d
(False, False, False, False)

And it's wrong to use x == True when x could be an arbitrary Python value and you only want to know whether it is the Boolean value True. The only certainty we have is that just using x is best when you just want to test "truthiness". Thankfully that is usually all that is required, at least in the code I write!

A more sure way would be x == True and type(x) is bool. But that's getting pretty verbose for a pretty obscure case. It also doesn't look very Pythonic by doing explicit type checking... but that really is what you're doing when you're trying to test precisely True rather than truthy; the duck typing way would be to accept truthy values and allow any user-defined class to declare itself to be truthy.

If you're dealing with this extremely precise notion of truth where you not only don't consider non-empty collections to be true but also don't consider 1 to be true, then just using x is True is probably okay, because presumably then you know that x didn't come from code that considers 1 to be true. I don't think there's any pure-python way to come up with another True that lives at a different memory address (although you could probably do it from C), so this shouldn't ever break despite being theoretically the "wrong" thing to do.

And I used to think Booleans were simple!

End Edit


In the case of None, however, the idiom is to use if x is None. In many circumstances you can use if not x, because None is a "falsey" value to an if statement. But it's best to only do this if you're wanting to treat all falsey values (zero-valued numeric types, empty collections, and None) the same way. If you are dealing with a value that is either some possible other value or None to indicate "no value" (such as when a function returns None on failure), then it's much better to use if x is None so that you don't accidentally assume the function failed when it just happened to return an empty list, or the number 0.

My arguments for using == rather than is for immutable value types would suggest that you should use if x == None rather than if x is None. However, in the case of None Python does explicitly guarantee that there is exactly one None in the entire universe, and normal idiomatic Python code uses is.


Regarding whether to return None or raise an exception, it depends on the context.

For something like your get_attr example I would expect it to raise an exception, because I'm going to be calling it like do_something_with(get_attr(file)). The normal expectation of the callers is that they'll get the attribute value, and having them get None and assume that was the attribute value is a much worse danger than forgetting to handle the exception when you can actually continue if the attribute can't be found. Plus, returning None to indicate failure means that None is not a valid value for the attribute. This can be a problem in some cases.

For an imaginary function like see_if_matching_file_exists, that we provide a pattern to and it checks several places to see if there's a match, it could return a match if it finds one or None if it doesn't. But alternatively it could return a list of matches; then no match is just the empty list (which is also "falsey"; this is one of those situations where I'd just use if x to see if I got anything back).

So when choosing between exceptions and None to indicate failure, you have to decide whether None is an expected non-failure value, and then look at the expectations of code calling the function. If the "normal" expectation is that there will be a valid value returned, and only occasionally will a caller be able to work fine whether or not a valid value is returned, then you should use exceptions to indicate failure. If it will be quite common for there to be no valid value, so callers will be expecting to handle both possibilities, then you can use None.

Remove all items from a FormArray in Angular

You can easily define a getter for your array and clear it as follows:

  formGroup: FormGroup    
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.formGroup = this.fb.group({
      sliders: this.fb.array([])
    })
  }
  get sliderForms() {
    return this.formGroup.get('sliders') as FormArray
  }

  clearAll() {
    this.formGroup.reset()
    this.sliderForms.clear()
  }

Google Chrome form autofill and its yellow background

Solution here:

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
    $(window).load(function(){
        $('input:-webkit-autofill').each(function(){
            var text = $(this).val();
            var name = $(this).attr('name');
            $(this).after(this.outerHTML).remove();
            $('input[name=' + name + ']').val(text);
        });
    });
}

Good Free Alternative To MS Access

The issue is finding an alternative to MS Access that includes a visual, drag and drop development environment with a "reasonable" database where the whole kit and caboodle can be deployed free of charge.

My first suggestion would be to look at this very complete list of MS Access alternatives (many of which are free), followed by a gander at this list of open source database development tools on osalt.com.

My second suggestion would be to check out WaveMaker, which is sort of an open source PowerBuilder for the cloud (disclaimer: I work there so should not be considered to be an unbiased source of information ;-)

WaveMaker combines a drag and drop IDE with an open source Java back end. It is licensed under the Apache license and boasts a 15,000-strong developer community.

Open page in new window without popup blocking

For the Submit button, add this code and then set your form target="newwin"

onclick=window.open("about:blank","newwin") 

Truncate a string straight JavaScript

Here's one method you can use. This is the answer for one of FreeCodeCamp Challenges:

function truncateString(str, num) {
  if (str.length > num) {
    return str.slice(0, num) + "...";
  } else {
    return str;
  }
}

How to store and retrieve a dictionary with redis

If you want to store a python dict in redis, it is better to store it as json string.

import redis

r = redis.StrictRedis(host='localhost', port=6379, db=0)
mydict = { 'var1' : 5, 'var2' : 9, 'var3': [1, 5, 9] }
rval = json.dumps(mydict)
r.set('key1', rval)

While retrieving de-serialize it using json.loads

data = r.get('key1')
result = json.loads(data)
arr = result['var3']

What about types (eg.bytes) that are not serialized by json functions ?

You can write encoder/decoder functions for types that cannot be serialized by json functions. eg. writing base64/ascii encoder/decoder function for byte array.

Finding common rows (intersection) in two Pandas dataframes

In SQL, this problem could be solved by several methods:

select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)

or join and then unpivot (possible in SQL server)

select
    df1.user_id,
    c.rating
from df1
    inner join df2 on df2.user_i = df1.user_id
    outer apply (
        select df1.rating union all
        select df2.rating
    ) as c

Second one could be written in pandas with something like:

>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
   user_id  rating
0        3      20
0        3      30

How can I iterate over an enum?

If you knew that the enum values were sequential, for example the Qt:Key enum, you could:

Qt::Key shortcut_key = Qt::Key_0;
for (int idx = 0; etc...) {
    ....
    if (shortcut_key <= Qt::Key_9) {
        fileMenu->addAction("abc", this, SLOT(onNewTab()),
                            QKeySequence(Qt::CTRL + shortcut_key));
        shortcut_key = (Qt::Key) (shortcut_key + 1);
    }
}

It works as expected.

How to convert <font size="10"> to px?

This is really old, but <font size="10"> would be about <p style= "font-size:55px">

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

When I'm running a springboot project, the application.yml configuration is like this:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/lof?serverTimezone=GMT
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

Notice that there isn't quotation marks around the password. And I can run this project in my windows System.

But when I try to deploy to the server, I have the problem and I fix it by changing the application.yml to:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/lof?serverTimezone=GMT
    username: root
    password: "root"
    driver-class-name: com.mysql.cj.jdbc.Driver

Laravel Query Builder where max id

You should be able to perform a select on the orders table, using a raw WHERE to find the max(id) in a subquery, like this:

 \DB::table('orders')->where('id', \DB::raw("(select max(`id`) from orders)"))->get();

If you want to use Eloquent (for example, so you can convert your response to an object) you will want to use whereRaw, because some functions such as toJSON or toArray will not work without using Eloquent models.

 $order = Order::whereRaw('id = (select max(`id`) from orders)')->get();

That, of course, requires that you have a model that extends Eloquent.

 class Order extends Eloquent {}

As mentioned in the comments, you don't need to use whereRaw, you can do the entire query using the query builder without raw SQL.

 // Using the Query Builder
 \DB::table('orders')->find(\DB::table('orders')->max('id'));

 // Using Eloquent
 $order = Order::find(\DB::table('orders')->max('id'));

(Note that if the id field is not unique, you will only get one row back - this is because find() will only return the first result from the SQL server.).

Do you recommend using semicolons after every statement in JavaScript?

An ambiguous case that breaks in the absence of a semicolon:

// define a function
var fn = function () {
    //...
} // semicolon missing at this line

// then execute some code inside a closure
(function () {
    //...
})();

This will be interpreted as:

var fn = function () {
    //...
}(function () {
    //...
})();

We end up passing the second function as an argument to the first function and then trying to call the result of the first function call as a function. The second function will fail with a "... is not a function" error at runtime.

How to add a custom right-click menu to a webpage?

Tested and works in Opera 12.17, firefox 30, Internet Explorer 9 and chrome 26.0.1410.64

document.oncontextmenu =function( evt ){
        alert("OK?");
        return false;
        }

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

How do you add swap to an EC2 instance?

You can use the following script to add swap on Amazon Linux.

https://github.com/chetankapoor/swap

Download the script using wget:

wget https://raw.githubusercontent.com/chetankapoor/swap/master/swap.sh -O swap.sh

Then run the script with the following format:

sh swap.sh 2G

For a complete tutorial you can visit:

https://installvirtual.com/shell-script-to-create-swap/

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

From http://docs.python.org/library/csv.html#csv.writer:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with statement to close the file when you're done writing to it.
Tested example below:

from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
    output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
    output.writerow(dict((fn,fn) for fn in headers))
    output.writerows(rows)

HTML input - name vs. id

  • name identifies form fields* ; so they can be shared by controls that stand to represent multiple possibles values for such a field (radio buttons, checkboxes). They will be submitted as keys for form values.
  • id identifies DOM elements ; so they can be targeted by CSS or Javascript.

* names also used to identify local anchors, but this is deprecated and 'id' is a preferred way to do so nowadays.

Passing multiple values to a single PowerShell script parameter

The easiest way is probably to use two parameters: One for hosts (can be an array), and one for vlan.

param([String[]] $Hosts, [String] $VLAN)

Instead of

foreach ($i in $args)

you can use

foreach ($hostName in $Hosts)

If there is only one host, the foreach loop will iterate only once. To pass multiple hosts to the script, pass it as an array:

myScript.ps1 -Hosts host1,host2,host3 -VLAN 2

...or something similar.

Class is not abstract and does not override abstract method

Both classes Rectangle and Ellipse need to override both of the abstract methods.

To work around this, you have 3 options:

  • Add the two methods
  • Make each class that extends Shape abstract
  • Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:

    abstract class Shape {
        // ...
        void draw(Graphics g);
    }
    

And

    class Rectangle extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

Finally

    class Ellipse extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

And you can switch in between them, like so:

    Shape shape = new Ellipse();
    shape.draw(/* ... */);

    shape = new Rectangle();
    shape.draw(/* ... */);

Again, just an example.

A more useful statusline in vim?

What I've found useful is to know which copy/paste buffer (register) is currently active: %{v:register}. Otherwise, my complete status line looks almost exactly like the standard line.

:set statusline=%<%f\ %h%m%r\ %y%=%{v:register}\ %-14.(%l,%c%V%)\ %P

Get values from an object in JavaScript

To access the properties of an object without knowing the names of those properties you can use a for ... in loop:

for(key in data) {
    if(data.hasOwnProperty(key)) {
        var value = data[key];
        //do something with value;
    }
}

What is the meaning of ToString("X2")?

It prints the byte in Hexadecimal format.

No format string: 13

'X2' format string: 0D

http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx

jQuery - Getting the text value of a table cell in the same row as a clicked element

You want .children() instead (documentation here):

$(this).closest('tr').children('td.two').text();

Error: [ng:areq] from angular controller

There's also another way this could happen.

In my app I have a main module that takes care of the ui-router state management, config, and things like that. The actual functionality is all defined in other modules.

I had defined a module

angular.module('account', ['services']);

that had a controller 'DashboardController' in it, but had forgotten to inject it into the main module where I had a state that referenced the DashboardController.

Since the DashboardController wasn't available because of the missing injection, it threw this error.

Looping each row in datagridview

You could loop through DataGridView using Rows property, like:

foreach (DataGridViewRow row in datagridviews.Rows)
{
   currQty += row.Cells["qty"].Value;
   //More code here
}

Share application "link" in Android

Call this method:

public static void shareApp(Context context)
{
    final String appPackageName = context.getPackageName();
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out the App at: https://play.google.com/store/apps/details?id=" + appPackageName);
    sendIntent.setType("text/plain");
    context.startActivity(sendIntent);
}

Tool for comparing 2 binary files in Windows

If you want to find out only whether or not the files are identical, you can use the Windows fc command in binary mode:

fc.exe /b file1 file2

For details, see the reference for fc

Sending and Parsing JSON Objects in Android

you just need to import this

   import org.json.JSONObject;


  constructing the String that you want to send

 JSONObject param=new JSONObject();
 JSONObject post=new JSONObject();

im using two object because you can have an jsonObject within another

post.put("username(here i write the key)","someusername"(here i put the value);
post.put("message","this is a sweet message");
post.put("image","http://localhost/someimage.jpg");
post.put("time":  "present time");

then i put the post json inside another like this

  param.put("post",post);

this is the method that i use to make a request

 makeRequest(param.toString());

public JSONObject makeRequest(String param)
{
    try
    {

setting the connection

        urlConnection = new URL("your url");
        connection = (HttpURLConnection) urlConnection.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
        connection.setReadTimeout(60000);
        connection.setConnectTimeout(60000);
        connection.connect();

setting the outputstream

        dataOutputStream = new DataOutputStream(connection.getOutputStream());

i use this to see in the logcat what i am sending

        Log.d("OUTPUT STREAM  " ,param);
        dataOutputStream.writeBytes(param);
        dataOutputStream.flush();
        dataOutputStream.close();

        InputStream in = new BufferedInputStream(connection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;

here the string is constructed

        while ((line = reader.readLine()) != null)
        {
            result.append(line);
        }

i use this log to see what its comming in the response

         Log.d("INPUTSTREAM: ",result.toString());

instancing a json with the String that contains the server response

        jResponse=new JSONObject(result.toString());

    }
    catch (IOException e) {
        e.printStackTrace();
        return jResponse=null;
    } catch (JSONException e)
    {
        e.printStackTrace();
        return jResponse=null;
    }
    connection.disconnect();
    return jResponse;
}

What is tempuri.org?

Note that namespaces that are in the format of a valid Web URL don't necessarily need to be dereferenced i.e. you don't need to serve actual content at that URL. All that matters is that the namespace is globally unique.

how to change onclick event with jquery?

(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});

I tried $('#'+id).off().on(...), but it wouldn't work to reset the onClick attribute every time it was called to be reset.

I use .on('click',function(){...}); to stay away from having to quote block all my javascript functions.

The O.P. could now use:

$(this).removeAttr('onclick').off('click').on('click', function(){ displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this); });

Where this came through for me is when my div was set with the onClick attribute set statically:

<div onclick = '...'>

Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});.

Without the off('click') my onClick listeners were being appended not replaced.

How to get a path to a resource in a Java JAR file

A File is an abstraction for a file in a filesystem, and the filesystems don't know anything about what are the contents of a JAR.

Try with an URI, I think there's a jar:// protocol that might be useful for your purpouses.

How to change UIButton image in Swift

Swift 5 and ensures the image scales to the size of the button but stays within the buttons bounds.

yourButton.clipsToBounds = true
yourButton.contentMode = .scaleAspectFill

// Use setBackgroundImage or setImage
yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)

Force file download with php using header()

This worked for me like a charm for downloading PNG and PDF.

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_url)); //Absolute URL
ob_clean();
flush();
readfile($file_url); //Absolute URL
exit();

Double precision - decimal places

Decimal representation of floating point numbers is kind of strange. If you have a number with 15 decimal places and convert that to a double, then print it out with exactly 15 decimal places, you should get the same number. On the other hand, if you print out an arbitrary double with 15 decimal places and the convert it back to a double, you won't necessarily get the same value back—you need 17 decimal places for that. And neither 15 nor 17 decimal places are enough to accurately display the exact decimal equivalent of an arbitrary double. In general, you need over 100 decimal places to do that precisely.

See the Wikipedia page for double-precision and this article on floating-point precision.

How to clear variables in ipython?

Apart from the methods mentioned earlier. You can also use the command del to remove multiple variables

del variable1,variable2

How to connect to a docker container from outside the host (same network) [Windows]

This is the most common issue faced by Windows users for running Docker Containers. IMO this is the "million dollar question on Docker"; @"Rocco Smit" has rightly pointed out "inbound traffic for it was disabled by default on my host machine's firewall"; in my case, my McAfee Anti Virus software. I added additional ports to be allowed for inbound traffic from other computers on the same Wifi LAN in the Firewall Settings of McAfee; then it was magic. I had struggled for more than a week browsing all over internet, SO, Docker documentations, Tutorials after Tutorials related to the Networking of Docker, and the many illustrations of "not supported on Windows" for "macvlan", "ipvlan", "user defined bridge" and even this same SO thread couple of times. I even started browsing google with "anybody using Docker in Production?", (yes I know Linux is more popular for Prod workloads compared to Windows servers) as I was not able to access (from my mobile in the same Home wifi) an nginx app deployed in Docker Container on Windows. After all, what good it is, if you cannot access the application (deployed on a Docker Container) from other computers / devices in the same LAN at-least; Ultimately in my case, the issue was just with a firewall blocking inbound traffic;

Converting an integer to binary in C

You can convert decimal to bin, hexa to decimal, hexa to bin, vice-versa etc by following this example. CONVERTING DECIMAL TO BIN

int convert_to_bin(int number){
    int binary = 0, counter = 0;
    while(number > 0){
        int remainder = number % 2;
        number /= 2;
        binary += pow(10, counter) * remainder;
        counter++;
    }   
}

Then you can print binary equivalent like this:

printf("08%d", convert_to_bin(13)); //shows leading zeros

C# Generics and Type Checking

I hope you find this helpful:

  • typeof(IList<T>).IsGenericType == true
  • typeof(IList<T>).GetGenericTypeDefinition() == typeof(IList<>)
  • typeof(IList<int>).GetGenericArguments()[0] == typeof(int)

https://dotnetfiddle.net/5qUZnt

List comprehension vs. lambda + filter

generally filter is slightly faster if using a builtin function.

I would expect the list comprehension to be slightly faster in your case

milliseconds to days

If you don't have another time interval bigger than days:

int days = (int) (milliseconds / (1000*60*60*24));

If you have weeks too:

int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));

It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.

Switch focus between editor and integrated terminal in Visual Studio Code

SIMPLE WINDOWS SOLUTION FOR ANY KEYBOARD LAYOUT (may work for other OS but not tested)

I use a Finnish keyboard so none of the above worked but this should work for all keyboards.

  • Terminal focus: Hover your mouse over the terminal text in the integrated terminal. The shortcut for focusing on the terminal will pop up - mine for example said CTRL+ö.
  • Editor focus: as mentioned above use CTRL+1.

How To Make Circle Custom Progress Bar in Android

I have solved this cool custom progress bar by creating the custom view. I have overriden the onDraw() method to draw the circles, filled arc and text on the canvas.

following is the custom progress bar

import android.annotation.TargetApi;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.graphics.Path;

import android.graphics.Rect;

import android.graphics.RectF;

import android.os.Build;

import android.util.AttributeSet;

import android.view.View;

import com.investorfinder.utils.UiUtils;


public class CustomProgressBar extends View {


private int max = 100;

private int progress;

private Path path = new Path();

int color = 0xff44C8E5;

private Paint paint;

private Paint mPaintProgress;

private RectF mRectF;

private Paint textPaint;

private String text = "0%";

private final Rect textBounds = new Rect();

private int centerY;

private int centerX;

private int swipeAndgle = 0;


public CustomProgressBar(Context context) {
    super(context);
    initUI();
}

public CustomProgressBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    initUI();
}

public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initUI();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    initUI();
}

private void initUI() {
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStrokeWidth(UiUtils.dpToPx(getContext(), 1));
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(color);


    mPaintProgress = new Paint();
    mPaintProgress.setAntiAlias(true);
    mPaintProgress.setStyle(Paint.Style.STROKE);
    mPaintProgress.setStrokeWidth(UiUtils.dpToPx(getContext(), 9));
    mPaintProgress.setColor(color);

    textPaint = new Paint();
    textPaint.setAntiAlias(true);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(color);
    textPaint.setStrokeWidth(2);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
    int viewHeight = MeasureSpec.getSize(heightMeasureSpec);

    int radius = (Math.min(viewWidth, viewHeight) - UiUtils.dpToPx(getContext(), 2)) / 2;

    path.reset();

    centerX = viewWidth / 2;
    centerY = viewHeight / 2;
    path.addCircle(centerX, centerY, radius, Path.Direction.CW);

    int smallCirclRadius = radius - UiUtils.dpToPx(getContext(), 7);
    path.addCircle(centerX, centerY, smallCirclRadius, Path.Direction.CW);
    smallCirclRadius += UiUtils.dpToPx(getContext(), 4);

    mRectF = new RectF(centerX - smallCirclRadius, centerY - smallCirclRadius, centerX + smallCirclRadius, centerY + smallCirclRadius);

    textPaint.setTextSize(radius * 0.5f);
}


@Override
protected void onDraw(Canvas canvas) {


    super.onDraw(canvas);

    canvas.drawPath(path, paint);

    canvas.drawArc(mRectF, 270, swipeAndgle, false, mPaintProgress);

    drawTextCentred(canvas);

}

public void drawTextCentred(Canvas canvas) {

    textPaint.getTextBounds(text, 0, text.length(), textBounds);

    canvas.drawText(text, centerX - textBounds.exactCenterX(), centerY - textBounds.exactCenterY(), textPaint);
}

public void setMax(int max) {
    this.max = max;
}

public void setProgress(int progress) {
    this.progress = progress;

    int percentage = progress * 100 / max;

    swipeAndgle = percentage * 360 / 100;

    text = percentage + "%";

    invalidate();
}

public void setColor(int color) {
    this.color = color;
}
}

In layout XML

<com.your.package.name.CustomProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/txt_title"
            android:layout_marginRight="15dp" />

in activity

CustomProgressBar progressBar = (CustomProgressBar)findViewById(R.id.progress_bar);

    progressBar.setMax(9);

    progressBar.setProgress(5);

using mailto to send email with an attachment

Nope, this is not possible at all. There is no provision for it in the mailto: protocol, and it would be a gaping security hole if it were possible.

The best idea to send a file, but have the client send the E-Mail that I can think of is:

  • Have the user choose a file
  • Upload the file to a server
  • Have the server return a random file name after upload
  • Build a mailto: link that contains the URL to the uploaded file in the message body

Creating a URL in the controller .NET MVC

If you just want to get the path to a certain action, use UrlHelper:

UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("About", "Home", null);

if you want to create a hyperlink:

string link = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, System.Web.Routing.RouteTable.Routes, "My link", "Root", "About", "Home", null, null);

Intellisense will give you the meaning of each of the parameters.


Update from comments: controller already has a UrlHelper:

string url = this.Url.Action("About", "Home", null); 

Can I add jars to maven 2 build classpath without installing them?

This is how we add or install a local jar

    <dependency>
        <groupId>org.example</groupId>
        <artifactId>iamajar</artifactId>
        <version>1.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/lib/iamajar.jar</systemPath>
    </dependency>

i gave some default groupId and artifactId because they are mandatory :)

PHP Get Site URL Protocol - http vs https

it's the best solution of https or http use this :

<?php
$protocol = '//';  
$site_url = $protocol.$_SERVER["HTTP_HOST"];
?>

But can't display https or http, so it only use to link your site content like image, etc.

if want to redirect your site in https, add this code in .htaccess file :

<IfModule mod_rewrite.c>
 RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
 RewriteRule ^(.*)$ https://www.your-domain.com$1 [L]
</IfModule>

Change www.your-domain.com with your dowmain name.

How do I use CMake?

Cmake from Windows terminal:

mkdir build
cd build/
cmake ..
cmake --build . --config Release
./Release/main.exe

The operation cannot be completed because the DbContext has been disposed error

using(var database=new DatabaseEntities()){}

Don't use using statement. Just write like that

DatabaseEntities database=new DatabaseEntities ();{}

It will work.

For documentation on the using statement see here.

Delete many rows from a table using id in Mysql

how about using IN

DELETE FROM tableName
WHERE ID IN (1,2) -- add as many ID as you want.

UTF-8 all the way through

In addition to setting default_charset in php.ini, you can send the correct charset using header() from within your code, before any output:

header('Content-Type: text/html; charset=utf-8');

Working with Unicode in PHP is easy as long as you realize that most of the string functions don't work with Unicode, and some might mangle strings completely. PHP considers "characters" to be 1 byte long. Sometimes this is okay (for example, explode() only looks for a byte sequence and uses it as a separator -- so it doesn't matter what actual characters you look for). But other times, when the function is actually designed to work on characters, PHP has no idea that your text has multi-byte characters that are found with Unicode.

A good library to check into is phputf8. This rewrites all of the "bad" functions so you can safely work on UTF8 strings. There are extensions like the mbstring extension that try to do this for you, too, but I prefer using the library because it's more portable (but I write mass-market products, so that's important for me). But phputf8 can use mbstring behind the scenes, anyway, to increase performance.

Can I force a UITableView to hide the separator between empty cells?

Setting the table's separatorStyle to UITableViewCellSeparatorStyleNone (in code or in IB) should do the trick.

What is the use of a private static variable in Java?

private static variable will be shared in subclass as well. If you changed in one subclass and the other subclass will get the changed value, in which case, it may not what you expect.

public class PrivateStatic {

private static int var = 10;
public void setVar(int newVal) {
    var = newVal;
}

public int getVar() {
    return var;
}

public static void main(String... args) {
    PrivateStatic p1 = new Sub1();
    System.out.println(PrivateStatic.var);
    p1.setVar(200);

    PrivateStatic p2 = new Sub2();
    System.out.println(p2.getVar());
}
}


class Sub1 extends PrivateStatic {

}

class Sub2 extends PrivateStatic {
}

Can an Option in a Select tag carry multiple values?

One way to do this, first one an array, 2nd an object:

    <select name="">
        <option value='{"num_sequence":[0,1,2,3]}'>Option one</option>
        <option value='{"foo":"bar","one":"two"}'>Option two</option>
    </select>

Edited (3 years after answering) to put both values into JSON format (using JSON.stringify()) because of a complaint that my proof-of-concept answer "could confuse a newbie developer."

Could not load file or assembly 'Microsoft.Web.Infrastructure,

Resharper detected Microsoft.Web.Infrastructure as an unused reference an so I deleted it. Locally was working fine but then I got the same error after publishing to dev.

Conclusion, beware when deleting references marked as unused by Resharper

How to select rows with no matching entry in another table?

Here's a simple query:

SELECT t1.ID
FROM Table1 t1
    LEFT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL

The key points are:

  1. LEFT JOIN is used; this will return ALL rows from Table1, regardless of whether or not there is a matching row in Table2.

  2. The WHERE t2.ID IS NULL clause; this will restrict the results returned to only those rows where the ID returned from Table2 is null - in other words there is NO record in Table2 for that particular ID from Table1. Table2.ID will be returned as NULL for all records from Table1 where the ID is not matched in Table2.

Is it possible to use an input value attribute as a CSS selector?

Sure, try:

input[value="United States"]{ color: red; }

jsFiddle example.

Android: Difference between Parcelable and Serializable?

Serializable

Serializable is a markable interface or we can call as an empty interface. It doesn’t have any pre-implemented methods. Serializable is going to convert an object to byte stream. So the user can pass the data between one activity to another activity. The main advantage of serializable is the creation and passing data is very easy but it is a slow process compare to parcelable.

Parcelable

Parcel able is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn’t create more temp objects while passing the data between two activities.

How to make shadow on border-bottom?

The issue is shadow coming out the side of the containing div. In order to avoid this, the blur value must equal the absolute value of the spread value.

_x000D_
_x000D_
div {_x000D_
  -webkit-box-shadow: 0 4px 6px -6px #222;_x000D_
  -moz-box-shadow: 0 4px 6px -6px #222;_x000D_
  box-shadow: 0 4px 6px -6px #222;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

covered in depth here

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

MySQL - UPDATE query based on SELECT Query

I had an issue with duplicate entries in one table itself. Below is the approaches were working for me. It has also been advocated by @sibaz.

Finally I solved it using the below queries:

  1. The select query is saved in a temp table

    IF OBJECT_ID(N'tempdb..#New_format_donor_temp', N'U') IS NOT NULL
        DROP TABLE #New_format_donor_temp;
    
    select *
    into #New_format_donor_temp
    from DONOR_EMPLOYMENTS
    where DONOR_ID IN (
      1, 2
    )
    
    -- Test New_format_donor_temp
    -- SELECT *
    -- FROM #New_format_donor_temp;
    
  2. The temp table is joined in the update query.

    UPDATE de
    SET STATUS_CD=de_new.STATUS_CD, STATUS_REASON_CD=de_new.STATUS_REASON_CD, TYPE_CD=de_new.TYPE_CD
    FROM DONOR_EMPLOYMENTS AS de
      INNER JOIN #New_format_donor_temp AS de_new ON de_new.EMP_NO = de.EMP_NO
    WHERE
      de.DONOR_ID IN (
        3, 4
    )
    

I not very experienced with SQL please advise any better approach you know.

Above queries are for MySql server.

Javascript parse float is ignoring the decimals after my comma

Why not use globalize? This is only one of the issues that you can run in to when you don't use the english language:

Globalize.parseFloat('0,04'); // 0.04

Some links on stackoverflow to look into:

How to use a different version of python during NPM install?

set python to python2.7 before running npm install

Linux:

export PYTHON=python2.7

Windows:

set PYTHON=python2.7

git remove merge commit from history

There are two ways to tackle this based on what you want:

Solution 1: Remove purple commits, preserving history (incase you want to roll back)

git revert -m 1 <SHA of merge>

-m 1 specifies which parent line to choose

Purple commits will still be there in history but since you have reverted, you will not see code from those commits.


Solution 2: Completely remove purple commits (disruptive change if repo is shared)

git rebase -i <SHA before branching out>

and delete (remove lines) corresponding to purple commits.

This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase.

How can I get the source code of a Python function?

While I'd generally agree that inspect is a good answer, I'd disagree that you can't get the source code of objects defined in the interpreter. If you use dill.source.getsource from dill, you can get the source of functions and lambdas, even if they are defined interactively. It also can get the code for from bound or unbound class methods and functions defined in curries... however, you might not be able to compile that code without the enclosing object's code.

>>> from dill.source import getsource
>>> 
>>> def add(x,y):
...   return x+y
... 
>>> squared = lambda x:x**2
>>> 
>>> print getsource(add)
def add(x,y):
  return x+y

>>> print getsource(squared)
squared = lambda x:x**2

>>> 
>>> class Foo(object):
...   def bar(self, x):
...     return x*x+x
... 
>>> f = Foo()
>>> 
>>> print getsource(f.bar)
def bar(self, x):
    return x*x+x

>>> 

How to set "value" to input web element using selenium?

As Shubham Jain stated, this is working to me: driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"??, "new value");

Border color on default input style

You can use jquery for this by utilizing addClass() method

CSS

 .defaultInput
    {
     width: 100px;
     height:25px;
     padding: 5px;
    }

.error
{
 border:1px solid red;
}

<input type="text" class="defaultInput"/>

Jquery Code

$(document).ready({
  $('.defaultInput').focus(function(){
       $(this).addClass('error');
  });
});

Update: You can remove that error class using

$('.defaultInput').removeClass('error');

It won't remove that default style. It will remove .error class only

How to set the value for Radio Buttons When edit?

When you populate your fields, you can check for the value:

<input type="radio" name="sex" value="Male" <?php echo ($sex=='Male')?'checked':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=='Female')?'checked':'' ?> size="17">Female

Assuming that the value you return from your database is in the variable $sex

The checked property will preselect the value that match

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

git push -u origin master

… is the same as:

git push origin master ; git branch --set-upstream master origin/master

Do the last statement, if you forget the -u!

Or you could force it:

git config branch.master.remote origin
git config branch.master.merge refs/heads/master

If you let the command do it for you, it will pick your mistakes like if you typed a non-existent branch or you didn't git remote add; though that might be what you want. :)

Why can't I have "public static const string S = "stuff"; in my Class?

A const member is considered static by the compiler, as well as implying constant value semantics, which means references to the constant might be compiled into the using code as the value of the constant member, instead of a reference to the member.

In other words, a const member containing the value 10, might get compiled into code that uses it as the number 10, instead of a reference to the const member.

This is different from a static readonly field, which will always be compiled as a reference to the field.

Note, this is pre-JIT. When the JIT'ter comes into play, it might compile both these into the target code as values.

how to change namespace of entire project?

When renaming a project, it's a simple process

  • Rename your project
  • Edit project properties to have new Default Namespace value
  • Find/Replace all "namespace OLD" and "using OLD" statements in your solution
  • Manually edit .sln file in text editor and replace your old project name in the directory structure with your new project name.
  • Reload solution when VS prompts

SQLAlchemy ORDER BY DESCENDING?

from sqlalchemy import desc
someselect.order_by(desc(table1.mycol))

Usage from @jpmc26

TypeError: Converting circular structure to JSON in nodejs

I also ran into this issue. It was because I forgot to await for a promise.

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

install certificate in java linux

/opt/jdk(version)/bin/keytool -import -alias aliasname -file certificate.cer -keystore cacerts -storepass password

IIS7 URL Redirection from root to sub directory

I think, this could be done without IIS URL Rewrite module. <httpRedirect> supports wildcards, so you can configure it this way:

  <system.webServer>
    <httpRedirect enabled="true">
      <add wildcard="/" destination="/menu_1/MainScreen.aspx" />
    </httpRedirect>
  </system.webServer>

Note that you need to have the "HTTP Redirection" feature enabled on IIS - see HTTP Redirects

retrieve links from web page using python and BeautifulSoup

import urllib2
from bs4 import BeautifulSoup
a=urllib2.urlopen('http://dir.yahoo.com')
code=a.read()
soup=BeautifulSoup(code)
links=soup.findAll("a")
#To get href part alone
print links[0].attrs['href']

SSRS - Checking whether the data is null

Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).

Either way works, I like to put that logic in the query so the report has to do less.

How to convert comma-separated String to List?

List commaseperated = new ArrayList();
String mylist = "item1 , item2 , item3";
mylist = Arrays.asList(myStr.trim().split(" , "));

// enter code here

Cannot refer to a non-final variable inside an inner class defined in a different method

use ClassName.this.variableName to reference the non-final variable

How do I print the type or class of a variable in Swift?

You can still access the class, through className (which returns a String).

There are actually several ways to get the class, for example classForArchiver, classForCoder, classForKeyedArchiver (all return AnyClass!).

You can't get the type of a primitive (a primitive is not a class).

Example:

var ivar = [:]
ivar.className // __NSDictionaryI

var i = 1
i.className // error: 'Int' does not have a member named 'className'

If you want to get the type of a primitive, you have to use bridgeToObjectiveC(). Example:

var i = 1
i.bridgeToObjectiveC().className // __NSCFNumber

Creating a file name as a timestamp in a batch job

This will ensure that the output is a 2-digit value...you can rearrange the output to your liking and test by un-commenting the diagnostics section. Enjoy!

(I borrowed a lot of this from other forums...)

:: ------------------ Date and Time Modifier ------------------------

@echo off
setlocal

:: THIS CODE WILL DISPLAY A 2-DIGIT TIMESTAMP FOR USE IN APPENDING FILENAMES

:: CREATE VARIABLE %TIMESTAMP%

for /f "tokens=1-8 delims=.:/-, " %%i in ('echo exit^|cmd /q /k"prompt $D $T"') do (
   for /f "tokens=2-4 skip=1 delims=/-,()" %%a in ('echo.^|date') do (
set dow=%%i
set %%a=%%j
set %%b=%%k
set %%c=%%l
set hh=%%m
set min=%%n
set sec=%%o
set hsec=%%p
)
)

:: ensure that hour is always 2 digits

if %hh%==0 set hh=00
if %hh%==1 set hh=01
if %hh%==2 set hh=02
if %hh%==3 set hh=03
if %hh%==4 set hh=04
if %hh%==5 set hh=05
if %hh%==6 set hh=06
if %hh%==7 set hh=07
if %hh%==8 set hh=08
if %hh%==9 set hh=09


:: --------- TIME STAMP DIAGNOSTICS -------------------------

:: Un-comment these lines to test output

:: echo dayOfWeek = %dow%
:: echo year = %yy%
:: echo month = %mm%
:: echo day = %dd%
:: echo hour = %hh%
:: echo minute = %min%
:: echo second = %sec%
:: echo hundredthsSecond = %hsec%
:: echo.
:: echo Hello! 
:: echo Today is %dow%, %mm%/%dd%. 
:: echo.
:: echo. 
:: echo.
:: echo.
:: pause

:: --------- END TIME STAMP DIAGNOSTICS ----------------------

:: assign timeStamp:
:: Add the date and time parameters as necessary - " yy-mm-dd-dow-min-sec-hsec "

endlocal & set timeStamp=%yy%%mm%%dd%_%hh%-%min%-%sec%
echo %timeStamp%

How can you get the Manifest Version number from the App's (Layout) XML variables?

I solved this issue by extending the Preference class.

package com.example.android;

import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;

public class VersionPreference extends Preference {
    public VersionPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        String versionName;
        final PackageManager packageManager = context.getPackageManager();
        if (packageManager != null) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                versionName = null;
            }
            setSummary(versionName);
        }
    }
}

Then in my preferences XML:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <com.example.android.VersionPreference android:title="Version" />
</PreferenceScreen>

Convert datatable to JSON in C#

//Common DLL client, server
public class transferDataTable
{
    public class myError
    {
        public string Message { get; set; }
        public int Code { get; set; }
    }

    public myError Error { get; set; }
    public List<string> ColumnNames { get; set; }
    public List<string> DataTypes { get; set; }
    public List<Object> Data { get; set; }
    public int Count { get; set; }
}

public static class ExtensionMethod
{
    public static transferDataTable LoadData(this transferDataTable transfer, DataTable dt)
    {
        if (dt != null)
        {
            transfer.DataTypes = new List<string>();
            transfer.ColumnNames = new List<string>();                
            foreach (DataColumn c in dt.Columns)
            {
                transfer.ColumnNames.Add(c.ColumnName);
                transfer.DataTypes.Add(c.DataType.ToString());
            }

            transfer.Data = new List<object>();
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn col in dt.Columns)
                {
                    transfer.Data.Add(dr[col] == DBNull.Value ? null : dr[col]);
                }
            }
            transfer.Count = dt.Rows.Count;
        }            
        return transfer;
    }        

    public static DataTable GetDataTable(this transferDataTable transfer, bool ConvertToLocalTime = true)
    {
        if (transfer.Error != null || transfer.ColumnNames == null || transfer.DataTypes == null || transfer.Data == null)
            return null;

        int columnsCount = transfer.ColumnNames.Count;
        DataTable dt = new DataTable();
        for (int i = 0; i < columnsCount; i++ )
        {
            Type colType = Type.GetType(transfer.DataTypes[i]);
            dt.Columns.Add(new DataColumn(transfer.ColumnNames[i], colType));
        }

        int index = 0;
        DataRow row = dt.NewRow();
        foreach (object o in transfer.Data)
        {
            if (ConvertToLocalTime && o != null && o.GetType() == typeof(DateTime))
            {
                DateTime dat = Convert.ToDateTime(o);
                row[index] = dat.ToLocalTime();
            }
            else
                row[index] = o == null ? DBNull.Value : o;

            index++;

            if (columnsCount == index)
            {
                index = 0;
                dt.Rows.Add(row);
                row = dt.NewRow();
            }
        }
        return dt;
    }
}

//Server
    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "json/data")]
    transferDataTable _Data();

    public transferDataTable _Data()
    {
        try
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["myConnString"]))
            {
                con.Open();
                DataSet ds = new DataSet();
                SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT * FROM tbGalleries", con);
                myAdapter.Fill(ds, "table");
                DataTable dt = ds.Tables["table"];
                return new transferDataTable().LoadData(dt);
            }
        }
        catch(Exception ex)
        {
            return new transferDataTable() { Error = new transferDataTable.myError() { Message = ex.Message, Code = ex.HResult } };
        }
    }

//Client
        Response = Vossa.getAPI(serviceUrl + "json/data");
        transferDataTable transfer = new JavaScriptSerializer().Deserialize<transferDataTable>(Response);
        if (transfer.Error == null)
        {
            DataTable dt = transfer.GetDataTable();
            dbGrid.ItemsSource = dt.DefaultView;
        }
        else
            MessageBox.Show(transfer.Error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

log4j:WARN No appenders could be found for logger in web.xml

OK, I see a lot of answer and some very correct. However, none fixed my problem. The problem in my case was the UNIX filesystem permissions had the log4j.properties file I was editing on the server as owned by root. and readable by only root. However, the web application I was deploying was to tomcat couldn't read the file as tomcat runs as user tomcat on Linux systems by default. Hope this helps. so the solution was typing 'chown tomcat:tomcat log4j.properties' in the directory where the log4j.properties file resides.

Removing object properties with Lodash

You can approach it from either an "allow list" or a "block list" way:

// Block list
// Remove the values you don't want
var result = _.omit(credentials, ['age']);

// Allow list
// Only allow certain values
var result = _.pick(credentials, ['fname', 'lname']);

If it's reusable business logic, you can partial it out as well:

// Partial out a "block list" version
var clean = _.partial(_.omit, _, ['age']);

// and later
var result = clean(credentials);

Note that Lodash 5 will drop support for omit

A similar approach can be achieved without Lodash:

const transform = (obj, predicate) => {
  return Object.keys(obj).reduce((memo, key) => {
    if(predicate(obj[key], key)) {
      memo[key] = obj[key]
    }
    return memo
  }, {})
}

const omit = (obj, items) => transform(obj, (value, key) => !items.includes(key))

const pick = (obj, items) => transform(obj, (value, key) => items.includes(key))

// Partials
// Lazy clean
const cleanL = (obj) => omit(obj, ['age'])

// Guarded clean
const cleanG = (obj) => pick(obj, ['fname', 'lname'])


// "App"
const credentials = {
    fname:"xyz",
    lname:"abc",
    age:23
}

const omitted = omit(credentials, ['age'])
const picked = pick(credentials, ['age'])
const cleanedL = cleanL(credentials)
const cleanedG = cleanG(credentials)

Request Monitoring in Chrome

You could use Fiddler which is a good free tool.

Force encode from US-ASCII to UTF-8 (iconv)

People say you can't and I understand you may be frustrated when asking a question and getting such an answer.

If you really want it to show in UTF-8 instead of US ASCII then you need to do it in two steps.

First:

iconv -f us-ascii -t utf-16 yourfile > youfileinutf16.*

Second:

iconv -f utf-16le -t utf-8 yourfileinutf16 > yourfileinutf8.*

Then if you do a file -i, you'll see the new character set is UTF-8.

What is the maximum possible length of a query string?

Different web stacks do support different lengths of http-requests. I know from experience that the early stacks of Safari only supported 4000 characters and thus had difficulty handling ASP.net pages because of the USER-STATE. This is even for POST, so you would have to check the browser and see what the stack limit is. I think that you may reach a limit even on newer browsers. I cannot remember but one of them (IE6, I think) had a limit of 16-bit limit, 32,768 or something.

How to get bean using application context in spring boot

You can Autowire the ApplicationContext, either as a field

@Autowired
private ApplicationContext context;

or a method

@Autowired
public void context(ApplicationContext context) { this.context = context; }

Finally use

context.getBean(SomeClass.class)

SQL Switch/Case in 'where' clause

Try this:

WHERE (
    @smartLocationType IS NULL 
    OR account_location = (
         CASE
            WHEN @smartLocationType IS NOT NULL 
                 THEN @smartLocationType
            ELSE account_location 
         END
    )
)

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

No mapping found for HTTP request with URI.... in DispatcherServlet with name

I also faced the same issue, but after putting the namespace below, it works fine:

xmlns:mvc="http://www.springframework.org/schema/mvc" 

Eclipse doesn't stop at breakpoints

In my case I had to enable then disable an option in the Preferences. I don't prefer the debug view to keep jumping when a breakpoint is hit so I disabled this option, but caused the issue in question.

The solution was to enable it again, start a debug session, the breakpoint is hit and shown in the UI, then disable again the option.

Looks like a bug in Eclipse 4.17

enter image description here

UPDATE

There is also another simpler way that will make Eclipse show the debugging highlight at the breakpoint or rather refresh the debugging UI to work as it should. After the breakpoint is reached, Eclipse will ask you to switch to debugging mode if you are not already in, click switch button, then activate the debug tab/view, you will notice that the stepping buttons are activated and the breakpoint line is highlighted.

$('body').on('click', '.anything', function(){})

If you want to capture click on everything then do

$("*").click(function(){
//code here
}

I use this for selector: http://api.jquery.com/all-selector/

This is used for handling clicks: http://api.jquery.com/click/

And then use http://api.jquery.com/event.preventDefault/

To stop normal clicking actions.

What is the best way to add options to a select from a JavaScript object with jQuery?

jQuery

var list = $("#selectList");
$.each(items, function(index, item) {
  list.append(new Option(item.text, item.value));
});

Vanilla JavaScript

var list = document.getElementById("selectList");
for(var i in items) {
  list.add(new Option(items[i].text, items[i].value));
}

How to pick element inside iframe using document.getElementById

(this is to add to the chosen answer)

Make sure the iframe is loaded before you

contentWindow.document

Otherwise, your getElementById will be null.

PS: Can't comment, still low reputation to comment, but this is a follow-up on the chosen answer as I've spent some good debugging time trying to figure out I should force the iframe load before selecting the inner-iframe element.

Is it possible to animate scrollTop with jQuery?

You can use the jQuery animation for scroll page with a specific duration:

$("html, body").animate({scrollTop: "1024px"}, 5000);

where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.

Why can't I change my input value in React even with the onChange listener

If you would like to handle multiple inputs with one handler take a look at my approach where I'm using computed property to get value of the input based on it's name.

import React, { useState } from "react";
import "./style.css";

export default function App() {
  const [state, setState] = useState({
    name: "John Doe",
    email: "[email protected]"
  });

  const handleChange = e => {
    setState({
      [e.target.name]: e.target.value
    });
  };

  return (
    <div>
      <input
        type="text"
        className="name"
        name="name"
        value={state.name}
        onChange={handleChange}
      />

      <input
        type="text"
        className="email"
        name="email"
        value={state.email}
        onChange={handleChange}
      />
    </div>
  );
}

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

for eg if CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci replace it to CHARSET=latin1 and remove the collate

You are good to go

How can I reference a dll in the GAC from Visual Studio?

In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go

EDIT:

That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.

How to include clean target in Makefile?

In makefile language $@ means "name of the target", so rm -f $@ translates to rm -f clean.

You need to specify to rm what exactly you want to delete, like rm -f *.o code1 code2

What data type to use in MySQL to store images?

This can be done from the command line. This will create a column for your image with a NOT NULL property.

CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB; 

From here

Popup window in winform c#

i am using this method.

add a from that you want to pop up, add all controls you need. in the code you can handle the user input and return result to the caller. for pop up the form just create a new instance of the form and show method.

/* create new form instance. i am overriding constructor to allow the caller form to set the form header */ 
var t = new TextPrompt("Insert your message and click Send button");
// pop up the form
t.Show();
if (t.DialogResult == System.Windows.Forms.DialogResult.OK)
{ 
  MessageBox.Show("RTP", "Message sent to user"); 
}

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

How to remove element from array in forEach loop?

Although Xotic750's answer provides several good points and possible solutions, sometimes simple is better.

You know the array being iterated on is being mutated in the iteration itself (i.e. removing an item => index changes), thus the simplest logic is to go backwards in an old fashioned for (à la C language):

_x000D_
_x000D_
let arr = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];_x000D_
_x000D_
for (let i = arr.length - 1; i >= 0; i--) {_x000D_
  if (arr[i] === 'a') {_x000D_
    arr.splice(i, 1);_x000D_
  }_x000D_
}_x000D_
_x000D_
document.body.append(arr.join());
_x000D_
_x000D_
_x000D_

If you really think about it, a forEach is just syntactic sugar for a for loop... So if it's not helping you, just please stop breaking your head against it.

Server is already running in Rails

$ lsof -wni tcp:3000

# Kill the running process
$ kill -9 5946

$ rm tmp/server.pids

foreman start etc start the service

Android Studio 3.0 Execution failed for task: unable to merge dex

Same problem. I have enabled multidex: defaultConfig { applicationId "xxx.xxx.xxxx" minSdkVersion 24 targetSdkVersion 26 multiDexEnabled true

I have cleared cache, ran gradle clean, rebuild, make, tried to make sure no conflicts in imported libraries (Removed all transitive dependencies) and made all updates. Still:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'. java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Turns out the build did not like: implementation 'org.slf4j:slf4j-android:1.7.21'

How do I execute a PowerShell script automatically using Windows task scheduler?

Instead of only using the path to your script in the task scheduler, you should start PowerShell with your script in the task scheduler, e.g.

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -File "C:\Path\To\Your\PS1File.ps1"

See powershell /? for an explanation of those switches.

If you still get problems you should read this question.

Test if object implements interface

For the instance:

if (obj is IMyInterface) {}

For the class:

Check if typeof(MyClass).GetInterfaces() contains the interface.

Global variables in R

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

How to place two forms on the same page?

Well you can have each form go to to a different page. (which is preferable)

Or have a different value for the a certain input and base posts on that:

switch($_POST['submit']) {
    case 'login': 
    //...
    break;
    case 'register':
    //...
    break;
}

Random word generator- Python

There is a package random_word could implement this request very conveniently:

 $ pip install random-word

from random_word import RandomWords
r = RandomWords()

# Return a single random word
r.get_random_word()
# Return list of Random words
r.get_random_words()
# Return Word of the day
r.word_of_the_day()

Rails Root directory path?

In addition to all the other correct answers, since Rails.root is a Pathname object, this won't work:

Rails.root + '/app/assets/...'

You could use something like join

Rails.root.join('app', 'assets')

If you want a string use this:

Rails.root.join('app', 'assets').to_s

How do I calculate someone's age based on a DateTime type birthday?

I've made one small change to Mark Soen's answer: I've rewriten the third line so that the expression can be parsed a bit more easily.

public int AgeInYears(DateTime bday)
{
    DateTime now = DateTime.Today;
    int age = now.Year - bday.Year;            
    if (bday.AddYears(age) > now) 
        age--;
    return age;
}

I've also made it into a function for the sake of clarity.

Importing CSV data using PHP/MySQL

i think the main things to remember about parsing csv is that it follows some simple rules:

a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns

have a read of this post to see what i am talking about

it's actually very easy to do once you have the hang of it and becomes very useful.

Difference between logger.info and logger.debug

I suggest you look at the article called "Short Introduction to log4j". It contains a short explanation of log levels and demonstrates how they can be used in practice. The basic idea of log levels is that you want to be able to configure how much detail the logs contain depending on the situation. For example, if you are trying to troubleshoot an issue, you would want the logs to be very verbose. In production, you might only want to see warnings and errors.

The log level for each component of your system is usually controlled through a parameter in a configuration file, so it's easy to change. Your code would contain various logging statements with different levels. When responding to an Exception, you might call Logger.error. If you want to print the value of a variable at any given point, you might call Logger.debug. This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.

In the case of log4j at least, the ordering of log levels is:

DEBUG < INFO < WARN < ERROR < FATAL

Here is a short example from that article demonstrating how log levels work.

   // get a logger instance named "com.foo"
   Logger logger = Logger.getLogger("com.foo");

   // Now set its level. Normally you do not need to set the
   // level of a logger programmatically. This is usually done
   // in configuration files.
   logger.setLevel(Level.INFO);

   Logger barlogger = Logger.getLogger("com.foo.Bar");

   // This request is enabled, because WARN >= INFO.
   logger.warn("Low fuel level.");

   // This request is disabled, because DEBUG < INFO.
   logger.debug("Starting search for nearest gas station.");

   // The logger instance barlogger, named "com.foo.Bar",
   // will inherit its level from the logger named
   // "com.foo" Thus, the following request is enabled
   // because INFO >= INFO.
   barlogger.info("Located nearest gas station.");

   // This request is disabled, because DEBUG < INFO.
   barlogger.debug("Exiting gas station search");

Return value of x = os.system(..)

os.system('command') returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

Refer my answer for more detail in What is the return value of os.system() in Python?

Regex to check if valid URL that ends in .jpg, .png, or .gif

(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png) worked really well for me.

This will match URLs in the following forms:

https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.jpg
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.jpg
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.gif
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.gif
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.png
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.png

Check this regular expression against the URLs here: http://regexr.com/3g1v7

Xcode 4: How do you view the console?

You can always see the console in a different window by opening the Organiser, clicking on the Devices tab, choosing your device and selecting it's console.

Of course, this doesn't work for the simulator :(

How can I check the current status of the GPS receiver?

If you just need to know if there's a fix, then check for the last known location provided by the GPS receiver and check the .getTime() value to know how old is that. If it's recent enough (like... a few seconds) you have a fix.

   LocationManager lm = (LocationManager)context.getSystemService(LOCATION_SERVICE); 
   Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

   // Get the time of the last fix
   long lastFixTimeMillis = loc.getTime(); 

... and finally compare that to current date time (In UTC!). If it's recent enough you have a fix.

I do that in my app and so far so good.

How to run Rake tasks from within Rake tasks?

task :invoke_another_task do
  # some code
  Rake::Task["another:task"].invoke
end

When to use pthread_exit() and when to use pthread_join() in Linux?

As explained in the openpub documentations,

pthread_exit() will exit the thread that calls it.

In your case since the main calls it, main thread will terminate whereas your spawned threads will continue to execute. This is mostly used in cases where the main thread is only required to spawn threads and leave the threads to do their job

pthread_join will suspend execution of the thread that has called it unless the target thread terminates

This is useful in cases when you want to wait for thread/s to terminate before further processing in main thread.

What is so bad about singletons?

Singleton is a pattern and can be used or abused just like any other tool.

The bad part of a singleton is generally the user (or should I say the inappropriate use of a singleton for things it is not designed to do). The biggest offender is using a singleton as a fake global variable.

convert array into DataFrame in Python

You can add parameter columns or use dict with key which is converted to column name:

np.random.seed(123)
e = np.random.normal(size=10)  
dataframe=pd.DataFrame(e, columns=['a']) 
print (dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

e_dataframe=pd.DataFrame({'a':e}) 
print (e_dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You don't always want your instance variables to be fully accessible from outside of the class. There are plenty of cases where allowing read access to an instance variable makes sense, but writing to it might not (e.g. a model that retrieves data from a read-only source). There are cases where you want the opposite, but I can't think of any that aren't contrived off the top of my head.

Data binding for TextBox

We can use following code

textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

Where

  • "Text" – the property of textbox
  • model – the model object enter code here
  • "Name" – the value of model which to bind the textbox.

VBA macro that search for file in multiple subfolders

This sub will populate a Collection with all files matching the filename or pattern you pass in.

Sub GetFiles(StartFolder As String, Pattern As String, _
             DoSubfolders As Boolean, ByRef colFiles As Collection)

    Dim f As String, sf As String, subF As New Collection, s
    
    If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
    
    f = Dir(StartFolder & Pattern)
    Do While Len(f) > 0
        colFiles.Add StartFolder & f
        f = Dir()
    Loop
    
    If DoSubfolders then
        sf = Dir(StartFolder, vbDirectory)
        Do While Len(sf) > 0
            If sf <> "." And sf <> ".." Then
                If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
                        subF.Add StartFolder & sf
                End If
            End If
            sf = Dir()
        Loop
    
        For Each s In subF
            GetFiles CStr(s), Pattern, True, colFiles
        Next s
    End If

End Sub

Usage:

Dim colFiles As New Collection

GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
    'work with found files
End If

how to generate web service out of wsdl

You can generate the WS proxy classes using WSCF (Web Services Contract First) tool from thinktecture.com. So essentially, YOU CAN create webservices from wsdl's. Creating the asmx's, maybe not, but that's the easy bit isn't it? This tool integrates brilliantly into VS2005-8 (new version for 2010/WCF called WSCF-blue). I've used it loads and always found it to be really good.

How to pass arguments and redirect stdin from a file to program run in gdb?

If you want to have bare run command in gdb to execute your program with redirections and arguments, you can use set args:

% gdb ./a.out
(gdb) set args arg1 arg2 <file
(gdb) run

I was unable to achieve the same behaviour with --args parameter, gdb fiercely escapes the redirections, i.e.

% gdb --args echo 1 2 "<file"
(gdb) show args
Argument list to give program being debugged when it is started is "1 2 \<file".
(gdb) run
...
1 2 <file
...

This one actually redirects the input of gdb itself, not what we really want here

% gdb --args echo 1 2 <file
zsh: no such file or directory: file

Reverse engineering from an APK file to a project

First of all I recommend this video may this is clears all yours doubts

If not please go through it

Procedure for decoding .apk files, step-by-step method:

Step 1:

Make a new folder and put .apk file in it (which you want to decode). Now rename the extension of this .apk file to .zip (eg.: rename from filename.apk to filename.zip) and save it.

If problems in the converting into .zip please refers link

After getting .zip now you get classes.dex files, etc. At this stage you are able to see drawable but not xml and java files, so continue. If you don’t see the extensions go through check the configuration

Step 2:

Now extract this zip apk file in the same folder. Now download dex2jar from this link

and extract it to the same folder. Now open command prompt and change directory to that folder.

Then write dex2jar classes.dex and press enter. Now you get classes.dex.dex2jar file in the same folder.

Then download java decompiler

And now double click on jd-gui and click on open file. Then open classes.dex.dex2jar file from that folder. Now you get class files and save all these class files (click on file then click "save all sources" in jd-gui) by src name. Extract that zip file (classes_dex2jar.src.zip) and you will get all java files of the application.

At this stage you get java source but the xml files are still unreadable, so continue.

Step 3:

Now open another new folder and put these files

  1. put .apk file which you want to decode

  2. download Apktool for windows v1.x And Apktool

install window using google and put in the same folder

  1. download framework-res.apk file using google and put in the same folder (Not all apk file need framework-res.apk file)

  2. Open a command window

  3. Navigate to the root directory of APKtool and type the following command: apktool if framework-res.apk.

Above command should result in Framework installed ....

  1. apktool d "appName".apk ("appName" denotes application which you want to decode) now you get a file folder in that folder and now you can easily read xml files also.

Step 4: Finally we got the res/ as well as java code of project which is our target at starting.

P.S. If you are not able to get res folder by above steps please do install new apktool

  • Is Java 1.7 installed? Install Apktool 2.x
  • Is Java 1.6 or higher installed? Install Apktool 1.x

Enjoy and happy coding

What do we mean by Byte array?

I assume you know what a byte is. A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

Just as bytes can encode different types and ranges of data (numbers from 0 to 255, numbers from -128 to 127, single characters using ASCII e.g. 'a' or '%', CPU op-codes), each byte in a byte array may be any of these things, or contribute to some multi-byte values such as numbers with larger range (e.g. 16-bit unsigned int from 0..65535), international character sets, textual strings ("hello"), or part/all of a compiled computer programs.

The crucial thing about a byte array is that it gives indexed (fast), precise, raw access to each 8-bit value being stored in that part of memory, and you can operate on those bytes to control every single bit. The bad thing is the computer just treats every entry as an independent 8-bit number - which may be what your program is dealing with, or you may prefer some powerful data-type such as a string that keeps track of its own length and grows as necessary, or a floating point number that lets you store say 3.14 without thinking about the bit-wise representation. As a data type, it is inefficient to insert or remove data near the start of a long array, as all the subsequent elements need to be shuffled to make or fill the gap created/required.

Validate SSL certificates with Python

M2Crypto can do the validation. You can also use M2Crypto with Twisted if you like. The Chandler desktop client uses Twisted for networking and M2Crypto for SSL, including certificate validation.

Based on Glyphs comment it seems like M2Crypto does better certificate verification by default than what you can do with pyOpenSSL currently, because M2Crypto checks subjectAltName field too.

I've also blogged on how to get the certificates Mozilla Firefox ships with in Python and usable with Python SSL solutions.

How to disable keypad popup when on edittext?

For Xamarin Users:

[Activity(MainLauncher = true, 
        ScreenOrientation = ScreenOrientation.Portrait, 
        WindowSoftInputMode = SoftInput.StateHidden)] //SoftInput.StateHidden - disables keyboard autopop

Location Services not working in iOS 8

My solution which can be compiled in Xcode 5:

#ifdef __IPHONE_8_0
    NSUInteger code = [CLLocationManager authorizationStatus];
    if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) {
        // choose one request according to your business.
        if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){
            [self.locationManager requestAlwaysAuthorization];
        } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
            [self.locationManager  requestWhenInUseAuthorization];
        } else {
            NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
        }
    }
#endif
    [self.locationManager startUpdatingLocation];

MySQL date formats - difficulty Inserting a date

Looks like you've not encapsulated your string properly. Try this:

INSERT INTO custorder VALUES ('Kevin','yes'), STR_TO_DATE('1-01-2012', '%d-%m-%Y');

Alternatively, you can do the following but it is not recommended. Make sure that you use STR_TO-DATE it is because when you are developing web applications you have to explicitly convert String to Date which is annoying. Use first One.

INSERT INTO custorder VALUES ('Kevin','yes'), '2012-01-01';

I'm not confident that the above SQL is valid, however, and you may want to move the date part into the brackets. If you can provide the exact error you're getting, I might be able to more directly help with the issue.

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

UPDATE 2014-11-14: The solution below is too old, I recommend using flex box layout method. Here is a overview: http://learnlayout.com/flexbox.html


My solution

html

<li class="grid-list-header row-cw row-cw-msg-list ...">
  <div class="col-md-1 col-cw col-cw-name">
  <div class="col-md-1 col-cw col-cw-keyword">
  <div class="col-md-1 col-cw col-cw-reply">
  <div class="col-md-1 col-cw col-cw-action">
</li>

<li class="grid-list-item row-cw row-cw-msg-list ...">
  <div class="col-md-1 col-cw col-cw-name">
  <div class="col-md-1 col-cw col-cw-keyword">
  <div class="col-md-1 col-cw col-cw-reply">
  <div class="col-md-1 col-cw col-cw-action">
</li>

scss

.row-cw {
  position: relative;
}

.col-cw {
  position: absolute;
  top: 0;
}


.ir-msg-list {

  $col-reply-width: 140px;
  $col-action-width: 130px;

  .row-cw-msg-list {
    padding-right: $col-reply-width + $col-action-width;
  }

  .col-cw-name {
    width: 50%;
  }

  .col-cw-keyword {
    width: 50%;
  }

  .col-cw-reply {
    width: $col-reply-width;
    right: $col-action-width;
  }

  .col-cw-action {
    width: $col-action-width;
    right: 0;
  }
}

Without modify too much bootstrap layout code.


Update (not from OP): adding code snippet below to facilitate understanding of this answer. But it doesn't seem to work as expected.

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
.row-cw {_x000D_
  position: relative;_x000D_
  height: 20px;_x000D_
}_x000D_
.col-cw {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  background-color: rgba(150, 150, 150, .5);_x000D_
}_x000D_
.row-cw-msg-list {_x000D_
  padding-right: 270px;_x000D_
}_x000D_
.col-cw-name {_x000D_
  width: 50%;_x000D_
  background-color: rgba(150, 0, 0, .5);_x000D_
}_x000D_
.col-cw-keyword {_x000D_
  width: 50%;_x000D_
  background-color: rgba(0, 150, 0, .5);_x000D_
}_x000D_
.col-cw-reply {_x000D_
  width: 140px;_x000D_
  right: 130px;_x000D_
  background-color: rgba(0, 0, 150, .5);_x000D_
}_x000D_
.col-cw-action {_x000D_
  width: 130px;_x000D_
  right: 0;_x000D_
  background-color: rgba(150, 150, 0, .5);_x000D_
}
_x000D_
<ul class="ir-msg-list">_x000D_
  <li class="grid-list-header row-cw row-cw-msg-list">_x000D_
    <div class="col-md-1 col-cw col-cw-name">name</div>_x000D_
    <div class="col-md-1 col-cw col-cw-keyword">keyword</div>_x000D_
    <div class="col-md-1 col-cw col-cw-reply">reply</div>_x000D_
    <div class="col-md-1 col-cw col-cw-action">action</div>_x000D_
  </li>_x000D_
_x000D_
  <li class="grid-list-item row-cw row-cw-msg-list">_x000D_
    <div class="col-md-1 col-cw col-cw-name">name</div>_x000D_
    <div class="col-md-1 col-cw col-cw-keyword">keyword</div>_x000D_
    <div class="col-md-1 col-cw col-cw-reply">reply</div>_x000D_
    <div class="col-md-1 col-cw col-cw-action">action</div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Move UIView up when the keyboard appears in iOS

Just in case someone is looking for solution in Swift, throw this in your code:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}


@objc func keyboardWillShow(notification: Notification) {
    if let userInfo = notification.userInfo {
        if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            UIView.animate(withDuration: 0.3) {
                var alteredFrame = self.view.frame
                alteredFrame.origin.y = -keyboardSize.height
                self.view.frame = alteredFrame
            }
        }
    }
}

@objc func keyboardWillHide(notification: Notification) {
    UIView.animate(withDuration: 0.3) {
        var alteredFrame = self.view.frame
        alteredFrame.origin.y = 0.0
        self.view.frame = alteredFrame
    }
}

What is a Java String's default initial value?

There are three types of variables:

  • Instance variables: are always initialized
  • Static variables: are always initialized
  • Local variables: must be initialized before use

The default values for instance and static variables are the same and depends on the type:

  • Object type (String, Integer, Boolean and others): initialized with null
  • Primitive types:
    • byte, short, int, long: 0
    • float, double: 0.0
    • boolean: false
    • char: '\u0000'

An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.

Once the array is created all of its elements are assiged with the default type value. For example:

private boolean[] list; // default value is null

private Boolean[] list; // default value is null

once is initialized:

private boolean[] list = new boolean[10]; // all ten elements are assigned to false

private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)

Multidimensional arrays in Swift

Your original logic for creating the matrix is indeed correct, and it even works in Swift 2. The problem is that in the print loop, you have the row and column variables reversed. If you change it to:

for row in 0...2 {
  for column in 0...2 {
    print("column: \(column) row: \(row) value:\(array[column][row])")

  }
}

you will get the correct results. Hope this helps!

Find a file by name in Visual Studio Code

It is CMD + P (or CTRL + P) by default. However the keyboard bindings may differ according to your preferences.

To know your bindings go to the "Keyboard Shortcuts" settings and search for "Go to File"

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

I've had this error when there's been different RxJS-versions across projects. The internal checks in RxJS fails because there are several different Symbol_observable. Eventually this function throws once called from a flattening operator like switchMap.

Try importing symbol-observable in some entry point.

// main index.ts
import 'symbol-observable';

Determine when a ViewPager changes pages

For ViewPager2,

viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
  override fun onPageSelected(position: Int) {
    super.onPageSelected(position)
  }
})

where OnPageChangeCallback is a static class with three methods:

onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position), 
onPageScrollStateChanged(@ScrollState int state)

Sum a list of numbers in Python

All answers did show a programmatic and general approach. I suggest a mathematical approach specific for your case. It can be faster in particular for long lists. It works because your list is a list of natural numbers up to n:

Let's assume we have the natural numbers 1, 2, 3, ..., 10:

>>> nat_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

You can use the sum function on a list:

>>> print sum(nat_seq)
55

You can also use the formula n*(n+1)/2 where n is the value of the last element in the list (here: nat_seq[-1]), so you avoid iterating over elements:

>>> print (nat_seq[-1]*(nat_seq[-1]+1))/2
55

To generate the sequence (1+2)/2, (2+3)/2, ..., (9+10)/2 you can use a generator and the formula (2*k-1)/2. (note the dot to make the values floating points). You have to skip the first element when generating the new list:

>>> new_seq = [(2*k-1)/2. for k in nat_seq[1:]]
>>> print new_seq
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

Here too, you can use the sum function on that list:

>>> print sum(new_seq)
49.5

But you can also use the formula (((n*2+1)/2)**2-1)/2, so you can avoid iterating over elements:

>>> print (((new_seq[-1]*2+1)/2)**2-1)/2
49.5

Enable CORS in Web API 2

Late reply for future reference. What was working for me was enabling it by nuget and then adding custom headers into web.config.

How to escape % in String.Format?

This is a stronger regex replace that won't replace %% that are already doubled in the input.

str = str.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%");

Inline JavaScript onclick function

This should work

 <a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a>

You may inline any javascript inside the onclick as if you were assigning the method through javascript. I think is just a matter of making code cleaner keeping your js inside a script block

CAML query with nested ANDs and ORs for multiple fields

This code will dynamically generate the expression for you with the nested clauses. I have a scenario where the number of "OR" s was unknown, so I'm using the below. Usage:

        private static void Main(string[] args)
        {
            var query = new PropertyString(@"<Query><Where>{{WhereClauses}}</Where></Query>");
            var whereClause =
                new PropertyString(@"<Eq><FieldRef Name='ID'/><Value Type='Counter'>{{NestClauseValue}}</Value></Eq>");
            var andClause = new PropertyString("<Or>{{FirstExpression}}{{SecondExpression}}</Or>");

            string[] values = {"1", "2", "3", "4", "5", "6"};

            query["WhereClauses"] = NestEq(whereClause, andClause, values);

            Console.WriteLine(query);
        }

And here's the code:

   private static string MakeExpression(PropertyString nestClause, string value)
        {
            var expr = nestClause.New();
            expr["NestClauseValue"] = value;
            return expr.ToString();
        }

        /// <summary>
        /// Recursively nests the clause with the nesting expression, until nestClauseValue is empty.
        /// </summary>
        /// <param name="whereClause"> A property string in the following format: <Eq><FieldRef Name='Title'/><Value Type='Text'>{{NestClauseValue}}</Value></Eq>"; </param>
        /// <param name="nestingExpression"> A property string in the following format: <And>{{FirstExpression}}{{SecondExpression}}</And> </param>
        /// <param name="nestClauseValues">A string value which NestClauseValue will be filled in with.</param>
        public static string NestEq(PropertyString whereClause, PropertyString nestingExpression, string[] nestClauseValues, int pos=0)
        {
            if (pos > nestClauseValues.Length)
            {
                return "";
            }

            if (nestClauseValues.Length == 1)
            {
                return MakeExpression(whereClause, nestClauseValues[0]);
            }

            var expr = nestingExpression.New();
            if (pos == nestClauseValues.Length - 2)
            {
                expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
                expr["SecondExpression"] = MakeExpression(whereClause, nestClauseValues[pos + 1]);
                return expr.ToString();
            }
            else
            {
                expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
                expr["SecondExpression"] = NestEq(whereClause, nestingExpression, nestClauseValues, pos + 1);
                return expr.ToString();
            }
        }






          public class PropertyString
    {
        private string _propStr;

        public PropertyString New()
        {
            return new PropertyString(_propStr );
        }

        public PropertyString(string propStr)
        {
            _propStr = propStr;
            _properties = new Dictionary<string, string>();
        }

        private Dictionary<string, string> _properties;
        public string this[string key]
        {
            get
            {
                return _properties.ContainsKey(key) ? _properties[key] : string.Empty;
            }
            set
            {
                if (_properties.ContainsKey(key))
                {
                    _properties[key] = value;
                }
                else
                {
                    _properties.Add(key, value);
                }
            }
        }



        /// <summary>
        /// Replaces properties in the format {{propertyName}} in the source string with values from KeyValuePairPropertiesDictionarysupplied dictionary.nce you've set a property it's replaced in the string and you 
        /// </summary>
        /// <param name="originalStr"></param>
        /// <param name="keyValuePairPropertiesDictionary"></param>
        /// <returns></returns>
        public override string ToString()
        {
            string modifiedStr = _propStr;
            foreach (var keyvaluePair in _properties)
            {
                modifiedStr = modifiedStr.Replace("{{" + keyvaluePair.Key + "}}", keyvaluePair.Value);
            }

            return modifiedStr;
        }
    }

MS Access: how to compact current database in VBA

For Access 2013, you could just do

Sendkeys "%fic"

This is the same as typing ALT, F, I, C on your keyboard.

It's probably a different sequence of letters for different versions, but the "%" symbol means "ALT", so keep that in the code. you may just need to change the letters, depending on what letters appear when you press ALT

Letters that appear when pressing ALT in Access 2013

How do I verify that a string only contains letters, numbers, underscores and dashes?

There are a variety of ways of achieving this goal, some are clearer than others. For each of my examples, 'True' means that the string passed is valid, 'False' means it contains invalid characters.

First of all, there's the naive approach:

import string
allowed = string.letters + string.digits + '_' + '-'

def check_naive(mystring):
    return all(c in allowed for c in mystring)

Then there's use of a regular expression, you can do this with re.match(). Note that '-' has to be at the end of the [] otherwise it will be used as a 'range' delimiter. Also note the $ which means 'end of string'. Other answers noted in this question use a special character class, '\w', I always prefer using an explicit character class range using [] because it is easier to understand without having to look up a quick reference guide, and easier to special-case.

import re
CHECK_RE = re.compile('[a-zA-Z0-9_-]+$')
def check_re(mystring):
    return CHECK_RE.match(mystring)

Another solution noted that you can do an inverse match with regular expressions, I've included that here now. Note that [^...] inverts the character class because the ^ is used:

CHECK_INV_RE = re.compile('[^a-zA-Z0-9_-]')
def check_inv_re(mystring):
   return not CHECK_INV_RE.search(mystring)

You can also do something tricky with the 'set' object. Have a look at this example, which removes from the original string all the characters that are allowed, leaving us with a set containing either a) nothing, or b) the offending characters from the string:

def check_set(mystring):
    return not set(mystring) - set(allowed)

Switch case with fallthrough?

If the values are integer then you can use [2-3] or you can use [5,7,8] for non continuous values.

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    1)
        echo "one"
        ;;
    [2-3])
        echo "two or three"
        ;;
    [4-6])
        echo "four to six"
        ;;
    [7,9])
        echo "seven or nine"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

If the values are string then you can use |.

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    "one")
        echo "one"
        ;;
    "two" | "three")
        echo "two or three"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

How to print environment variables to the console in PowerShell?

The following is works best in my opinion:

Get-Item Env:PATH
  1. It's shorter and therefore a little bit easier to remember than Get-ChildItem. There's no hierarchy with environment variables.
  2. The command is symmetrical to one of the ways that's used for setting environment variables with Powershell. (EX: Set-Item -Path env:SomeVariable -Value "Some Value")
  3. If you get in the habit of doing it this way you'll remember how to list all Environment variables; simply omit the entry portion. (EX: Get-Item Env:)

I found the syntax odd at first, but things started making more sense after I understood the notion of Providers. Essentially PowerShell let's you navigate disparate components of the system in a way that's analogous to a file system.

What's the point of the trailing colon in Env:? Try listing all of the "drives" available through Providers like this:

PS> Get-PSDrive

I only see a few results... (Alias, C, Cert, D, Env, Function, HKCU, HKLM, Variable, WSMan). It becomes obvious that Env is simply another "drive" and the colon is a familiar syntax to anyone who's worked in Windows.

You can navigate the drives and pick out specific values:

Get-ChildItem C:\Windows
Get-Item C:
Get-Item Env:
Get-Item HKLM:
Get-ChildItem HKLM:SYSTEM

java.lang.NoClassDefFoundError: Could not initialize class XXX

As mentioned above, this could be a number of things. In my case I had a statically initialized variable which relied on a missing entry in my properties file. Added the missing entry to the properties file and the problem was solved.

How to load all modules in a folder?

import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
for imp, module, ispackage in pkgutil.walk_packages(path=__path__, prefix=__name__+'.'):
  __import__(module)

Git Bash: Could not open a connection to your authentication agent

Situation: MVS2017 App - Using 'Git Bash' on Windows 10 - Trying to connect to a BitBucket repository.

To be clear, when you install Git for Windows (https://git-scm.com/download/win), it comes with an utility called Git Bash.

enter image description here

So, I am in 'Git Bash', as follows:

Mike@DUBLIN MINGW64 ~/source/repos/DoubleIrish (master)
$ git remote add origin [email protected]:Guiness/DoubleIrish.git
$ git remote -v
origin  [email protected]:Guiness/DoubleIrish.git (fetch)
origin  [email protected]:Guiness/DoubleIrish.git (push)
Mike@DUBLIN MINGW64 ~/source/repos/DoubleIrish (master)
$ git push -u origin master
[...]
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

Is the private key set up?

$ ssh -V
OpenSSH_7.7p1, OpenSSL 1.0.2p  14 Aug 2018
$ ls -a ~/.ssh
./  ../  known_hosts

I can see that, at this point, my private key file (id_rsa) is missing. So I add it: (note: generating a pair of private-public keys is out of scope of my reply, but I can say that in Linux, you can use ssh-keygen for that.)

$ ls -a ~/.ssh
./  ../  id_rsa  known_hosts

OK, let's proceed:

$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-KhQwFLAgWGYC/agent.18320; export SSH_AUTH_SOCK;
SSH_AGENT_PID=17996; export SSH_AGENT_PID;
echo Agent pid 17996;

$ ssh-add ~/.ssh/id_rsa
Could not open a connection to your authentication agent.

To solve this, I run:

$ ssh-agent bash

And then, again:

$ ssh-add ~/.ssh/id_rsa
Identity added: /c/Users/Mike.CORP/.ssh/id_rsa (/c/Users/Mike.CORP/.ssh/id_rsa)

It worked for me. Hope this helps

Custom height Bootstrap's navbar

For Bootstrap 4, there are now spacing utilities so it's easier to change the height via padding on the nav links. This can be responsively applied only at specific breakpoints (ie: py-md-3). For example, on larger (md) screens, this nav is 120px high, then shrinks to normal height for the mobile menu. No extra CSS is needed..

<nav class="navbar navbar-fixed-top navbar-inverse bg-primary navbar-toggleable-md py-md-3">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
    <div class="navbar-collapse collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Home</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">More</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Options</a></li>
        </ul>
    </div>
</nav>

Bootstrap 4 Navbar Height Demo

How to add a color overlay to a background image?

Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/

.tinted-image {

  width: 300px;
  height: 200px;

  background: 
    /* top, transparent red */ 
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* bottom, image */
    url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}

Oracle query execution time

select LAST_LOAD_TIME, ELAPSED_TIME, MODULE, SQL_TEXT elapsed from v$sql
  order by LAST_LOAD_TIME desc

More complicated example (don't forget to delete or to substitute PATTERN):

select * from (
  select LAST_LOAD_TIME, to_char(ELAPSED_TIME/1000, '999,999,999.000') || ' ms' as TIME,
         MODULE, SQL_TEXT from SYS."V_\$SQL"
    where SQL_TEXT like '%PATTERN%'
    order by LAST_LOAD_TIME desc
  ) where ROWNUM <= 5;

Using jQuery To Get Size of Viewport

To get size of viewport on load and on resize (based on SimaWB response):

function getViewport() {
    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();
    $('#viewport').html('Viewport: '+viewportWidth+' x '+viewportHeight+' px');
}

getViewport();

$(window).resize(function() {
    getViewport()
});

YouTube embedded video: set different thumbnail

This solution is HTML and CSS based using z-index and hover, which works if JS is disabled or the video isn't yours (since you can add a thumbnail in YouTube).

<style>
.videoWrapper {
  position: relative;
  padding-bottom: 56.25%;
}
.videoWrapper .video-modal-poster img {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 10;
}
.videoWrapper .video-modal-poster:hover img {
  z-index:0;
}
.videoWrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
</style>
<div class="videoWrapper">
  <a href="#" class="video-modal-poster">
    <img alt="" src="" width="353" height="199" />
    <iframe width="353" height="199" src="https://www.youtube.com/embed/" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
  </a>
</div>

Detect click outside React component

To extend on the accepted answer made by Ben Bud, if you are using styled-components, passing refs that way will give you an error such as "this.wrapperRef.contains is not a function".

The suggested fix, in the comments, to wrap the styled component with a div and pass the ref there, works. Having said that, in their docs they already explain the reason for this and the proper use of refs within styled-components:

Passing a ref prop to a styled component will give you an instance of the StyledComponent wrapper, but not to the underlying DOM node. This is due to how refs work. It's not possible to call DOM methods, like focus, on our wrappers directly. To get a ref to the actual, wrapped DOM node, pass the callback to the innerRef prop instead.

Like so:

<StyledDiv innerRef={el => { this.el = el }} />

Then you can access it directly within the "handleClickOutside" function:

handleClickOutside = e => {
    if (this.el && !this.el.contains(e.target)) {
        console.log('clicked outside')
    }
}

This also applies for the "onBlur" approach:

componentDidMount(){
    this.el.focus()
}
blurHandler = () => {
    console.log('clicked outside')
}
render(){
    return(
        <StyledDiv
            onBlur={this.blurHandler}
            tabIndex="0"
            innerRef={el => { this.el = el }}
        />
    )
}

How do I turn off PHP Notices?

You can set ini_set('display_errors',0); in your script or define which errors you do want to display with error_reporting().

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.

Note, also, that your usage of .filter() was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each() loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:

$(".buttonClick").click(function () {

    $("input[type=text]").each(function () {
        var validated =  true;
        if(this.value.length < 8)
            validated = false;
        if(!/\d/.test(this.value))
            validated = false;
        if(!/[a-z]/.test(this.value))
            validated = false;
        if(!/[A-Z]/.test(this.value))
            validated = false;
        if(/[^0-9a-zA-Z]/.test(this.value))
            validated = false;
        $('div').text(validated ? "pass" : "fail");
        // use DOM traversal to select the correct div for this input above
    });
});

Working demo

jQuery $.cookie is not a function

Check that you included the script in header and not in footer of the page. Particularly in WordPress this one didn't work:

wp_register_script('cookie', get_template_directory_uri() . '/js/jquery.cookie.js', array(), false, true);

The last parameter indicates including the script in footer and needed to be changed to false (default). The way it worked:

wp_register_script('cookie', get_template_directory_uri() . '/js/jquery.cookie.js');

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

You can try openSSL to generate certificates. Take a look at this.

You are going to need a .key and .crt file to add HTTPS to node JS express server. Once you generate this, use this code to add HTTPS to server.

var https = require('https');
var fs = require('fs');
var express = require('express');

var options = {
    key: fs.readFileSync('/etc/apache2/ssl/server.key'),
    cert: fs.readFileSync('/etc/apache2/ssl/server.crt'),
    requestCert: false,
    rejectUnauthorized: false
};


var app = express();

var server = https.createServer(options, app).listen(3000, function(){
    console.log("server started at port 3000");
});

This is working fine in my local machine as well as the server where I have deployed this. The one I have in server was bought from goDaddy but localhost had a self signed certificate.

However, every browser threw an error saying connection is not trusted, do you want to continue. After I click continue, it worked fine.

If anyone has ever bypassed this error with self signed certificate, please enlighten.

How to setup Main class in manifest file in jar produced by NetBeans project

It is simple.

  • Right click on the project
  • Go to Properties
  • Go to Run in Categories tree
  • Set the Main Class in the right side panel.
  • Build the project

Thats it. Hope this helps.

How to merge multiple dicts with same key or different key?

assuming all keys are always present in all dicts:

ds = [d1, d2]
d = {}
for k in d1.iterkeys():
    d[k] = tuple(d[k] for d in ds)

Note: In Python 3.x use below code:

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = tuple(d[k] for d in ds)

and if the dic contain numpy arrays:

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = np.concatenate(list(d[k] for d in ds))

What exactly is RESTful programming?

There is not such notion as "RESTful programming" per se. It would be better called RESTful paradigm or even better RESTful architecture. It is not a programming language. It is a paradigm.

From Wikipedia:

In computing, representational state transfer (REST) is an architectural style used for web development.

An existing connection was forcibly closed by the remote host

I got the same issue while using .NET Framework 4.5. However, when I update the .NET version to 4.7.2 connection issue was resolved. Maybe this is due to SecurityProtocol support issue.

Usage of unicode() and encode() functions in Python

str is text representation in bytes, unicode is text representation in characters.

You decode text from bytes to unicode and encode a unicode into bytes with some encoding.

That is:

>>> 'abc'.decode('utf-8')  # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'

UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str was renamed to bytes, and unicode was renamed to str.

>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'

How to read values from the querystring with ASP.NET Core?

You could use the ToString method on IQueryCollection which will return the desired value if a single page parameter is specified:

string page = HttpContext.Request.Query["page"].ToString();

if there are multiple values like ?page=1&page=2 then the result of the ToString call will be 1,2

But as @mike-g suggested in his answer you would better use model binding and not directly accessing the HttpContext.Request.Query object.

How to get an element by its href in jquery?

If you want to get any element that has part of a URL in their href attribute you could use:

$( 'a[href*="google.com"]' );

This will select all elements with a href that contains google.com, for example:

As stated by @BalusC in the comments below, it will also match elements that have google.com at any position in the href, like blahgoogle.com.

Looping through array and removing items, without breaking for loop

If you are e using ES6+ - why not just use Array.filter method?

Auction.auctions = Auction.auctions.filter((auction) => {
  auction['seconds'] --;
  return (auction.seconds > 0)
})  

Note that modifying the array element during filter iteration only works for objects and will not work for array of primitive values.

How can I format a number into a string with leading zeros?

int num=1;
string number=num.ToString().PadLeft(4, '0')

Output="00001"

EDIT: Changed to match the PadLeft amount

loop through json array jquery

I dont think youre returning json object from server. just a string.

you need the dataType of the return object to be json

How to get length of a list of lists in python

This saves the data in a list of lists.

text = open("filetest.txt", "r")
data = [ ]
for line in text:
    data.append( line.strip().split() )

print "number of lines ", len(data)
print "number of columns ", len(data[0])

print "element in first row column two ", data[0][1]

Calculating Time Difference

Here is a piece of code to do so:

def(StringChallenge(str1)):

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0

def time_dif(h1,m1,h2,m2):
    if(h1 == h2):
        return m2-m1
    else:
        return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0

if str1[1] == ':':
    h1=int(str1[:1])
    m1=int(str1[2:4])
else:
    h1=int(str1[:2])
    m1=int(str1[3:5])

if str1[-7] == '-':
    h2=int(str1[-6])
    m2=int(str1[-4:-2])
else:
    h2=int(str1[-7:-5])
    m2=int(str1[-4:-2])

if h1 == 12:
    h1 = 0
if h2 == 12:
    h2 = 0

if "am" in str1[:8]:
    flag1 = 0
else:
    flag1= 1

if "am" in str1[7:]:
    flag2 = 0
else:
    flag2 = 1

if flag1 == flag2:
    if h2 > h1 or (h2 == h1 and m2 >= m1):
        count_min += time_dif(h1,m1,h2,m2)
    else:
        count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
    count_min += (12-h1-1)*60
    count_min += (60 - m1)
    count_min += (h2*60)+m2


return count_min

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

I had this issue. The security settings in the ControlPanel seem to be user specific. Try running it as the user you are actually running your browser as (you are not browsing as root!??) and setting the security level to Medium there. - For me, that did it.

How to remove error about glyphicons-halflings-regular.woff2 not found

This problem happens because IIS does not find the actual location of woff2 file mime types. Set URL of font-face properly, also keep font-family as glyphicons-halflings-regular in your CSS file as shown below.

@font-face {
font-family: 'glyphicons-halflings-regular'; 
src: url('../../../fonts/glyphicons-halflings-regular.woff2') format('woff2');}

Stretch and scale CSS background

Scaling an image with CSS is not quite possible, but a similar effect can be achieved in the following manner, though.

Use this markup:

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

with the following CSS:

#background {
    width: 100%; 
    height: 100%; 
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}

.stretch {
    width:100%;
    height:100%;
}

and you should be done!

In order to scale the image to be "full bleed" and maintain the aspect ratio, you can do this instead:

.stretch { min-width:100%; min-height:100%; width:auto; height:auto; }

It works out quite nicely! If one dimension is cropped, however, it will be cropped on only one side of the image, rather than being evenly cropped on both sides (and centered). I've tested it in Firefox, Webkit, and Internet Explorer 8.

Labeling file upload button

You get your browser's language for your button. There's no way to change it programmatically.

IN-clause in HQL or Java Persistence Query Language

in HQL you can use query parameter and set Collection with setParameterList method.

    Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
    q.setParameterList("names", names);

How to disable Home and other system buttons in Android?

First of, please think long and hard if you really want to disable the Home button or any other button for that matter (e.g. the Back button), this is not something that should be done (at least most of the times, this is a bad design). I can speak only for myself, but if I downloaded an app that doesn't let me do something like clicking an OS button, the next thing I do is uninstall that app and leave a very bad review. I also believe that your app will not be featured on the App Store.

Now...

Notice that MX Player is asking permission to draw on top of other applications:MX Player permissions
Since you cannot override the Home button on Android device (at least no in the latest OS versions). MX Player draws itself on top of your launcher when you "lock" the app and clicks on the Home button.
To see an example of that is a bit more simple and straight forward to understand, you can see the Facebook Messenger App.

As I was asked to provide some more info about MX Player Status Bar and Navigation Bar "overriding", I'm editing my answer to include these topics too.

First thing first, MX Player is using Immersive Full-Screen Mode (DevBytes Video) on KitKat.
Android 4.4 (API Level 19) introduces a new SYSTEM_UI_FLAG_IMMERSIVE flag for setSystemUiVisibility() that lets your app go truly "full screen." This flag, when combined with the SYSTEM_UI_FLAG_HIDE_NAVIGATION and SYSTEM_UI_FLAG_FULLSCREEN flags, hides the navigation and status bars and lets your app capture all touch events on the screen.

When immersive full-screen mode is enabled, your activity continues to receive all touch events. The user can reveal the system bars with an inward swipe along the region where the system bars normally appear. This clears the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag (and the SYSTEM_UI_FLAG_FULLSCREEN flag, if applied) so the system bars become visible. This also triggers your View.OnSystemUiVisibilityChangeListener, if set. However, if you'd like the system bars to automatically hide again after a few moments, you can instead use the SYSTEM_UI_FLAG_IMMERSIVE_STICKY flag. Note that the "sticky" version of the flag doesn't trigger any listeners, as system bars temporarily shown in this mode are in a transient state.

Second: Hiding the Status Bar
Third: Hiding the Navigation Bar
Please note that although using immersive full screen is only for KitKat, hiding the Status Bar and Navigation Bar is not only for KitKat.

I don't have much to say about the 2nd and 3rd, You get the idea I believe, it's a fast read in any case. Just make sure you pay close attention to View.OnSystemUiVisibilityChangeListener.

I added a Gist that explains what I meant, it's not complete and needs some fixing but you'll get the idea. https://gist.github.com/Epsiloni/8303531

Good luck implementing this, and have fun!

Cosine Similarity between 2 Number Lists

I did a benchmark based on several answers in the question and the following snippet is believed to be the best choice:

def dot_product2(v1, v2):
    return sum(map(operator.mul, v1, v2))


def vector_cos5(v1, v2):
    prod = dot_product2(v1, v2)
    len1 = math.sqrt(dot_product2(v1, v1))
    len2 = math.sqrt(dot_product2(v2, v2))
    return prod / (len1 * len2)

The result makes me surprised that the implementation based on scipy is not the fastest one. I profiled and find that cosine in scipy takes a lot of time to cast a vector from python list to numpy array.

enter image description here

Configuring Log4j Loggers Programmatically

It sounds like you're trying to use log4j from "both ends" (the consumer end and the configuration end).

If you want to code against the slf4j api but determine ahead of time (and programmatically) the configuration of the log4j Loggers that the classpath will return, you absolutely have to have some sort of logging adaptation which makes use of lazy construction.

public class YourLoggingWrapper {
    private static boolean loggingIsInitialized = false;

    public YourLoggingWrapper() {
        // ...blah
    }

    public static void debug(String debugMsg) {
        log(LogLevel.Debug, debugMsg);
    }

    // Same for all other log levels your want to handle.
    // You mentioned TRACE and ERROR.

    private static void log(LogLevel level, String logMsg) {
        if(!loggingIsInitialized)
            initLogging();

        org.slf4j.Logger slf4jLogger = org.slf4j.LoggerFactory.getLogger("DebugLogger");

        switch(level) {
        case: Debug:
            logger.debug(logMsg);
            break;
        default:
            // whatever
        }
    }

    // log4j logging is lazily constructed; it gets initialized
    // the first time the invoking app calls a log method
    private static void initLogging() {
        loggingIsInitialized = true;

        org.apache.log4j.Logger debugLogger = org.apache.log4j.LoggerFactory.getLogger("DebugLogger");

        // Now all the same configuration code that @oers suggested applies...
        // configure the logger, configure and add its appenders, etc.
        debugLogger.addAppender(someConfiguredFileAppender);
    }

With this approach, you don't need to worry about where/when your log4j loggers get configured. The first time the classpath asks for them, they get lazily constructed, passed back and made available via slf4j. Hope this helped!

Jquery find nearest matching element

You could try:

$(this).closest(".column").prev().find(".inputQty").val();

sql query to find the duplicate records

select distinct title, (
               select count(title) 
               from kmovies as sub 
               where sub.title=kmovies.title) as cnt 
from kmovies 
group by title 
order by cnt desc

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.