Programs & Examples On #Pruning

What is the MySQL JDBC driver connection string?

Check if the Driver Connector jar matches the SQL version.

I was also getting the same error as I was using the

mySQl-connector-java-5.1.30.jar

with MySql 8

IN-clause in HQL or Java Persistence Query Language

Are you using Hibernate's Query object, or JPA? For JPA, it should work fine:

String jpql = "from A where name in (:names)";
Query q = em.createQuery(jpql);
q.setParameter("names", l);

For Hibernate's, you'll need to use the setParameterList:

String hql = "from A where name in (:names)";
Query q = s.createQuery(hql);
q.setParameterList("names", l);

cannot import name patterns

As of Django 1.10, the patterns module has been removed (it had been deprecated since 1.8).

Luckily, it should be a simple edit to remove the offending code, since the urlpatterns should now be stored in a plain-old list:

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    # ... your url patterns
]

What does '<?=' mean in PHP?

It means assign the key to $user and the variable to $pass

When you assign an array, you do it like this

$array = array("key" => "value");

It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.

According to the PHP Manual, the '=>' created key/value pairs.

Also, Equal or Greater than is the opposite way: '>='. In PHP the greater or less than sign always goes first: '>=', '<='.

And just as a side note, excluding the second value does not work like you think it would. Instead of only giving you the key, It actually only gives you a value:

$array = array("test" => "foo");

foreach($array as $key => $value)
{
    echo $key . " : " . $value; // Echoes "test : foo"
}

foreach($array as $value)
{
    echo $value; // Echoes "foo"
}

Is there a way to specify how many characters of a string to print out using printf()?

Using printf you can do

printf("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");

If you're using C++, you can achieve the same result using the STL:

using namespace std; // for clarity
string s("A string that is more than 8 chars");
cout << "Here are the first 8 chars: ";
copy(s.begin(), s.begin() + 8, ostream_iterator<char>(cout));
cout << endl;

Or, less efficiently:

cout << "Here are the first 8 chars: " <<
        string(s.begin(), s.begin() + 8) << endl;

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

pandas get rows which are NOT in other dataframe

You can also concat df1, df2:

x = pd.concat([df1, df2])

and then remove all duplicates:

y = x.drop_duplicates(keep=False, inplace=False)

Transport security has blocked a cleartext HTTP

Transport security is available on iOS 9.0 or later. You may have this warning when trying to call a WS inside your application:

Application Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

Adding the following to your Info.plist will disable ATS:

<key>NSAppTransportSecurity</key>
<dict>
     <key>NSAllowsArbitraryLoads</key><true/>
</dict>

How can I send emails through SSL SMTP with the .NET Framework?

If it's Implicit SSL, it looks like it can't be done with System.Net.Mail and isn't supported as of yet.

http://blogs.msdn.com/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx

To check if it's Implicit SSL try this.

Regular expression to remove HTML tags from a string

A trivial approach would be to replace

<[^>]*>

with nothing. But depending on how ill-structured your input is that may well fail.

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

I wanted to add one more point is, if you are storing a really large number like 902054990011312 then one can easily see the difference of INT(20) and BIGINT(20). It is advisable to store in BIGINT.

How can I check if a jQuery plugin is loaded?

Run this in your browser console of choice.

if(jQuery().pluginName){console.log('bonjour');}

If the plugin exists it will print out "bonjour" as a response in your console.

Parse json string using JSON.NET

If your keys are dynamic I would suggest deserializing directly into a DataTable:

    class SampleData
    {
        [JsonProperty(PropertyName = "items")]
        public System.Data.DataTable Items { get; set; }
    }

    public void DerializeTable()
    {
        const string json = @"{items:["
            + @"{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
            + @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
            + @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]}";
        var sampleData = JsonConvert.DeserializeObject<SampleData>(json);
        var table = sampleData.Items;

        // write tab delimited table without knowing column names
        var line = string.Empty;
        foreach (DataColumn column in table.Columns)            
            line += column.ColumnName + "\t";                       
        Console.WriteLine(line);

        foreach (DataRow row in table.Rows)
        {
            line = string.Empty;
            foreach (DataColumn column in table.Columns)                
                line += row[column] + "\t";                                   
            Console.WriteLine(line);
        }

        // Name   Age   Job    
        // AAA    22    PPP    
        // BBB    25    QQQ    
        // CCC    38    RRR    
    }

You can determine the DataTable column names and types dynamically once deserialized.

Easy way to test a URL for 404 in PHP?

If your running php5 you can use:

$url = 'http://www.example.com';
print_r(get_headers($url, 1));

Alternatively with php4 a user has contributed the following:

/**
This is a modified version of code from "stuart at sixletterwords dot com", at 14-Sep-2005 04:52. This version tries to emulate get_headers() function at PHP4. I think it works fairly well, and is simple. It is not the best emulation available, but it works.

Features:
- supports (and requires) full URLs.
- supports changing of default port in URL.
- stops downloading from socket as soon as end-of-headers is detected.

Limitations:
- only gets the root URL (see line with "GET / HTTP/1.1").
- don't support HTTPS (nor the default HTTPS port).
*/

if(!function_exists('get_headers'))
{
    function get_headers($url,$format=0)
    {
        $url=parse_url($url);
        $end = "\r\n\r\n";
        $fp = fsockopen($url['host'], (empty($url['port'])?80:$url['port']), $errno, $errstr, 30);
        if ($fp)
        {
            $out  = "GET / HTTP/1.1\r\n";
            $out .= "Host: ".$url['host']."\r\n";
            $out .= "Connection: Close\r\n\r\n";
            $var  = '';
            fwrite($fp, $out);
            while (!feof($fp))
            {
                $var.=fgets($fp, 1280);
                if(strpos($var,$end))
                    break;
            }
            fclose($fp);

            $var=preg_replace("/\r\n\r\n.*\$/",'',$var);
            $var=explode("\r\n",$var);
            if($format)
            {
                foreach($var as $i)
                {
                    if(preg_match('/^([a-zA-Z -]+): +(.*)$/',$i,$parts))
                        $v[$parts[1]]=$parts[2];
                }
                return $v;
            }
            else
                return $var;
        }
    }
}

Both would have a result similar to:

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

Therefore you could just check to see that the header response was OK eg:

$headers = get_headers($url, 1);
if ($headers[0] == 'HTTP/1.1 200 OK') {
//valid 
}

if ($headers[0] == 'HTTP/1.1 301 Moved Permanently') {
//moved or redirect page
}

W3C Codes and Definitions

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

I believe those comments refer specifically to the browsers, i.e., clicking links and submitting forms, not XMLHttpRequest. XMLHttpRequest is just a custom client that you wrote in JavaScript that uses the browser as a runtime.

UPDATE: To clarify, I did not mean (though I did write) that you wrote XMLHttpRequest; I meant that you wrote the code that uses XMLHttpRequest. The browsers do not natively support XMLHttpRequest. XMLHttpRequest comes from the JavaScript runtime, which may be hosted by a browser, although it isn't required to be (see Rhino). That's why people say browsers don't support PUT and DELETE—because it's actually JavaScript that is supporting them.

How to encode a string in JavaScript for displaying in HTML?

You need to escape < and &. Escaping > too doesn't hurt:

function magic(input) {
    input = input.replace(/&/g, '&amp;');
    input = input.replace(/</g, '&lt;');
    input = input.replace(/>/g, '&gt;');
    return input;
}

Or you let the DOM engine do the dirty work for you (using jQuery because I'm lazy):

function magic(input) {
    return $('<span>').text(input).html();
}

What this does is creating a dummy element, assigning your string as its textContent (i.e. no HTML-specific characters have side effects since it's just text) and then you retrieve the HTML content of that element - which is the text but with special characters converted to HTML entities in cases where it's necessary.

angularjs ng-style: background-image isn't working

This worked for me, curly braces are not required.

ng-style="{'background-image':'url(../../../app/img/notification/'+notification.icon+'.png)'}"

notification.icon here is scope variable.

Best practice to run Linux service as a different user

After looking at all the suggestions here, I've discovered a few things which I hope will be useful to others in my position:

  1. hop is right to point me back at /etc/init.d/functions: the daemon function already allows you to set an alternate user:

    daemon --user=my_user my_cmd &>/dev/null &
    

    This is implemented by wrapping the process invocation with runuser - more on this later.

  2. Jonathan Leffler is right: there is setuid in Python:

    import os
    os.setuid(501) # UID of my_user is 501
    

    I still don't think you can setuid from inside a JVM, however.

  3. Neither su nor runuser gracefully handle the case where you ask to run a command as the user you already are. E.g.:

    [my_user@my_host]$ id
    uid=500(my_user) gid=500(my_user) groups=500(my_user)
    [my_user@my_host]$ su my_user -c "id"
    Password: # don't want to be prompted!
    uid=500(my_user) gid=500(my_user) groups=500(my_user)
    

To workaround that behaviour of su and runuser, I've changed my init script to something like:

if [[ "$USER" == "my_user" ]]
then
    daemon my_cmd &>/dev/null &
else
    daemon --user=my_user my_cmd &>/dev/null &
fi

Thanks all for your help!

Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}

Declare and assign multiple string variables at the same time

Try

string     Camnr , Klantnr , Ordernr , Bonnr , Volgnr , Omschrijving , Startdatum ,    Bonprioriteit , Matsoort , Dikte , Draaibaarheid , Draaiomschrijving , Orderleverdatum , Regeltaakkode , Gebruiksvoorkeur , Regelcamprog , Regeltijd , Orderrelease ;

and then

Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = "";

How can I convert a DateTime to the number of seconds since 1970?

That approach will be good if the date-time in question is in UTC, or represents local time in an area that has never observed daylight saving time. The DateTime difference routines do not take into account Daylight Saving Time, and consequently will regard midnight June 1 as being a multiple of 24 hours after midnight January 1. I'm unaware of anything in Windows that reports historical daylight-saving rules for the current locale, so I don't think there's any good way to correctly handle any time prior to the most recent daylight-saving rule change.

Does delete on a pointer to a subclass call the base class destructor?

You should delete A yourself in the destructor of B.

Best way to do multi-row insert in Oracle?

This works in Oracle:

insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
          select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual

The thing to remember here is to use the from dual statement.

bootstrap responsive table content wrapping

EDIT

I think the reason that your table is not responsive to start with was you did not wrap in .container, .row and .col-md-x classes like this one

<div class="container">
   <div class="row">
     <div class="col-md-12">
     <!-- or use any other number .col-md- -->
         <div class="table-responsive">
             <div class="table">
             </div>
         </div>
     </div>
   </div>
</div>

With this, you can still use <p> tags and even make it responsive.

Please see the Bootply example here

How to upload file to server with HTTP POST multipart/form-data?

For people searching for 403 forbidden issue while trying to upload in multipart form the below might help as there is a case depending on the server configuration that you will get MULTIPART_STRICT_ERROR "!@eq 0" due to incorrect MultipartFormDataContent headers. Please note that both imagetag/filename variables include quotations (\") eg filename="\"myfile.png\"" .

    MultipartFormDataContent form = new MultipartFormDataContent();
    ByteArrayContent imageContent = new ByteArrayContent(fileBytes, 0, fileBytes.Length);
    imageContent.Headers.TryAddWithoutValidation("Content-Disposition", "form-data; name="+imagetag+"; filename="+filename);
    imageContent.Headers.TryAddWithoutValidation("Content-Type", "image / png");
    form.Add(imageContent, imagetag, filename);

Error when testing on iOS simulator: Couldn't register with the bootstrap server

status: this has been seen as recently as Mac OS 10.8 and Xcode 4.4.

tl;dr: This can occur in two contexts: when running on the device and when running on the simulator. When running on the device, disconnecting and reconnecting the device seems to fix things.

Mike Ash suggested

launchctl list|grep UIKitApplication|awk '{print $3}'|xargs launchctl remove

This doesn't work all the time. In fact, it's never worked for me but it clearly works in some cases. Just don't know which cases. So it's worth trying.

Otherwise, the only known way to fix this is to restart the user launchd. Rebooting will do that but there is a less drastic/faster way. You'll need to create another admin user, but you only have to do that once. When things wedge, log out as yourself, log in as that user, and kill the launchd that belongs to your main user, e.g.,

sudo kill -9 `ps aux | egrep 'user_id .*[0-9] /sbin/launchd' | awk '{print $2}'`

substituting your main user name for user_id. Logging in again as your normal user gets you back to a sane state. Kinda painful, but less so than a full reboot.

details:

This has started happening more often with Lion/Xcode 4.2. (Personally, I never saw it before that combination.)

The bug seems to be in launchd, which inherits the app process as a child when the debugger stops debugging it without killing it. This is usually signaled by the app becoming a zombie, having a process status of Z in ps.

The core issue appears to be in the bootstrap name server which is implemented in launchd. This (to the extent I understand it) maps app ids to mach ports. When the bug is triggered, the app dies but doesn't get cleaned out of the bootstrap server's name server map and as result, the bootstrap server refuses to allow another instance of the app to be registered under the same name.

It was hoped (see the comments) that forcing launchd to wait() for the zombie would fix things but it doesn't. It's not the zombie status that's the core problem (which is why some zombies are benign) but the bootstrap name server and there's no known way to clear this short of killing launchd.

It looks like the bug is triggered by something bad between Xcode, gdb, and the user launchd. I just repeated the wedge by running an app in the iphone simulator, having it stopped within gdb, and then doing a build and run to the ipad simulator. It seems to be sensitive to switching simulators (iOS 4.3/iOS 5, iPad/iPhone). It doesn't happen all the time but fairly frequently when I'm switching simulators a lot.

Killing launchd while you're logged in will screw up your session. Logging out and logging back in doesn't kill the user launchd; OS X keeps the existing process around. A reboot will fix things, but that's painful. The instructions above are faster.

I've submitted a bug to Apple, FWIW. rdar://10330930

How to handle AssertionError in Python and find out which line or statement it occurred on?

Use the traceback module:

import sys
import traceback

try:
    assert True
    assert 7 == 7
    assert 1 == 2
    # many more statements like this
except AssertionError:
    _, _, tb = sys.exc_info()
    traceback.print_tb(tb) # Fixed format
    tb_info = traceback.extract_tb(tb)
    filename, line, func, text = tb_info[-1]

    print('An error occurred on line {} in statement {}'.format(line, text))
    exit(1)

Accessing dict keys like an attribute?

tuples can be used dict keys. How would you access tuple in your construct?

Also, namedtuple is a convenient structure which can provide values via the attribute access.

How to make a HTML Page in A4 paper size page(s)?

A4 size is 210x297mm

So you can set the HTML page to fit those sizes with CSS:

html,body{
    height:297mm;
    width:210mm;
}

How to insert default values in SQL table?

Best practice it to list your columns so you're independent of table changes (new column or column order etc)

insert into table1 (field1, field3)  values (5,10)

However, if you don't want to do this, use the DEFAULT keyword

insert into table1 values (5, DEFAULT, 10, DEFAULT)

Jaxb, Class has two properties of the same name

You need to configure class ModeleREP as well with @XmlAccessorType(XmlAccessType.FIELD) as you did with class TimeSeries.

Have al look at OOXS

What do all of Scala's symbolic operators mean?

Oohoo so you want an exhaustive answer? Here's a fun, hopefully complete, and rather lengthy list for you :)

http://jim-mcbeath.blogspot.com/2008/12/scala-operator-cheat-sheet.html

(Disclaimer - the post was written in 2008 so may be a little out of date)

!! AbstractActor
!! Actor // Sends msg to this actor and immediately ...
!! Proxy
! Actor // Sends msg to this actor (asynchronous).
! Channel // Sends a message to this Channel.
! OutputChannel // Sends msg to this ...
! Proxy // Sends msg to this ...
!= Any // o != arg0 is the same as !(o == (arg0)).
!= AnyRef
!= Boolean
!= Byte
!= Char
!= Double
!= Float
!= Int
!= Long
!= Short
!? AbstractActor
!? Actor // Sends msg to this actor and awaits reply ...
!? Channel // Sends a message to this Channel and ...
!? Proxy
% BigInt // Remainder of BigInts
% Byte
% Char
% Double
% Float
% Int
% Long
% Short
% Elem // Returns a new element with updated attributes, resolving namespace uris from this element's scope. ...
&&& Parsers.Parser
&& Boolean
&+ NodeBuffer // Append given object to this buffer, returns reference on this NodeBuffer ...
& BigInt // Bitwise and of BigInts
& Boolean
& Byte
& Char
& Enumeration.Set32 // Equivalent to * for bit sets. ...
& Enumeration.Set64 // Equivalent to * for bit sets. ...
& Enumeration.SetXX // Equivalent to * for bit sets. ...
& Int
& Long
& Short
&~ BigInt // Bitwise and-not of BigInts. Returns a BigInt whose value is (this & ~that).
&~ Enumeration.Set32 // Equivalent to - for bit sets. ...
&~ Enumeration.Set64 // Equivalent to - for bit sets. ...
&~ Enumeration.SetXX // Equivalent to - for bit sets. ...
>>> Byte
>>> Char
>>> Int
>>> Long
>>> Short
>> BigInt // (Signed) rightshift of BigInt
>> Byte
>> Char
>> Int
>> Long
>> Short
>> Parsers.Parser // Returns into(fq)
>> Parsers.Parser // Returns into(fq)
> BigDecimal // Greater-than comparison of BigDecimals
> BigInt // Greater-than comparison of BigInts
> Byte
> Char
> Double
> Float
> Int
> Long
> Ordered
> PartiallyOrdered
> Short
>= BigDecimal // Greater-than-or-equals comparison of BigDecimals
>= BigInt // Greater-than-or-equals comparison of BigInts
>= Byte
>= Char
>= Double
>= Float
>= Int
>= Long
>= Ordered
>= PartiallyOrdered
>= Short
<< BigInt // Leftshift of BigInt
<< Byte
<< Char
<< Int
<< Long
<< Short
<< Buffer // Send a message to this scriptable object.
<< BufferProxy // Send a message to this scriptable object.
<< Map // Send a message to this scriptable object.
<< MapProxy // Send a message to this scriptable object.
<< Scriptable // Send a message to this scriptable object.
<< Set // Send a message to this scriptable object.
<< SetProxy // Send a message to this scriptable object.
<< SynchronizedBuffer // Send a message to this scriptable object.
<< SynchronizedMap // Send a message to this scriptable object.
<< SynchronizedSet // Send a message to this scriptable object.
< BigDecimal // Less-than of BigDecimals
< BigInt // Less-than of BigInts
< Byte
< Char
< Double
< Float
< Int
< Long
< Ordered
< PartiallyOrdered
< Short
< OffsetPosition // Compare this position to another, by first comparing their line numbers, ...
< Position // Compare this position to another, by first comparing their line numbers, ...
<= BigDecimal // Less-than-or-equals comparison of BigDecimals
<= BigInt // Less-than-or-equals comparison of BigInts
<= Byte
<= Char
<= Double
<= Float
<= Int
<= Long
<= Ordered
<= PartiallyOrdered
<= Short
<~ Parsers.Parser // A parser combinator for sequential composition which keeps only the left result
** Enumeration.SetXX
** Set // Intersect. It computes an intersection with set that. ...
** Set // This method is an alias for intersect. ...
* BigDecimal // Multiplication of BigDecimals
* BigInt // Multiplication of BigInts
* Byte
* Char
* Double
* Float
* Int
* Long
* Short
* Set
* RichString // return n times the current string
* Parsers.Parser // Returns a parser that repeatedly parses what this parser parses, interleaved with the `sep' parser. ...
* Parsers.Parser // Returns a parser that repeatedly parses what this parser parses
* Parsers.Parser // Returns a parser that repeatedly parses what this parser parses, interleaved with the `sep' parser. ...
* Parsers.Parser // Returns a parser that repeatedly parses what this parser parses, interleaved with the `sep' parser.
* Parsers.Parser // Returns a parser that repeatedly parses what this parser parses
++: ArrayBuffer // Prepends a number of elements provided by an iterable object ...
++: Buffer // Prepends a number of elements provided by an iterable object ...
++: BufferProxy // Prepends a number of elements provided by an iterable object ...
++: SynchronizedBuffer // Prepends a number of elements provided by an iterable object ...
++ Array // Returns an array consisting of all elements of this array followed ...
++ Enumeration.SetXX
++ Iterable // Appends two iterable objects.
++ IterableProxy // Appends two iterable objects.
++ Iterator // Returns a new iterator that first yields the elements of this ...
++ List // Appends two list objects.
++ RandomAccessSeq // Appends two iterable objects.
++ RandomAccessSeqProxy // Appends two iterable objects.
++ Seq // Appends two iterable objects.
++ SeqProxy // Appends two iterable objects.
++ IntMap // Add a sequence of key/value pairs to this map.
++ LongMap // Add a sequence of key/value pairs to this map.
++ Map // Add a sequence of key/value pairs to this map.
++ Set // Add all the elements provided by an iterator ...
++ Set // Add all the elements provided by an iterator to the set.
++ SortedMap // Add a sequence of key/value pairs to this map.
++ SortedSet // Add all the elements provided by an iterator ...
++ Stack // Push all elements provided by the given iterable object onto ...
++ Stack // Push all elements provided by the given iterator object onto ...
++ TreeHashMap
++ TreeHashMap // Add a sequence of key/value pairs to this map.
++ Collection // Operator shortcut for addAll.
++ Set // Operator shortcut for addAll.
++ ArrayBuffer // Appends two iterable objects.
++ Buffer // Appends a number of elements provided by an iterable object ...
++ Buffer // Appends a number of elements provided by an iterator ...
++ Buffer // Appends two iterable objects.
++ BufferProxy // Appends a number of elements provided by an iterable object ...
++ Map // Add a sequence of key/value pairs to this map.
++ MapProxy // Add a sequence of key/value pairs to this map.
++ PriorityQueue
++ Set // Add all the elements provided by an iterator ...
++ SynchronizedBuffer // Appends a number of elements provided by an iterable object ...
++ RichString // Appends two iterable objects.
++ RichStringBuilder // Appends a number of elements provided by an iterable object ...
++ RichStringBuilder // Appends two iterable objects.
++= Map // Add a sequence of key/value pairs to this map.
++= MapWrapper // Add a sequence of key/value pairs to this map.
++= ArrayBuffer // Appends a number of elements in an array
++= ArrayBuffer // Appends a number of elements provided by an iterable object ...
++= ArrayStack // Pushes all the provided elements onto the stack.
++= Buffer // Appends a number of elements in an array
++= Buffer // Appends a number of elements provided by an iterable object ...
++= Buffer // Appends a number of elements provided by an iterator
++= BufferProxy // Appends a number of elements provided by an iterable object ...
++= Map // Add a sequence of key/value pairs to this map.
++= MapProxy // Add a sequence of key/value pairs to this map.
++= PriorityQueue // Adds all elements provided by an Iterable object ...
++= PriorityQueue // Adds all elements provided by an iterator into the priority queue.
++= PriorityQueueProxy // Adds all elements provided by an Iterable object ...
++= PriorityQueueProxy // Adds all elements provided by an iterator into the priority queue.
++= Queue // Adds all elements provided by an Iterable object ...
++= Queue // Adds all elements provided by an iterator ...
++= QueueProxy // Adds all elements provided by an Iterable object ...
++= QueueProxy // Adds all elements provided by an iterator ...
++= Set // Add all the elements provided by an iterator ...
++= SetProxy // Add all the elements provided by an iterator ...
++= Stack // Pushes all elements provided by an Iterable object ...
++= Stack // Pushes all elements provided by an iterator ...
++= StackProxy // Pushes all elements provided by an Iterable object ...
++= StackProxy // Pushes all elements provided by an iterator ...
++= SynchronizedBuffer // Appends a number of elements provided by an iterable object ...
++= SynchronizedMap // Add a sequence of key/value pairs to this map.
++= SynchronizedPriorityQueue // Adds all elements provided by an Iterable object ...
++= SynchronizedPriorityQueue // Adds all elements provided by an iterator into the priority queue.
++= SynchronizedQueue // Adds all elements provided by an Iterable object ...
++= SynchronizedQueue // Adds all elements provided by an iterator ...
++= SynchronizedSet // Add all the elements provided by an iterator ...
++= SynchronizedStack // Pushes all elements provided by an Iterable object ...
++= SynchronizedStack // Pushes all elements provided by an iterator ...
++= RichStringBuilder // Appends a number of elements provided by an iterable object ...
+: ArrayBuffer // Prepends a single element to this buffer and return ...
+: Buffer // Prepend a single element to this buffer and return ...
+: BufferProxy // Prepend a single element to this buffer and return ...
+: ListBuffer // Prepends a single element to this buffer. It takes constant ...
+: ObservableBuffer // Prepend a single element to this buffer and return ...
+: SynchronizedBuffer // Prepend a single element to this buffer and return ...
+: RichStringBuilder // Prepend a single element to this buffer and return ...
+: BufferWrapper // Prepend a single element to this buffer and return ...
+: RefBuffer // Prepend a single element to this buffer and return ...
+ BigDecimal // Addition of BigDecimals
+ BigInt // Addition of BigInts
+ Byte
+ Char
+ Double
+ Enumeration.SetXX // Create a new set with an additional element.
+ Float
+ Int
+ List
+ Long
+ Short
+ EmptySet // Create a new set with an additional element.
+ HashSet // Create a new set with an additional element.
+ ListSet.Node // This method creates a new set with an additional element.
+ ListSet // This method creates a new set with an additional element.
+ Map
+ Map // Add a key/value pair to this map.
+ Map // Add two or more key/value pairs to this map.
+ Queue // Creates a new queue with element added at the end ...
+ Queue // Returns a new queue with all all elements provided by ...
+ Set // Add two or more elements to this set.
+ Set // Create a new set with an additional element.
+ Set1 // Create a new set with an additional element.
+ Set2 // Create a new set with an additional element.
+ Set3 // Create a new set with an additional element.
+ Set4 // Create a new set with an additional element.
+ SortedMap // Add a key/value pair to this map.
+ SortedMap // Add two or more key/value pairs to this map.
+ SortedSet // Create a new set with an additional element.
+ Stack // Push all elements provided by the given iterable object onto ...
+ Stack // Push an element on the stack.
+ TreeSet // A new TreeSet with the entry added is returned,
+ Buffer // adds "a" from the collection. Useful for chaining.
+ Collection // adds "a" from the collection. Useful for chaining.
+ Map // Add a key/value pair to this map.
+ Set // adds "a" from the collection. Useful for chaining.
+ Buffer // Append a single element to this buffer and return ...
+ BufferProxy // Append a single element to this buffer and return ...
+ Map // Add a key/value pair to this map.
+ Map // Add two or more key/value pairs to this map.
+ MapProxy // Add a key/value pair to this map.
+ MapProxy // Add two or more key/value pairs to this map.
+ ObservableBuffer // Append a single element to this buffer and return ...
+ PriorityQueue
+ Set // Add a new element to the set.
+ Set // Add two or more elements to this set.
+ SynchronizedBuffer // Append a single element to this buffer and return ...
+ Parsers.Parser // Returns a parser that repeatedly (at least once) parses what this parser parses.
+ Parsers.Parser // Returns a parser that repeatedly (at least once) parses what this parser parses.
+= Collection // adds "a" from the collection.
+= Map // Add a key/value pair to this map.
+= ArrayBuffer // Appends a single element to this buffer and returns ...
+= ArrayStack // Alias for push.
+= BitSet // Sets i-th bit to true. ...
+= Buffer // Append a single element to this buffer.
+= BufferProxy // Append a single element to this buffer.
+= HashSet // Add a new element to the set.
+= ImmutableSetAdaptor // Add a new element to the set.
+= JavaSetAdaptor // Add a new element to the set.
+= LinkedHashSet // Add a new element to the set.
+= ListBuffer // Appends a single element to this buffer. It takes constant ...
+= Map // Add a key/value pair to this map.
+= Map // Add two or more key/value pairs to this map.
+= Map // This method defines syntactic sugar for adding or modifying ...
+= MapProxy // Add a key/value pair to this map.
+= MapProxy // Add two or more key/value pairs to this map.
+= ObservableSet // Add a new element to the set.
+= PriorityQueue // Add two or more elements to this set.
+= PriorityQueue // Inserts a single element into the priority queue.
+= PriorityQueueProxy // Inserts a single element into the priority queue.
+= Queue // Inserts a single element at the end of the queue.
+= QueueProxy // Inserts a single element at the end of the queue.
+= Set // Add a new element to the set.
+= Set // Add two or more elements to this set.
+= SetProxy // Add a new element to the set.
+= Stack // Pushes a single element on top of the stack.
+= StackProxy // Pushes a single element on top of the stack.
+= SynchronizedBuffer // Append a single element to this buffer.
+= SynchronizedMap // Add a key/value pair to this map.
+= SynchronizedMap // Add two or more key/value pairs to this map.
+= SynchronizedPriorityQueue // Inserts a single element into the priority queue.
+= SynchronizedQueue // Inserts a single element at the end of the queue.
+= SynchronizedSet // Add a new element to the set.
+= SynchronizedStack // Pushes a single element on top of the stack.
+= RichStringBuilder // Append a single element to this buffer.
+= Reactions // Add a reaction.
+= RefBuffer // Append a single element to this buffer.
+= CachedFileStorage // adds a node, setting this.dirty to true as a side effect
+= IndexedStorage // adds a node, setting this.dirty to true as a side effect
+= SetStorage // adds a node, setting this.dirty to true as a side effect
-> Map.MapTo
-> Map.MapTo
-- List // Computes the difference between this list and the given list ...
-- Map // Remove a sequence of keys from this map
-- Set // Remove all the elements provided by an iterator ...
-- SortedMap // Remove a sequence of keys from this map
-- MutableIterable // Operator shortcut for removeAll.
-- Set // Operator shortcut for removeAll.
-- Map // Remove a sequence of keys from this map
-- MapProxy // Remove a sequence of keys from this map
-- Set // Remove all the elements provided by an iterator ...
--= Map // Remove a sequence of keys from this map
--= MapProxy // Remove a sequence of keys from this map
--= Set // Remove all the elements provided by an iterator ...
--= SetProxy // Remove all the elements provided by an iterator ...
--= SynchronizedMap // Remove a sequence of keys from this map
--= SynchronizedSet // Remove all the elements provided by an iterator ...
- BigDecimal // Subtraction of BigDecimals
- BigInt // Subtraction of BigInts
- Byte
- Char
- Double
- Enumeration.SetXX // Remove a single element from a set.
- Float
- Int
- List // Computes the difference between this list and the given object ...
- Long
- Short
- EmptyMap // Remove a key from this map
- EmptySet // Remove a single element from a set.
- HashMap // Remove a key from this map
- HashSet // Remove a single element from a set.
- IntMap // Remove a key from this map
- ListMap.Node // Creates a new mapping without the given key. ...
- ListMap // This creates a new mapping without the given key. ...
- ListSet.Node // - can be used to remove a single element from ...
- ListSet // - can be used to remove a single element from ...
- LongMap // Remove a key from this map
- Map // Remove a key from this map
- Map // Remove two or more keys from this map
- Map1 // Remove a key from this map
- Map2 // Remove a key from this map
- Map3 // Remove a key from this map
- Map4 // Remove a key from this map
- Set // Remove a single element from a set.
- Set // Remove two or more elements from this set.
- Set1 // Remove a single element from a set.
- Set2 // Remove a single element from a set.
- Set3 // Remove a single element from a set.
- Set4 // Remove a single element from a set.
- SortedMap // Remove a key from this map
- SortedMap // Remove two or more keys from this map
- TreeHashMap // Remove a key from this map
- TreeMap // Remove a key from this map
- TreeSet // Remove a single element from a set.
- UnbalancedTreeMap.Node // Remove a key from this map
- UnbalancedTreeMap // Remove a key from this map
- Map // Remove a key from this map
- MutableIterable
- Set
- ListBuffer // Removes a single element from the buffer and return ...
- Map // Remove a key from this map
- Map // Remove two or more keys from this map
- MapProxy // Remove a key from this map
- MapProxy // Remove two or more keys from this map
- Set // Remove a new element from the set.
- Set // Remove two or more elements from this set.
-= Buffer // removes "a" from the collection.
-= Collection // removes "a" from the collection.
-= Map // Remove a key from this map, noop if key is not present.
-= BitSet // Clears the i-th bit.
-= Buffer // Removes a single element from this buffer, at its first occurrence. ...
-= HashMap // Remove a key from this map, noop if key is not present.
-= HashSet // Removes a single element from a set.
-= ImmutableMapAdaptor // Remove a key from this map, noop if key is not present.
-= ImmutableSetAdaptor // Removes a single element from a set.
-= JavaMapAdaptor // Remove a key from this map, noop if key is not present.
-= JavaSetAdaptor // Removes a single element from a set.
-= LinkedHashMap // Remove a key from this map, noop if key is not present.
-= LinkedHashSet // Removes a single element from a set.
-= ListBuffer // Remove a single element from this buffer. It takes linear time ...
-= Map // Remove a key from this map, noop if key is not present.
-= Map // Remove two or more keys from this map
-= MapProxy // Remove a key from this map, noop if key is not present.
-= MapProxy // Remove two or more keys from this map
-= ObservableMap // Remove a key from this map, noop if key is not present.
-= ObservableSet // Removes a single element from a set.
-= OpenHashMap // Remove a key from this map, noop if key is not present.
-= Set // Remove two or more elements from this set.
-= Set // Removes a single element from a set.
-= SetProxy // Removes a single element from a set.
-= SynchronizedMap // Remove a key from this map, noop if key is not present.
-= SynchronizedMap // Remove two or more keys from this map
-= SynchronizedSet // Removes a single element from a set.
-= Reactions // Remove the given reaction.
-= CachedFileStorage // removes a tree, setting this.dirty to true as a side effect
-= IndexedStorage // removes a tree, setting this.dirty to true as a side effect
/% BigInt // Returns a pair of two BigInts containing (this / that) and (this % that).
/: Iterable // Similar to foldLeft but can be used as ...
/: IterableProxy // Similar to foldLeft but can be used as ...
/: Iterator // Similar to foldLeft but can be used as ...
/ BigDecimal // Division of BigDecimals
/ BigInt // Division of BigInts
/ Byte
/ Char
/ Double
/ Float
/ Int
/ Long
/ Short
:/: Document
::: List
:: List
:: Document
:\ Iterable // An alias for foldRight. ...
:\ IterableProxy // An alias for foldRight. ...
:\ Iterator // An alias for foldRight. ...
== Any // o == arg0 is the same as o.equals(arg0).
== AnyRef // o == arg0 is the same as if (o eq null) arg0 eq null else o.equals(arg0).
== Boolean
== Byte
== Char
== Double
== Float
== Int
== Long
== Short
? Actor // Receives the next message from this actor's mailbox.
? Channel // Receives the next message from this Channel.
? InputChannel // Receives the next message from this Channel.
? Parsers.Parser // Returns a parser that optionally parses what this parser parses.
? Parsers.Parser // Returns a parser that optionally parses what this parser parses.
\ NodeSeq // Projection function. Similar to XPath, use this \ "foo"
\\ NodeSeq // projection function. Similar to XPath, use this \\ 'foo
^ BigInt // Bitwise exclusive-or of BigInts
^ Boolean
^ Byte
^ Char
^ Int
^ Long
^ Short
^? Parsers.Parser // A parser combinator for partial function application
^? Parsers.Parser // A parser combinator for partial function application
^^ Parsers.Parser // A parser combinator for function application
^^ Parsers.Parser // A parser combinator for function application
^^ Parsers.UnitParser // A parser combinator for function application
^^^ Parsers.Parser
| BigInt // Bitwise or of BigInts
| Boolean
| Byte
| Char
| Enumeration.Set32 // Equivalent to ++ for bit sets. Returns a set ...
| Enumeration.Set32 // Equivalent to + for bit sets. Returns a set ...
| Enumeration.Set64 // Equivalent to ++ for bit sets. Returns a set ...
| Enumeration.Set64 // Equivalent to + for bit sets. Returns a set ...
| Enumeration.SetXX // Equivalent to ++ for bit sets. Returns a set ...
| Enumeration.SetXX // Equivalent to + for bit sets. Returns a set ...
| Int
| Long
| Short
| Parsers.Parser // A parser combinator for alternative composition
| Parsers.Parser // A parser combinator for alternative composition
| Parsers.UnitParser // A parser combinator for alternative composition
|| Boolean
||| Parsers.Parser
||| Parsers.Parser // A parser combinator for alternative with longest match composition
||| Parsers.Parser // A parser combinator for alternative with longest match composition
||| Parsers.UnitParser // A parser combinator for alternative with longest match composition
~! Parsers.Parser // A parser combinator for non-back-tracking sequential composition
~! Parsers.Parser // A parser combinator for non-back-tracking sequential composition with a unit-parser
~! Parsers.Parser // A parser combinator for non-back-tracking sequential composition
~! Parsers.UnitParser // A parser combinator for non-back-tracking sequential composition with a unit-parser
~! Parsers.UnitParser // A parser combinator for non-back-tracking sequential composition
~> Parsers.Parser // A parser combinator for sequential composition which keeps only the right result
~ BigInt // Returns the bitwise complement of this BigNum
~ Parsers.OnceParser // A parser combinator for sequential composition
~ Parsers.Parser // A parser combinator for sequential composition
~ Parsers
~ Parsers.OnceParser // A parser combinator for sequential composition with a unit-parser
~ Parsers.OnceParser // A parser combinator for sequential composition
~ Parsers.Parser // A parser combinator for sequential composition with a unit-parser
~ Parsers.Parser // A parser combinator for sequential composition
~ Parsers.UnitOnceParser // A parser combinator for sequential composition with a unit-parser
~ Parsers.UnitOnceParser // A parser combinator for sequential composition
~ Parsers.UnitParser // A parser combinator for sequential composition with a unit-parser
~ Parsers.UnitParser // A parser combinator for sequential composition
unary_! Boolean
unary_+ Byte
unary_+ Char
unary_+ Double
unary_+ Float
unary_+ Int
unary_+ Long
unary_+ Short
unary_- BigDecimal // Returns a BigDecimal whose value is the negation of this BigDecimal
unary_- BigInt // Returns a BigInt whose value is the negation of this BigInt
unary_- Byte
unary_- Char
unary_- Double
unary_- Float
unary_- Int
unary_- Long
unary_- Short
unary_~ Byte
unary_~ Char
unary_~ Int
unary_~ Long
unary_~ Short

How to use MySQLdb with Python and Django in OSX 10.6?

Try this: This solved the issue for me .

pip install MySQL-python

Check if object value exists within a Javascript array of objects and if not add a new object to array

xorWith in Lodash can be used to achieve this

let objects = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
let existingObject = { id: 1, username: 'fred' };
let newObject = { id: 1729, username: 'Ramanujan' }

_.xorWith(objects, [existingObject], _.isEqual)
// returns [ { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

_.xorWith(objects, [newObject], _.isEqual)
// returns [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ,{ id: 1729, username: 'Ramanujan' } ]

Presenting a UIAlertController properly on an iPad using iOS 8

Just add the following code before presenting your action sheet:

if let popoverController = optionMenu.popoverPresentationController {
    popoverController.sourceView = self.view
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
    popoverController.permittedArrowDirections = []
}

Android and Facebook share intent

    public void invokeShare(Activity activity, String quote, String credit) {
    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, activity.getString(R.string.share_subject));
    shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Example text");    
    shareIntent.putExtra("com.facebook.platform.extra.APPLICATION_ID", activity.getString(R.string.app_id));                        
    activity.startActivity(Intent.createChooser(shareIntent, activity.getString(R.string.share_title)));
}

Console logging for react?

Here are some more console logging "pro tips":

console.table

var animals = [
    { animal: 'Horse', name: 'Henry', age: 43 },
    { animal: 'Dog', name: 'Fred', age: 13 },
    { animal: 'Cat', name: 'Frodo', age: 18 }
];

console.table(animals);

console.table

console.trace

Shows you the call stack for leading up to the console.

console.trace

You can even customise your consoles to make them stand out

console.todo = function(msg) {
    console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}

console.important = function(msg) {
    console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}

console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);

console.todo

If you really want to level up don't limit your self to the console statement.

Here is a great post on how you can integrate a chrome debugger right into your code editor!

https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037

iPhone UITextField - Change placeholder text color

[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];

How can I stop float left?

You should also check out the "clear" property in css in case removing a float isn't an option

How can I list the scheduled jobs running in my database?

Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:

GRANT CREATE JOB TO scott;

After this statement is executed, scott can create jobs, schedules, or programs in his schema.

copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239

Error after upgrading pip: cannot import name 'main'

Check if pip has been cached on another path, to do so, call $ which pip and check that the path is different from the one prompted in the error, if that's the case run:

$ hash -r

When the cache is clear, pip will be working again. reference: http://cheng.logdown.com/posts/2015/06/14/-usr-bin-pip-no-such-file-or-directory

Stretch horizontal ul to fit width of div

People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">

Reading NFC Tags with iPhone 6 / iOS 8

From digging into the iOS 8 docs that are available as of Sept 9th 3:30pm there is no mention of developer access to the NFC controller to perform any NFC operations; that includes reading tags, writing tags, pairing, payments, tag emulation... Given its an NXP controller the hardware has the capability to perform these features. They did mention a 3rd party app for the watch that allowed a hotel guest to open their room door with NFC. This is a classic use case for NFC and gives some indication that the NFC controller will be open to developers at some point. Remember, the watch is not supposed to be released until Q1 2015. So for now I'd say it's closed but will be open soon. Given the 'newness' of contactless payments for the general US consumer and the recent security breaches its not surprising Apple wants to keep this closed for a while.

Disclosure: Im the CEO of GoToTags, an NFC company with obvious vested interest in Apple opening up NFC to developers.

--- Correction & Update ---

The hotel app actually uses Bluetooth, not NFC. NFC is still often used for door unlocking, just not in this one example. NFC could be used if the watch has an open NFC controller.

I do know that Apple is aware of all of this and is discussing this with their top developers and stakeholders. There has already been massive negative push back on the lack of support for reading tags. As often the case in the past, I expect Apple to eventually open this up to developers for non-payment related functionality (reading tags, pairing). I do not think Apple will ever allow other wallets though. File sharing will likely be left to AirDrop as well.

--- Update on March 23rd 2016 ---

I am continually asked for updates about this topic, often with people referencing this post. With Apple releasing the iPhone SE, many are again asking why Apple has not supported tag reading yet. In summary Apple is more focused on Apple Pay succeeding than the other use cases for NFC for now. Apple could make a lot of money from Apple Pay, and has less to make from the other uses for NFC. Apple will likely open up NFC tag reading when they feel that consumer trust and security with NFC and Apple Pay is such that it wont put Apple Pay at risk. Further information here.

--- Update on May 24th 2017 ---

A developer in Greece has hacked the iPhone 6s to get it to read NFC tags via the NFC private frameworks; more info & video. While this isn't a long term solution, it provides some guidance on some outstanding question: Is there enough power in the iPhone's NFC controller to power an NFC tag? Looks like the answer is yes. From initial testing the range is a few cm, which isn't too bad. It might also be the power is tunable; this is being investigated at this time. The implications of this are significant. If the older model phones do have enough RF power for tag reading/writing, then when Apple does open up the SDK it means there will be 100Ms of iPhones that can read NFC tags, vs the case where only the new iPhones could.

Setting public class variables

If you are going to follow the examples given (using getter/setter or setting it in the constructor) change it to private since those are ways to control what is set in the variable.

It doesn't make sense to keep the property public with all those things added to the class.

What does $@ mean in a shell script?

$@ is all of the parameters passed to the script.

For instance, if you call ./someScript.sh foo bar then $@ will be equal to foo bar.

If you do:

./someScript.sh foo bar

and then inside someScript.sh reference:

umbrella_corp_options "$@"

this will be passed to umbrella_corp_options with each individual parameter enclosed in double quotes, allowing to take parameters with blank space from the caller and pass them on.

How to generate a random number in C++?

Using modulo may introduce bias into the random numbers, depending on the random number generator. See this question for more info. Of course, it's perfectly possible to get repeating numbers in a random sequence.

Try some C++11 features for better distribution:

#include <random>
#include <iostream>

int main()
{
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]

    std::cout << dist6(rng) << std::endl;
}

See this question/answer for more info on C++11 random numbers. The above isn't the only way to do this, but is one way.

How do I upgrade to Python 3.6 with conda?

I'm using a Mac OS Mojave

These 4 steps worked for me.

  1. conda update conda
  2. conda install python=3.6
  3. conda install anaconda-client
  4. conda update anaconda

Prevent PDF file from downloading and printing

Creating a video with QuickTime's screen capture or anything similar kind of defeats all the effort to protect your document file from being copied.

How to download an entire directory and subdirectories using wget?

This link just gave me the best answer:

$ wget --no-clobber --convert-links --random-wait -r -p --level 1 -E -e robots=off -U mozilla http://base.site/dir/

Worked like a charm.

How to "comment-out" (add comment) in a batch/cmd?

The :: instead of REM was preferably used in the days that computers weren't very fast. REM'ed line are read and then ingnored. ::'ed line are ignored all the way. This could speed up your code in "the old days". Further more after a REM you need a space, after :: you don't.

And as said in the first comment: you can add info to any line you feel the need to

SET DATETIME=%DTS:~0,8%-%DTS:~8,6% ::Makes YYYYMMDD-HHMMSS

As for the skipping of parts. Putting REM in front of every line can be rather time consuming. As mentioned using GOTO to skip parts is an easy way to skip large pieces of code. Be sure to set a :LABEL at the point you want the code to continue.

SOME CODE

GOTO LABEL  ::REM OUT THIS LINE TO EXECUTE THE CODE BETWEEN THIS GOTO AND :LABEL

SOME CODE TO SKIP
.
LAST LINE OF CODE TO SKIP

:LABEL
CODE TO EXECUTE

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

I followed the sample code from @codeslord, but for some reason I had to access my screenshot data differently:

 # Open the Firefox webdriver
 driver = webdriver.Firefox()
 # Find the element that you're interested in
 imagepanel = driver.find_element_by_class_name("panel-height-helper")
 # Access the data bytes for the web element
 datatowrite = imagepanel.screenshot_as_png
 # Write the byte data to a file
 outfile = open("imagepanel.png", "wb")
 outfile.write(datatowrite)
 outfile.close()

(using Python 3.7, Selenium 3.141.0 and Mozilla Geckodriver 71.0.0.7222)

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

I added in android.support.design.widget.NawigationView this parameter:

android:layout_gravity="start"

And problem was solved.

Difference between except: and except Exception as e: in Python

Another way to look at this. Check out the details of the exception:

In [49]: try: 
    ...:     open('file.DNE.txt') 
    ...: except Exception as  e: 
    ...:     print(dir(e)) 
    ...:                                                                                                                                    
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']

There are lots of "things" to access using the 'as e' syntax.

This code was solely meant to show the details of this instance.

Is there an Eclipse plugin to run system shell in the Console?

I just found out about WickedShell, but it seems to work wrong with GNU/Linux and bash. Seems like some sort of encoding issue, all the characters in my prompt are displayed wrong.

Seems to be the best (only) tool for the job anyways, so I'll give it some more testing and see if it's good enough. I'll contact the developer anyways about this issue.

Sending email with gmail smtp with codeigniter email library

Change it to the following:

$ci = get_instance();
$ci->load->library('email');
$config['protocol'] = "smtp";
$config['smtp_host'] = "ssl://smtp.gmail.com";
$config['smtp_port'] = "465";
$config['smtp_user'] = "[email protected]"; 
$config['smtp_pass'] = "yourpassword";
$config['charset'] = "utf-8";
$config['mailtype'] = "html";
$config['newline'] = "\r\n";

$ci->email->initialize($config);

$ci->email->from('[email protected]', 'Blabla');
$list = array('[email protected]');
$ci->email->to($list);
$this->email->reply_to('[email protected]', 'Explendid Videos');
$ci->email->subject('This is an email test');
$ci->email->message('It is working. Great!');
$ci->email->send();

How to update-alternatives to Python 3 without breaking apt?

replace

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python3.5 3

with

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python3.5 3

e.g. installing into /usr/local/bin instead of /usr/bin.

and ensure the /usr/local/bin is before /usr/bin in PATH.

i.e.

[bash:~] $ echo $PATH
/usr/local/bin:/usr/bin:/bin

Ensure this always is the case by adding

export PATH=/usr/local/bin:$PATH

to the end of your ~/.bashrc file. Prefixing the PATH environment variable with custom bin folder such as /usr/local/bin or /opt/<some install>/bin is generally recommended to ensure that customizations are found before the default system ones.

jQuery: Adding two attributes via the .attr(); method

Should work:

.attr({
    target:"nw", 
    title:"Opens in a new window",
    "data-value":"internal link" // attributes which contain dash(-) should be covered in quotes.
});

Note:

" When setting multiple attributes, the quotes around attribute names are optional.

WARNING: When setting the 'class' attribute, you must always use quotes!

From the jQuery documentation (Sep 2016) for .attr:

Attempting to change the type attribute on an input or button element created via document.createElement() will throw an exception on Internet Explorer 8 or older.

Edit:
For future reference... To get a single attribute you would use

var strAttribute = $(".something").attr("title");

To set a single attribute you would use

$(".something").attr("title","Test");

To set multiple attributes you need to wrap everything in { ... }

$(".something").attr( { title:"Test", alt:"Test2" } );

Edit - If you're trying to get/set the 'checked' attribute from a checkbox...

You will need to use prop() as of jQuery 1.6+

the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

...the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does

So to get the checked status of a checkbox, you should use:

$('#checkbox1').prop('checked'); // Returns true/false

Or to set the checkbox as checked or unchecked you should use:

$('#checkbox1').prop('checked', true); // To check it
$('#checkbox1').prop('checked', false); // To uncheck it

How to ssh connect through python Paramiko with ppk public key

For me I doing this:

import paramiko
hostname = 'my hostname or IP' 
myuser   = 'the user to ssh connect'
mySSHK   = '/path/to/sshkey.pub'
sshcon   = paramiko.SSHClient()  # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed

works for me pretty ok

How do I escape a percentage sign in T-SQL?

Use brackets. So to look for 75%

WHERE MyCol LIKE '%75[%]%'

This is simpler than ESCAPE and common to most RDBMSes.

Share data between html pages

I know this is an old post, but figured I'd share my two cents. @Neji is correct in that you can use sessionStorage.getItem('label'), and sessionStorage.setItem('label', 'value') (although he had the setItem parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:

var val = sessionStorage.myValue

in place of getItem and

sessionStorage.myValue = 'value'

in place of setItem.

Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:

sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object

The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject all you get is [object Object], which doesn't help you too much.

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

Five equal columns in twitter bootstrap

Is someone uses bootstrap-sass (v3), here is simple code for 5 columns using bootstrap mixings:

  .col-xs-5ths {
     @include make-xs-column(2.4);
  }

  @media (min-width: $screen-sm-min) {
     .col-sm-5ths {
        @include make-sm-column(2.4);
     }
  }

  @media (min-width: $screen-md-min) {
     .col-md-5ths {
        @include make-md-column(2.4);
     }
  }

  @media (min-width: $screen-lg-min) {
     .col-lg-5ths {
        @include make-lg-column(2.4);
     }
  }

Make sure you have included:

@import "bootstrap/variables";
@import "bootstrap/mixins";

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

How can I use an array of function pointers?

The simplest solution is to give the address of the final vector you want , and modify it inside the function.

void calculation(double result[] ){  //do the calculation on result

   result[0] = 10+5;
   result[1] = 10 +6;
   .....
}

int main(){

    double result[10] = {0}; //this is the vector of the results

    calculation(result);  //this will modify result
}

Why do I get "'property cannot be assigned" when sending an SMTP email?

public static void SendMail(MailMessage Message)
{
    SmtpClient client = new SmtpClient();
    client.Host = "smtp.googlemail.com";
    client.Port = 587;
    client.UseDefaultCredentials = false;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.EnableSsl = true;
    client.Credentials = new NetworkCredential("[email protected]", "password");
    client.Send(Message); 
}

Determine SQL Server Database Size

According to SQL2000 help, sp_spaceused includes data and indexes.

This script should do:

CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18), 
data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))

EXEC sp_msforeachtable 'INSERT INTO #t EXEC sp_spaceused ''?'''
-- SELECT * FROM #t ORDER BY name
-- SELECT name, CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)) FROM #t ORDER BY name
SELECT SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3))) FROM #t
DROP TABLE #t

How do I declare a namespace in JavaScript?

I like this:

var yourNamespace = {

    foo: function() {
    },

    bar: function() {
    }
};

...

yourNamespace.foo();

Razor View Without Layout

Procedure 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder

This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.

 @{
 var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
 string cLayout = "";
 if (controller == "Webmaster") {
 cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
 }
 else {
 cLayout = "~/Views/Shared/_Layout.cshtml";
 }
 Layout = cLayout;
 }

Procedure 2 : Set Layout by Returning from ActionResult

One the the great feature of ASP.NET MVC is that, we can override the default layout rendering by returning the layout from the ActionResult. So, this is also a way to render different Layout in your ASP.NET MVC application. Following code sample show how it can be done.

public ActionResult Index()
{
 SampleModel model = new SampleModel();
 //Any Logic
 return View("Index", "_WebmasterLayout", model);
}

Procedure 3 : View - wise Layout (By defining Layout within each view on the top)

ASP.NET MVC provides us such a great feature & faxibility to override the default layout rendering by defining the layout on the view. To implement this we can write our code in following manner in each View.

@{
   Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}

Procedure 4 : Placing _ViewStart file in each of the directories

This is a very useful way to set different Layouts for each Controller in your ASP.NET MVC application. If we want to set default Layout for each directories than we can do this by putting _ViewStart file in each of the directories with the required Layout information as shown below:

@{
  Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}

Using %f with strftime() in Python to get microseconds

You are looking at the wrong documentation. The time module has different documentation.

You can use the datetime module strftime like this:

>>> from datetime import datetime
>>>
>>> now = datetime.now()
>>> now.strftime("%H:%M:%S.%f")
'12:19:40.948000'

How can I get color-int from color resource?

Accessing colors from a non-activity class can be difficult. One of the alternatives that I found was using enum. enum offers a lot of flexibility.

public enum Colors
{
  COLOR0(0x26, 0x32, 0x38),    // R, G, B
  COLOR1(0xD8, 0x1B, 0x60),
  COLOR2(0xFF, 0xFF, 0x72),
  COLOR3(0x64, 0xDD, 0x17);


  private final int R;
  private final int G;
  private final int B;

  Colors(final int R, final int G, final int B)
  {
    this.R = R;
    this.G = G;
    this.B = B;
  }

  public int getColor()
  {
    return (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);
  }

  public int getR()
  {
    return R;
  }

  public int getG()
  {
    return G;
  }

  public int getB()
  {
    return B;
  }
}

SQL query question: SELECT ... NOT IN

SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
  and idCustomer is not null

Make sure your list parameter does not contain null values.

Here's an explanation:

WHERE field1 NOT IN (1, 2, 3, null)

is the same as:

WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
  • That last comparision evaluates to null.
  • That null is OR'd with the rest of the boolean expression, yielding null. (*)
  • null is negated, yielding null.
  • null is not true - the where clause only keeps true rows, so all rows are filtered.

(*) Edit: this explanation is pretty good, but I wish to address one thing to stave off future nit-picking. (TRUE OR NULL) would evaluate to TRUE. This is relevant if field1 = 3, for example. That TRUE value would be negated to FALSE and the row would be filtered.

Remove duplicate elements from array in Ruby

You can remove the duplicate elements with the uniq method:

array.uniq  # => [1, 2, 4, 5, 6, 7, 8]

What might also be useful to know is that uniq takes a block, so if you have a have an array of keys:

["bucket1:file1", "bucket2:file1", "bucket3:file2", "bucket4:file2"]

and you want to know what the unique files are, you can find it out with:

a.uniq { |f| f[/\d+$/] }.map { |p| p.split(':').last }

Using OR & AND in COUNTIFS

In a more general case:

N( A union B) = N(A) + N(B) - N(A intersect B) 
= COUNTIFS(A1:A196,"Yes",J1:J196,"Agree")+COUNTIFS(A1:A196,"No",J1:J196,"Agree")-A1:A196,"Yes",A1:A196,"No")

how to download file in react js

If you are using React Router, use this:

<Link to="/files/myfile.pdf" target="_blank" download>Download</Link>

Where /files/myfile.pdf is inside your public folder.

How can I insert into a BLOB column from an insert statement in sqldeveloper?

Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:

insert into blob_fun values(1, hextoraw('453d7a34'));

453d7a34 is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.

How can I set the font-family & font-size inside of a div?

You need a semicolon after font-family: Arial, Helvetica, sans-serif. This will make your updated code the following:

<!DOCTYPE>
<html>
    <head>
        <title>DIV Font</title>

        <style>
            .my_text
            {
                font-family:    Arial, Helvetica, sans-serif;
                font-size:      40px;
                font-weight:    bold;
            }
        </style>
    </head>

    <body>
        <div class="my_text">some text</div>
    </body>
</html>

Local package.json exists, but node_modules missing

This issue can also raise when you change your system password but not the same updated on your .npmrc file that exist on path C:\Users\user_name, so update your password there too.

please check on it and run npm install first and then npm start.

What's the syntax to import a class in a default package in Java?

You can't import classes from the default package. You should avoid using the default package except for very small example programs.

From the Java language specification:

It is a compile time error to import a type from the unnamed package.

Laravel Eloquent update just if changes have been made

You're already doing it!

save() will check if something in the model has changed. If it hasn't it won't run a db query.

Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate:

protected function performUpdate(Builder $query, array $options = [])
{
    $dirty = $this->getDirty();

    if (count($dirty) > 0)
    {
        // runs update query
    }

    return true;
}

The getDirty() method simply compares the current attributes with a copy saved in original when the model is created. This is done in the syncOriginal() method:

public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

public function syncOriginal()
{
    $this->original = $this->attributes;

    return $this;
}

If you want to check if the model is dirty just call isDirty():

if($product->isDirty()){
    // changes have been made
}

Or if you want to check a certain attribute:

if($product->isDirty('price')){
    // price has changed
}

How to recover the deleted files using "rm -R" command in linux server?

since answers are disappointing I would like suggest a way in which I got deleted stuff back.

I use an ide to code and accidently I used rm -rf from terminal to remove complete folder. Thanks to ide I recoved it back by reverting the change from ide's local history.

(my ide is intelliJ but all ide's support history backup)

jQuery & CSS - Remove/Add display:none

You're not giving us much information but in general this might be a solution:

$("div.news").css("display", "block");

How can I remount my Android/system as read-write in a bash script using adb?

Otherwise... if

getenforce

returns

Enforcing

Then maybe you should call

setenforce 0 
mount -o rw,remount /system 
setenforce 1

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Shell script "for" loop syntax

Use:

max=10
for i in `eval echo {2..$max}`
do
    echo $i
done

You need the explicit 'eval' call to reevaluate the {} after variable substitution.

require is not defined? Node.js

To supplement what everyone else has said above, your js file is being read on the client side when you have a path to it in your HTML file. At least that was the problem for me. I had it as a script in my tag in my index.html Hope this helps!

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

To remove the floating section header sections completely, you can do this:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[UIView alloc] init];
}

return nil doesn't work.

To disable floating but still show section headers you can provide a custom view with its own behaviours.

How to print React component on click of a button?

If you're looking to print specific data that you already have access to, whether it's from a Store, AJAX, or available elsewhere, you can leverage my library react-print.

https://github.com/captray/react-print

It makes creating print templates much easier (assuming you already have a dependency on react). You just need to tag your HTML appropriately.

This ID should be added higher up in your actual DOM tree to exclude everything except the "print mount" below.

<div id="react-no-print"> 

This is where your react-print component will mount and wrap your template that you create:

<div id="print-mount"></div>

An example looks something like this:

var PrintTemplate = require('react-print');
var ReactDOM = require('react-dom');
var React = require('react');

var MyTemplate = React.createClass({
    render() {
        return (
            <PrintTemplate>
                <p>Your custom</p>
                <span>print stuff goes</span>
                <h1>Here</h1>
            </PrintTemplate>
        );
    }
});

ReactDOM.render(<MyTemplate/>, document.getElementById('print-mount'));

It's worth noting that you can create new or utilize existing child components inside of your template, and everything should render fine for printing.

Set environment variables on Mac OS X Lion

Unfortunately none of these answers solved the specific problem I had.

Here's a simple solution without having to mess with bash. In my case, it was getting gradle to work (for Android Studio).

Btw, These steps relate to OSX (Mountain Lion 10.8.5)

  • Open up Terminal.
  • Run the following command:

    sudo nano /etc/paths (or sudo vim /etc/paths for vim)

    nano

  • Go to the bottom of the file, and enter the path you wish to add.
  • Hit control-x to quit.
  • Enter 'Y' to save the modified buffer.
  • Open a new terminal window then type:

    echo $PATH

You should see the new path appended to the end of the PATH

I got these details from this post:

http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.UkED3rxPp3Q

I hope that can help someone else

Open another application from your own (intent)

Since applications aren't allowed to change many of the phone settings, you can open a settings activity just like another application.

Look at you LogCat output after you actually modified the setting manually:

INFO/ActivityManager(1306): Starting activity: Intent { act=android.intent.action.MAIN cmp=com.android.settings/.DevelopmentSettings } from pid 1924

Then use this to display the settings page from your app:

String SettingsPage = "com.android.settings/.DevelopmentSettings";

try
{
Intent intent = new Intent(Intent.ACTION_MAIN);             
intent.setComponent(ComponentName.unflattenFromString(SettingsPage));             
intent.addCategory(Intent.CATEGORY_LAUNCHER );             
startActivity(intent); 
}
catch (ActivityNotFoundException e)
{
 log it
}

jquery click event not firing?

Is this markup added to the DOM asynchronously? You will need to use live in that case:

NOTE: .live has been deprecated and removed in the latest versions of jQuery (for good reason). Please refer to the event delegation strategy below for usage and solution.

<script>
    $(document).ready(function(){
        $('.play_navigation a').live('click', function(){
            console.log("this is the click");
            return false;
        });
    });
</script>

The fact that you are able to re-run your script block and have it work tells me that for some reason the elements weren't available at the time of binding or the binding was removed at some point. If the elements weren't there at bind-time, you will need to use live (or event delegation, preferably). Otherwise, you need to check your code for something else that would be removing the binding.

Using jQuery 1.7 event delegation:

$(function () {

    $('.play_navigation').on('click', 'a', function (e) {
        console.log('this is the click');
        e.preventDefault();
    });

});

You can also delegate events up to the document if you feel that you would like to bind the event before the document is ready (note that this also causes jQuery to examine every click event to determine if the element matches the appropriate selector):

$(document).on('click', '.play_navigation a', function (e) {
    console.log('this is the click');
    e.preventDefault();
});

How to hide UINavigationBar 1px bottom line

Another option if you want to preserve translucency and you don't want to subclass every UINavigationController in your app:

#import <objc/runtime.h>

@implementation UINavigationController (NoShadow)

+ (void)load {
    Method original = class_getInstanceMethod(self, @selector(viewWillAppear:));
    Method swizzled = class_getInstanceMethod(self, @selector(swizzled_viewWillAppear:));
    method_exchangeImplementations(original, swizzled);
}

+ (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }

    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }

    return nil;
}

- (void)swizzled_viewWillAppear:(BOOL)animated {
    UIImageView *shadow = [UINavigationController findHairlineImageViewUnder:self.navigationBar];
    shadow.hidden = YES;

    [self swizzled_viewWillAppear:animated];
}

@end

What is TypeScript and why would I use it in place of JavaScript?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Five years later, this is an OK overview, but look at Lodewijk's answer below for more depth

1000ft view...

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

To get an idea of what I mean, watch Microsoft's introductory video on the language.

For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.

It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.

Are there other technologies like it?

There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code)

Example

As an example, here's some TypeScript (you can play with this in the TypeScript Playground)

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}  

And here's the JavaScript it would produce

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

It's also capable of inferring types which aren't explicitly declared, for example, it would determine the greet() method returns a string.

Debugging TypeScript

Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio

Want to know more?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Check out Lodewijk's answer to this question for some more current detail.

How to write to an existing excel file without overwriting data (using pandas)?

writer = pd.ExcelWriter('prueba1.xlsx'engine='openpyxl',keep_date_col=True)

The "keep_date_col" hope help you

What do \t and \b do?

Backspace and tab both move the cursor position. Neither is truly a 'printable' character.

Your code says:

  1. print "foo"
  2. move the cursor back one space
  3. move the cursor forward to the next tabstop
  4. output "bar".

To get the output you expect, you need printf("foo\b \tbar"). Note the extra 'space'. That says:

  1. output "foo"
  2. move the cursor back one space
  3. output a ' ' (this replaces the second 'o').
  4. move the cursor forward to the next tabstop
  5. output "bar".

Most of the time it is inappropriate to use tabs and backspace for formatting your program output. Learn to use printf() formatting specifiers. Rendering of tabs can vary drastically depending on how the output is viewed.

This little script shows one way to alter your terminal's tab rendering. Tested on Ubuntu + gnome-terminal:

#!/bin/bash
tabs -8 
echo -e "\tnormal tabstop"
for x in `seq 2 10`; do
  tabs $x
  echo -e "\ttabstop=$x"
 done

tabs -8
echo -e "\tnormal tabstop"

Also see man setterm and regtabs.

And if you redirect your output or just write to a file, tabs will quite commonly be displayed as fewer than the standard 8 chars, especially in "programming" editors and IDEs.

So in otherwords:

printf("%-8s%s", "foo", "bar"); /* this will ALWAYS output "foo     bar" */
printf("foo\tbar"); /* who knows how this will be rendered */

IMHO, tabs in general are rarely appropriate for anything. An exception might be generating output for a program that requires tab-separated-value input files (similar to comma separated value).

Backspace '\b' is a different story... it should never be used to create a text file since it will just make a text editor spit out garbage. But it does have many applications in writing interactive command line programs that cannot be accomplished with format strings alone. If you find yourself needing it a lot, check out "ncurses", which gives you much better control over where your output goes on the terminal screen. And typically, since it's 2011 and not 1995, a GUI is usually easier to deal with for highly interactive programs. But again, there are exceptions. Like writing a telnet server or console for a new scripting language.

Send XML data to webservice using php curl

Check this one. It will work.

function fetch($i1,$i2,$i3,$i4)
{
$input_data = '<I> 
                <i1>'.$i1.'</i1> 
                <i2>'.$i2.'</i2> 
                <i3>'.$i2.'</i3> 
                <i4>'.$i3.'</i4> 
              </I>';
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_PORT => "8080",
  CURLOPT_URL => "http://192.168.1.100:8080/avaliablity",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $input_data,
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Content-Type: application/xml"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
}

fetch('i1','i2','i3','i4');

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Difference between Encapsulation and Abstraction

Yes, it is true that Abstraction and Encapsulation are about hiding.

  • Using only relevant details and hiding unnecessary data at Design Level is called Abstraction. (Like selecting only relevant properties for a class 'Car' to make it more abstract or general.)

  • Encapsulation is the hiding of data at Implementation Level. Like how to actually hide data from direct/external access. This is done by binding data and methods to a single entity/unit to prevent external access. Thus, encapsulation is also known as data hiding at implementation level.

Cannot bulk load. Operating system error code 5 (Access is denied.)

This is what worked for me:

Log on SSIS with Windows authentication.

1. Open services and find MSSQL NT Service account name and copy it:

enter image description here

2. Open folder from which SQL server should read from. Security - Group or user names tab - Add and paste there copied account:**

enter image description here

  1. You will probably get "Multiple names found error", just select MSSQL user:

enter image description here

Your BULK INSERT query should run fine now. If problem persists try adding SQL Server Agent account to folder permissions in same way. Make sure you restart MSSQL server in services after you are done.

Should __init__() call the parent class's __init__()?

In Python, calling the super-class' __init__ is optional. If you call it, it is then also optional whether to use the super identifier, or whether to explicitly name the super class:

object.__init__(self)

In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__.

On the other hand, for __new__, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.

How to tell if homebrew is installed on Mac OS X

I just type brew -v in terminal if you have it it will respond with the version number installed.

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

Angular - How to apply [ngStyle] conditions

[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"

Properly Handling Errors in VBA (Excel)

You've got one truly marvelous answer from ray023, but your comment that it's probably overkill is apt. For a "lighter" version....

Block 1 is, IMHO, bad practice. As already pointed out by osknows, mixing error-handling with normal-path code is Not Good. For one thing, if a new error is thrown while there's an Error condition in effect you will not get an opportunity to handle it (unless you're calling from a routine that also has an error handler, where the execution will "bubble up").

Block 2 looks like an imitation of a Try/Catch block. It should be okay, but it's not The VBA Way. Block 3 is a variation on Block 2.

Block 4 is a bare-bones version of The VBA Way. I would strongly advise using it, or something like it, because it's what any other VBA programmer inherting the code will expect. Let me present a small expansion, though:

Private Sub DoSomething()
On Error GoTo ErrHandler

'Dim as required

'functional code that might throw errors

ExitSub:
    'any always-execute (cleanup?) code goes here -- analagous to a Finally block.
    'don't forget to do this -- you don't want to fall into error handling when there's no error
    Exit Sub

ErrHandler:
    'can Select Case on Err.Number if there are any you want to handle specially

    'display to user
    MsgBox "Something's wrong: " & vbCrLf & Err.Description

    'or use a central DisplayErr routine, written Public in a Module
    DisplayErr Err.Number, Err.Description

    Resume ExitSub
    Resume
End Sub

Note that second Resume. This is a trick I learned recently: It will never execute in normal processing, since the Resume <label> statement will send the execution elsewhere. It can be a godsend for debugging, though. When you get an error notification, choose Debug (or press Ctl-Break, then choose Debug when you get the "Execution was interrupted" message). The next (highlighted) statement will be either the MsgBox or the following statement. Use "Set Next Statement" (Ctl-F9) to highlight the bare Resume, then press F8. This will show you exactly where the error was thrown.

As to your objection to this format "jumping around", A) it's what VBA programmers expect, as stated previously, & B) your routines should be short enough that it's not far to jump.

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

I had this problem recently. This was happen, because the permissions of user database. check permissions of user database, maybe the user do not have permission to write on db.

Checkbox value true/false

Checkboxes can be really weird in JS. You're best off checking for the presence of the checked attribute. (I've had older jQuery versions return true even if checked is set to 'false'.) Once you've determined that something is checked then you can get the value from the value attribute.

Convert String To date in PHP

If you're up for it, use the DateTime class

How can I access Oracle from Python?

Here is how my code looks like. It also shows an example of how to use query parameters using a dictionary. It works on using Python 3.6:

import cx_Oracle

CONN_INFO = {
    'host': 'xxx.xx.xxx.x',
    'port': 12345,
    'user': 'SOME_SCHEMA',
    'psw': 'SECRETE',
    'service': 'service.server.com'
}

CONN_STR = '{user}/{psw}@{host}:{port}/{service}'.format(**CONN_INFO)

QUERY = '''
    SELECT
        *
    FROM
        USER
    WHERE
        NAME = :name
'''


class DB:
    def __init__(self):
        self.conn = cx_Oracle.connect(CONN_STR)

    def query(self, query, params=None):
        cursor = self.conn.cursor()
        result = cursor.execute(query, params).fetchall()
        cursor.close()
        return result


db = DB()
result = db.query(QUERY, {'name': 'happy'})

Writing numerical values on the plot with Matplotlib

Use pyplot.text() (import matplotlib.pyplot as plt)

import matplotlib.pyplot as plt

x=[1,2,3]
y=[9,8,7]

plt.plot(x,y)
for a,b in zip(x, y): 
    plt.text(a, b, str(b))
plt.show()

Guzzlehttp - How get the body of a response from Guzzle 6?

For get response in JSON format :

  1.$response = (string) $res->getBody();
      $response =json_decode($response); // Using this you can access any key like below
     
     $key_value = $response->key_name; //access key  

  2. $response = json_decode($res->getBody(),true);
     
     $key_value =   $response['key_name'];//access key

How can I access "static" class variables within class methods in Python?

class Foo(object):
     bar = 1
     def bah(self):
         print Foo.bar

f = Foo() 
f.bah()

An example of how to use getopts in bash

POSIX 7 example

It is also worth checking the example from the standard: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html

aflag=
bflag=
while getopts ab: name
do
    case $name in
    a)    aflag=1;;
    b)    bflag=1
          bval="$OPTARG";;
    ?)   printf "Usage: %s: [-a] [-b value] args\n" $0
          exit 2;;
    esac
done
if [ ! -z "$aflag" ]; then
    printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
    printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"

And then we can try it out:

$ sh a.sh
Remaining arguments are: 
$ sh a.sh -a
Option -a specified
Remaining arguments are: 
$ sh a.sh -b
No arg for -b option
Usage: a.sh: [-a] [-b value] args
$ sh a.sh -b myval
Option -b "myval" specified
Remaining arguments are: 
$ sh a.sh -a -b myval
Option -a specified
Option -b "myval" specified
Remaining arguments are: 
$ sh a.sh remain
Remaining arguments are: remain
$ sh a.sh -- -a remain
Remaining arguments are: -a remain

Tested in Ubuntu 17.10, sh is dash 0.5.8.

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

Use Query.setParameterList(), Javadoc here.

There are four variants to pick from.

How to apply `git diff` patch without Git installed?

Use

git apply patchfile

if possible.

patch -p1 < patchfile 

has potential side-effect.

git apply also handles file adds, deletes, and renames if they're described in the git diff format, which patch won't do. Finally, git apply is an "apply all or abort all" model where either everything is applied or nothing is, whereas patch can partially apply patch files, leaving your working directory in a weird state.

Use querystring variables in MVC controller

My problem was overwriting my query string parameters with default values:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = ""}
);

No matter what I plugged into query string or how only key="" results.

Then got rid of default overwrites using UrlParameter.Optional:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = UrlParameter.Optional }
);

now

prices/{key} 

or

prices?key={key} 

both work fine.

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

Regarding 'main(int argc, char *argv[])'

argc is the number of command line arguments and argv is array of strings representing command line arguments.

This gives you the option to react to the arguments passed to the program. If you are expecting none, you might as well use int main.

Find Item in ObservableCollection without using a loop

ObservableCollection is a list so if you don't know the element position you have to look at each element until you find the expected one.

Possible optimization If your elements are sorted use a binary search to improve performances otherwise use a Dictionary as index.

exceeds the list view threshold 5000 items in Sharepoint 2010

You can increase the List View Threshold beyond the 5,000 default, but it is highly recommended that you don't, as it has performance implications. The recommended fix is to add an index to the field or fields used in the query (usually the ID field for a list or the Title field for a library).

When there is an index, that is used to retrieve the item(s); when there is no index the whole list is opened for a scan (and therefore hits the threshold). You create the index on the List (or Library) settings page.

This article is a good overview: http://office.microsoft.com/en-us/sharepoint-foundation-help/manage-lists-and-libraries-with-many-items-HA010377496.aspx

Fastest way to flatten / un-flatten nested JSON objects

Here is some code I wrote to flatten an object I was working with. It creates a new class that takes every nested field and brings it into the first layer. You could modify it to unflatten by remembering the original placement of the keys. It also assumes the keys are unique even across nested objects. Hope it helps.

class JSONFlattener {
    ojson = {}
    flattenedjson = {}

    constructor(original_json) {
        this.ojson = original_json
        this.flattenedjson = {}
        this.flatten()
    }

    flatten() {
        Object.keys(this.ojson).forEach(function(key){
            if (this.ojson[key] == null) {

            } else if (this.ojson[key].constructor == ({}).constructor) {
                this.combine(new JSONFlattener(this.ojson[key]).returnJSON())
            } else {
                this.flattenedjson[key] = this.ojson[key]
            }
        }, this)        
    }

    combine(new_json) {
        //assumes new_json is a flat array
        Object.keys(new_json).forEach(function(key){
            if (!this.flattenedjson.hasOwnProperty(key)) {
                this.flattenedjson[key] = new_json[key]
            } else {
                console.log(key+" is a duplicate key")
            }
        }, this)
    }

    returnJSON() {
        return this.flattenedjson
    }
}

console.log(new JSONFlattener(dad_dictionary).returnJSON())

As an example, it converts

nested_json = {
    "a": {
        "b": {
            "c": {
                "d": {
                    "a": 0
                }
            }
        }
    },
    "z": {
        "b":1
    },
    "d": {
        "c": {
            "c": 2
        }
    }
}

into

{ a: 0, b: 1, c: 2 }

JPA: how do I persist a String into a database field, type MYSQL Text

Since you're using JPA, use the Lob annotation (and optionally the Column annotation). Here is what the JPA specification says about it:

9.1.19 Lob Annotation

A Lob annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.

So declare something like this:

@Lob 
@Column(name="CONTENT", length=512)
private String content;

References

  • JPA 1.0 specification:
    • Section 9.1.19 "Lob Annotation"

HTML5 Video // Completely Hide Controls

This method worked in my case.

video=getElementsByTagName('video');
function removeControls(video){
  video.removeAttribute('controls');
}
window.onload=removeControls(video);

Do you know the Maven profile for mvnrepository.com?

            <?xml version="1.0" encoding="UTF-8"?>

            <!--
            Licensed to the Apache Software Foundation (ASF) under one
            or more contributor license agreements.  See the NOTICE file
            distributed with this work for additional information
            regarding copyright ownership.  The ASF licenses this file
            to you under the Apache License, Version 2.0 (the
            "License"); you may not use this file except in compliance
            with the License.  You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
            Unless required by applicable law or agreed to in writing,
            software distributed under the License is distributed on an
            "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
            KIND, either express or implied.  See the License for the
            specific language governing permissions and limitations
            under the License.
            -->

            <!--
             | This is the configuration file for Maven. It can be specified at two levels:
             |
             |  1. User Level. This settings.xml file provides configuration for a single user,
             |                 and is normally provided in ${user.home}/.m2/settings.xml.
             |
             |                 NOTE: This location can be overridden with the CLI option:
             |
             |                 -s /path/to/user/settings.xml
             |
             |  2. Global Level. This settings.xml file provides configuration for all Maven
             |                 users on a machine (assuming they're all using the same Maven
             |                 installation). It's normally provided in
             |                 ${maven.conf}/settings.xml.
             |
             |                 NOTE: This location can be overridden with the CLI option:
             |
             |                 -gs /path/to/global/settings.xml
             |
             | The sections in this sample file are intended to give you a running start at
             | getting the most out of your Maven installation. Where appropriate, the default
             | values (values used when the setting is not specified) are provided.
             |
             |-->
            <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
              <!-- localRepository
               | The path to the local repository maven will use to store artifacts.
               |
               | Default: ${user.home}/.m2/repository
              <localRepository>/path/to/local/repo</localRepository>
              -->

              <!-- interactiveMode
               | This will determine whether maven prompts you when it needs input. If set to false,
               | maven will use a sensible default value, perhaps based on some other setting, for
               | the parameter in question.
               |
               | Default: true
              <interactiveMode>true</interactiveMode>
              -->

              <!-- offline
               | Determines whether maven should attempt to connect to the network when executing a build.
               | This will have an effect on artifact downloads, artifact deployment, and others.
               |
               | Default: false
              <offline>false</offline>
              -->

              <!-- pluginGroups
               | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
               | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
               | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
               |-->
              <pluginGroups>
                <!-- pluginGroup
                 | Specifies a further group identifier to use for plugin lookup.
                <pluginGroup>com.your.plugins</pluginGroup>
                -->
              </pluginGroups>

              <!-- proxies
               | This is a list of proxies which can be used on this machine to connect to the network.
               | Unless otherwise specified (by system property or command-line switch), the first proxy
               | specification in this list marked as active will be used.
               |-->
              <proxies>
                <!-- proxy
                 | Specification for one proxy, to be used in connecting to the network.
                 |
                <proxy>
                  <id>optional</id>
                  <active>false</active>
                  <protocol>http</protocol>
                  <username>proxyuser</username>
                  <password>proxypass</password>
                  <host>proxy.host.net</host>
                  <port>80</port>
                  <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
                </proxy>
                -->
              </proxies>

              <!-- servers
               | This is a list of authentication profiles, keyed by the server-id used within the system.
               | Authentication profiles can be used whenever maven must make a connection to a remote server.
               |-->
              <servers>
                <!-- server
                 | Specifies the authentication information to use when connecting to a particular server, identified by
                 | a unique name within the system (referred to by the 'id' attribute below).
                 |
                 | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
                 |       used together.
                 |
                <server>
                  <id>deploymentRepo</id>
                  <username>repouser</username>
                  <password>repopwd</password>
                </server>
                -->

                <!-- Another sample, using keys to authenticate.
                <server>
                  <id>siteServer</id>
                  <privateKey>/path/to/private/key</privateKey>
                  <passphrase>optional; leave empty if not used.</passphrase>
                </server>
                -->
              </servers>

              <!-- mirrors
               | This is a list of mirrors to be used in downloading artifacts from remote repositories.
               |
               | It works like this: a POM may declare a repository to use in resolving certain artifacts.
               | However, this repository may have problems with heavy traffic at times, so people have mirrored
               | it to several places.
               |
               | That repository definition will have a unique id, so we can create a mirror reference for that
               | repository, to be used as an alternate download site. The mirror site will be the preferred
               | server for that repository.
               |-->
              <mirrors>
                <!-- mirror
                 | Specifies a repository mirror site to use instead of a given repository. The repository that
                 | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
                 | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
                 |
                <mirror>
                  <id>mirrorId</id>
                  <mirrorOf>repositoryId</mirrorOf>
                  <name>Human Readable Name for this Mirror.</name>
                  <url>http://my.repository.com/repo/path</url>
                </mirror>
                 -->
              </mirrors>

              <!-- profiles
               | This is a list of profiles which can be activated in a variety of ways, and which can modify
               | the build process. Profiles provided in the settings.xml are intended to provide local machine-
               | specific paths and repository locations which allow the build to work in the local environment.
               |
               | For example, if you have an integration testing plugin - like cactus - that needs to know where
               | your Tomcat instance is installed, you can provide a variable here such that the variable is
               | dereferenced during the build process to configure the cactus plugin.
               |
               | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
               | section of this document (settings.xml) - will be discussed later. Another way essentially
               | relies on the detection of a system property, either matching a particular value for the property,
               | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
               | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
               | Finally, the list of active profiles can be specified directly from the command line.
               |
               | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
               |       repositories, plugin repositories, and free-form properties to be used as configuration
               |       variables for plugins in the POM.
               |
               |-->
              <profiles>

              <profile>
                <id>maven-https</id>
                <activation>
                    <activeByDefault>true</activeByDefault>
                </activation>
                <repositories>
                    <repository>
                        <id>central</id>
                        <url>https://repo1.maven.org/maven2</url>
                        <snapshots>
                            <enabled>false</enabled>
                        </snapshots>
                    </repository>
                </repositories>
                <pluginRepositories>
                    <pluginRepository>
                        <id>central</id>
                        <url>https://repo1.maven.org/maven2</url>
                        <snapshots>
                            <enabled>false</enabled>
                        </snapshots>
                    </pluginRepository>
                </pluginRepositories> 
            </profile>

                <!-- profile
                 | Specifies a set of introductions to the build process, to be activated using one or more of the
                 | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
                 | or the command line, profiles have to have an ID that is unique.
                 |
                 | An encouraged best practice for profile identification is to use a consistent naming convention
                 | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
                 | This will make it more intuitive to understand what the set of introduced profiles is attempting
                 | to accomplish, particularly when you only have a list of profile id's for debug.
                 |
                 | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
                <profile>
                  <id>jdk-1.4</id>
                  <activation>
                    <jdk>1.4</jdk>
                  </activation>
                  <repositories>
                    <repository>
                      <id>jdk14</id>
                      <name>Repository for JDK 1.4 builds</name>
                      <url>http://www.myhost.com/maven/jdk14</url>
                      <layout>default</layout>
                      <snapshotPolicy>always</snapshotPolicy>
                    </repository>

                  </repositories>
                </profile>
                -->

                <!--
                 | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
                 | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
                 | might hypothetically look like:
                 |
                 | ...
                 | <plugin>
                 |   <groupId>org.myco.myplugins</groupId>
                 |   <artifactId>myplugin</artifactId>
                 |
                 |   <configuration>
                 |     <tomcatLocation>${tomcatPath}</tomcatLocation>
                 |   </configuration>
                 | </plugin>
                 | ...
                 |
                 | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
                 |       anything, you could just leave off the <value/> inside the activation-property.
                 |
                <profile>
                  <id>env-dev</id>
                  <activation>
                    <property>
                      <name>target-env</name>
                      <value>dev</value>
                    </property>
                  </activation>
                  <properties>
                    <tomcatPath>/path/to/tomcat/instance</tomcatPath>
                  </properties>
                </profile>
                -->
              </profiles>

              <!-- activeProfiles
               | List of profiles that are active for all builds.
               |
              <activeProfiles>
                <activeProfile>alwaysActiveProfile</activeProfile>
                <activeProfile>anotherAlwaysActiveProfile</activeProfile>
              </activeProfiles>
              -->
            </settings>

Vertically aligning text next to a radio button

This will give dead on alignment

input[type="radio"] {
  margin-top: 1px;
  vertical-align: top;
}

How do I get the path of the assembly the code is in?

I got the same behaviour in the NUnit in the past. By default NUnit copies your assembly into the temp directory. You can change this behaviour in the NUnit settings:

enter image description here

Maybe TestDriven.NET and MbUnit GUI have the same settings.

UIImage: Resize, then Crop

Swift version:

    static func imageWithImage(image:UIImage, newSize:CGSize) ->UIImage {
    UIGraphicsBeginImageContextWithOptions(newSize, true, UIScreen.mainScreen().scale);
    image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))

    let newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    return newImage
}

Software Design vs. Software Architecture

Pretty subjective but my take:

Architecture The overall design of the system including interactions with other systems, hardware requirement, overall component design, and data flow.

Design The organization and flow of a component in the overall system. This would also include the component's API for interaction with other components.

Tkinter: How to use threads to preventing main event loop from "freezing"

I have used RxPY which has some nice threading functions to solve this in a fairly clean manner. No queues, and I have provided a function that runs on the main thread after completion of the background thread. Here is a working example:

import rx
from rx.scheduler import ThreadPoolScheduler
import time
import tkinter as tk

class UI:
   def __init__(self):
      self.root = tk.Tk()
      self.pool_scheduler = ThreadPoolScheduler(1) # thread pool with 1 worker thread
      self.button = tk.Button(text="Do Task", command=self.do_task).pack()

   def do_task(self):
      rx.empty().subscribe(
         on_completed=self.long_running_task, 
         scheduler=self.pool_scheduler
      )

   def long_running_task(self):
      # your long running task here... eg:
      time.sleep(3)
      # if you want a callback on the main thread:
      self.root.after(5, self.on_task_complete)

   def on_task_complete(self):
       pass # runs on main thread

if __name__ == "__main__":
    ui = UI()
    ui.root.mainloop()

Another way to use this construct which might be cleaner (depending on preference):

tk.Button(text="Do Task", command=self.button_clicked).pack()

...

def button_clicked(self):

   def do_task(_):
      time.sleep(3) # runs on background thread
             
   def on_task_done():
      pass # runs on main thread

   rx.just(1).subscribe(
      on_next=do_task, 
      on_completed=lambda: self.root.after(5, on_task_done), 
      scheduler=self.pool_scheduler
   )

String representation of an Enum

If you've come here looking to implement a simple "Enum" but whose values are strings instead of ints, here is the simplest solution:

    public sealed class MetricValueList
    {
        public static readonly string Brand = "A4082457-D467-E111-98DC-0026B9010912";
        public static readonly string Name = "B5B5E167-D467-E111-98DC-0026B9010912";
    }

Implementation:

var someStringVariable = MetricValueList.Brand;

How can I find last row that contains data in a specific column?

You should use the .End(xlup) but instead of using 65536 you might want to use:

sheetvar.Rows.Count

That way it works for Excel 2007 which I believe has more than 65536 rows

how to send a post request with a web browser

You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.

As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox

What's the scope of a variable initialized in an if statement?

you're executing this code from command line therefore if conditions is true and x is set. Compare:

>>> if False:
    y = 42


>>> y
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    y
NameError: name 'y' is not defined

bash: mkvirtualenv: command not found

Prerequisites to execute this command -

  1. pip (recursive acronym of Pip Installs Packages) is a package management system used to install and manage software packages written in Python. Many packages can be found in the Python Package Index (PyPI).

    sudo apt-get install python-pip

  2. Install Virtual Environment. Used to create virtual environment, to install packages and dependencies of multiple projects isolated from each other.

    sudo pip install virtualenv

  3. Install virtual environment wrapper About virtual env wrapper

    sudo pip install virtualenvwrapper

After Installing prerequisites you need to bring virtual environment wrapper into action to create virtual environment. Following are the steps -

  1. set virtual environment directory in path variable- export WORKON_HOME=(directory you need to save envs)

  2. source /usr/local/bin/virtualenvwrapper.sh -p $WORKON_HOME

As mentioned by @Mike, source `which virtualenvwrapper.sh` or which virtualenvwrapper.sh can used to locate virtualenvwrapper.sh file.

It's best to put above two lines in ~/.bashrc to avoid executing the above commands every time you open new shell. That's all you need to create environment using mkvirtualenv

Points to keep in mind -

  • Under Ubuntu, you may need install virtualenv and virtualenvwrapper as root. Simply prefix the command above with sudo.
  • Depending on the process used to install virtualenv, the path to virtualenvwrapper.sh may vary. Find the appropriate path by running $ find /usr -name virtualenvwrapper.sh. Adjust the line in your .bash_profile or .bashrc script accordingly.

Among $_REQUEST, $_GET and $_POST which one is the fastest?

GET vs. POST

1) Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

2) Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

3) $_GET is an array of variables passed to the current script via the URL parameters.

4) $_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?

Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

show dbs gives "Not Authorized to execute command" error

It was Docker running in the background in my case. If you have Docker installed, you may wanna close it and try again.

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

Correct way to use get_or_create?

The issue you are encountering is a documented feature of get_or_create.

When using keyword arguments other than "defaults" the return value of get_or_create is an instance. That's why it is showing you the parens in the return value.

you could use customer.source = Source.objects.get_or_create(name="Website")[0] to get the correct value.

Here is a link for the documentation: http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs

How to write a confusion matrix in Python?

I wrote a simple class to build a confusion matrix without the need to depend on a machine learning library.

The class can be used such as:

labels = ["cat", "dog", "velociraptor", "kraken", "pony"]
confusionMatrix = ConfusionMatrix(labels)

confusionMatrix.update("cat", "cat")
confusionMatrix.update("cat", "dog")
...
confusionMatrix.update("kraken", "velociraptor")
confusionMatrix.update("velociraptor", "velociraptor")

confusionMatrix.plot()

The class ConfusionMatrix:

import pylab
import collections
import numpy as np


class ConfusionMatrix:
    def __init__(self, labels):
        self.labels = labels
        self.confusion_dictionary = self.build_confusion_dictionary(labels)

    def update(self, predicted_label, expected_label):
        self.confusion_dictionary[expected_label][predicted_label] += 1

    def build_confusion_dictionary(self, label_set):
        expected_labels = collections.OrderedDict()

        for expected_label in label_set:
            expected_labels[expected_label] = collections.OrderedDict()

            for predicted_label in label_set:
                expected_labels[expected_label][predicted_label] = 0.0

        return expected_labels

    def convert_to_matrix(self, dictionary):
        length = len(dictionary)
        confusion_dictionary = np.zeros((length, length))

        i = 0
        for row in dictionary:
            j = 0
            for column in dictionary:
                confusion_dictionary[i][j] = dictionary[row][column]
                j += 1
            i += 1

        return confusion_dictionary

    def get_confusion_matrix(self):
        matrix = self.convert_to_matrix(self.confusion_dictionary)
        return self.normalize(matrix)

    def normalize(self, matrix):
        amin = np.amin(matrix)
        amax = np.amax(matrix)

        return [[(((y - amin) * (1 - 0)) / (amax - amin)) for y in x] for x in matrix]

    def plot(self):
        matrix = self.get_confusion_matrix()

        pylab.figure()
        pylab.imshow(matrix, interpolation='nearest', cmap=pylab.cm.jet)
        pylab.title("Confusion Matrix")

        for i, vi in enumerate(matrix):
            for j, vj in enumerate(vi):
                pylab.text(j, i+.1, "%.1f" % vj, fontsize=12)

        pylab.colorbar()

        classes = np.arange(len(self.labels))
        pylab.xticks(classes, self.labels)
        pylab.yticks(classes, self.labels)

        pylab.ylabel('Expected label')
        pylab.xlabel('Predicted label')
        pylab.show()

HTTP status code for update and delete?

{
    "VALIDATON_ERROR": {
        "code": 512,
        "message": "Validation error"
    },
    "CONTINUE": {
        "code": 100,
        "message": "Continue"
    },
    "SWITCHING_PROTOCOLS": {
        "code": 101,
        "message": "Switching Protocols"
    },
    "PROCESSING": {
        "code": 102,
        "message": "Processing"
    },
    "OK": {
        "code": 200,
        "message": "OK"
    },
    "CREATED": {
        "code": 201,
        "message": "Created"
    },
    "ACCEPTED": {
        "code": 202,
        "message": "Accepted"
    },
    "NON_AUTHORITATIVE_INFORMATION": {
        "code": 203,
        "message": "Non Authoritative Information"
    },
    "NO_CONTENT": {
        "code": 204,
        "message": "No Content"
    },
    "RESET_CONTENT": {
        "code": 205,
        "message": "Reset Content"
    },
    "PARTIAL_CONTENT": {
        "code": 206,
        "message": "Partial Content"
    },
    "MULTI_STATUS": {
        "code": 207,
        "message": "Multi-Status"
    },
    "MULTIPLE_CHOICES": {
        "code": 300,
        "message": "Multiple Choices"
    },
    "MOVED_PERMANENTLY": {
        "code": 301,
        "message": "Moved Permanently"
    },
    "MOVED_TEMPORARILY": {
        "code": 302,
        "message": "Moved Temporarily"
    },
    "SEE_OTHER": {
        "code": 303,
        "message": "See Other"
    },
    "NOT_MODIFIED": {
        "code": 304,
        "message": "Not Modified"
    },
    "USE_PROXY": {
        "code": 305,
        "message": "Use Proxy"
    },
    "TEMPORARY_REDIRECT": {
        "code": 307,
        "message": "Temporary Redirect"
    },
    "PERMANENT_REDIRECT": {
        "code": 308,
        "message": "Permanent Redirect"
    },
    "BAD_REQUEST": {
        "code": 400,
        "message": "Bad Request"
    },
    "UNAUTHORIZED": {
        "code": 401,
        "message": "Unauthorized"
    },
    "PAYMENT_REQUIRED": {
        "code": 402,
        "message": "Payment Required"
    },
    "FORBIDDEN": {
        "code": 403,
        "message": "Forbidden"
    },
    "NOT_FOUND": {
        "code": 404,
        "message": "Not Found"
    },
    "METHOD_NOT_ALLOWED": {
        "code": 405,
        "message": "Method Not Allowed"
    },
    "NOT_ACCEPTABLE": {
        "code": 406,
        "message": "Not Acceptable"
    },
    "PROXY_AUTHENTICATION_REQUIRED": {
        "code": 407,
        "message": "Proxy Authentication Required"
    },
    "REQUEST_TIMEOUT": {
        "code": 408,
        "message": "Request Timeout"
    },
    "CONFLICT": {
        "code": 409,
        "message": "Conflict"
    },
    "GONE": {
        "code": 410,
        "message": "Gone"
    },
    "LENGTH_REQUIRED": {
        "code": 411,
        "message": "Length Required"
    },
    "PRECONDITION_FAILED": {
        "code": 412,
        "message": "Precondition Failed"
    },
    "REQUEST_TOO_LONG": {
        "code": 413,
        "message": "Request Entity Too Large"
    },
    "REQUEST_URI_TOO_LONG": {
        "code": 414,
        "message": "Request-URI Too Long"
    },
    "UNSUPPORTED_MEDIA_TYPE": {
        "code": 415,
        "message": "Unsupported Media Type"
    },
    "REQUESTED_RANGE_NOT_SATISFIABLE": {
        "code": 416,
        "message": "Requested Range Not Satisfiable"
    },
    "EXPECTATION_FAILED": {
        "code": 417,
        "message": "Expectation Failed"
    },
    "IM_A_TEAPOT": {
        "code": 418,
        "message": "I'm a teapot"
    },
    "INSUFFICIENT_SPACE_ON_RESOURCE": {
        "code": 419,
        "message": "Insufficient Space on Resource"
    },
    "METHOD_FAILURE": {
        "code": 420,
        "message": "Method Failure"
    },
    "UNPROCESSABLE_ENTITY": {
        "code": 422,
        "message": "Unprocessable Entity"
    },
    "LOCKED": {
        "code": 423,
        "message": "Locked"
    },
    "FAILED_DEPENDENCY": {
        "code": 424,
        "message": "Failed Dependency"
    },
    "PRECONDITION_REQUIRED": {
        "code": 428,
        "message": "Precondition Required"
    },
    "TOO_MANY_REQUESTS": {
        "code": 429,
        "message": "Too Many Requests"
    },
    "REQUEST_HEADER_FIELDS_TOO_LARGE": {
        "code": 431,
        "message": "Request Header Fields Too"
    },
    "UNAVAILABLE_FOR_LEGAL_REASONS": {
        "code": 451,
        "message": "Unavailable For Legal Reasons"
    },
    "INTERNAL_SERVER_ERROR": {
        "code": 500,
        "message": "Internal Server Error"
    },
    "NOT_IMPLEMENTED": {
        "code": 501,
        "message": "Not Implemented"
    },
    "BAD_GATEWAY": {
        "code": 502,
        "message": "Bad Gateway"
    },
    "SERVICE_UNAVAILABLE": {
        "code": 503,
        "message": "Service Unavailable"
    },
    "GATEWAY_TIMEOUT": {
        "code": 504,
        "message": "Gateway Timeout"
    },
    "HTTP_VERSION_NOT_SUPPORTED": {
        "code": 505,
        "message": "HTTP Version Not Supported"
    },
    "INSUFFICIENT_STORAGE": {
        "code": 507,
        "message": "Insufficient Storage"
    },
    "NETWORK_AUTHENTICATION_REQUIRED": {
        "code": 511,
        "message": "Network Authentication Required"
    }
}

What is the Regular Expression For "Not Whitespace and Not a hyphen"

[^\s-]

should work and so will

[^-\s]
  • [] : The char class
  • ^ : Inside the char class ^ is the negator when it appears in the beginning.
  • \s : short for a white space
  • - : a literal hyphen. A hyphen is a meta char inside a char class but not when it appears in the beginning or at the end.

wamp server mysql user id and password

Go to http://localhost/phpmyadmin and click on the Privileges tab. There is a "Add a new user" link. alt text

How to print to console using swift playground?

You may still have trouble displaying the output in the Assistant Editor. Rather than wrapping the string in println(), simply output the string. For example:

for index in 1...5 {
    "The number is \(index)"
}

Will write (5 times) in the playground area. This will allow you to display it in the Assistant Editor (via the little circle on the far right edge).

However, if you were to println("The number is \(index)") you wouldn't be able to visualize it in the Assistant Editor.

How to convert JSONObjects to JSONArray?

Your response should be something like this to be qualified as Json Array.

{
  "songs":[
    {"2562862600": {"id":"2562862600", "pos":1}},  
    {"2562862620": {"id":"2562862620", "pos":1}},  
    {"2562862604": {"id":"2562862604", "pos":1}},  
    {"2573433638": {"id":"2573433638", "pos":1}}
  ]
}

You can parse your response as follows

String resp = ...//String output from your source
JSONObject ob = new JSONObject(resp);  
JSONArray arr = ob.getJSONArray("songs");

for(int i=0; i<arr.length(); i++){   
  JSONObject o = arr.getJSONObject(i);  
  System.out.println(o);  
}

user authentication libraries for node.js?

Session + If

I guess the reason that you haven't found many good libraries is that using a library for authentication is mostly over engineered.

What you are looking for is just a session-binder :) A session with:

if login and user == xxx and pwd == xxx 
   then store an authenticated=true into the session 
if logout destroy session

thats it.


I disagree with your conclusion that the connect-auth plugin is the way to go.

I'm using also connect but I do not use connect-auth for two reasons:

  1. IMHO breaks connect-auth the very powerful and easy to read onion-ring architecture of connect. A no-go - my opinion :). You can find a very good and short article about how connect works and the onion ring idea here.

  2. If you - as written - just want to use a basic or http login with database or file. Connect-auth is way too big. It's more for stuff like OAuth 1.0, OAuth 2.0 & Co


A very simple authentication with connect

(It's complete. Just execute it for testing but if you want to use it in production, make sure to use https) (And to be REST-Principle-Compliant you should use a POST-Request instead of a GET-Request b/c you change a state :)

var connect = require('connect');
var urlparser = require('url');

var authCheck = function (req, res, next) {
    url = req.urlp = urlparser.parse(req.url, true);

    // ####
    // Logout
    if ( url.pathname == "/logout" ) {
      req.session.destroy();
    }

    // ####
    // Is User already validated?
    if (req.session && req.session.auth == true) {
      next(); // stop here and pass to the next onion ring of connect
      return;
    }

    // ########
    // Auth - Replace this example with your Database, Auth-File or other things
    // If Database, you need a Async callback...
    if ( url.pathname == "/login" && 
         url.query.name == "max" && 
         url.query.pwd == "herewego"  ) {
      req.session.auth = true;
      next();
      return;
    }

    // ####
    // This user is not authorized. Stop talking to him.
    res.writeHead(403);
    res.end('Sorry you are not authorized.\n\nFor a login use: /login?name=max&pwd=herewego');
    return;
}

var helloWorldContent = function (req, res, next) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('authorized. Walk around :) or use /logout to leave\n\nYou are currently at '+req.urlp.pathname);
}

var server = connect.createServer(
      connect.logger({ format: ':method :url' }),
      connect.cookieParser(),
      connect.session({ secret: 'foobar' }),
      connect.bodyParser(),
      authCheck,
      helloWorldContent
);

server.listen(3000);

NOTE

I wrote this statement over a year ago and have currently no active node projects. So there are may be API-Changes in Express. Please add a comment if I should change anything.

How to prevent a click on a '#' link from jumping to top of page?

The #/ trick works, but adds a history event to the browser. So, clicking back doesn't work as the user may want/expect it to.

$('body').click('a[href="#"]', function(e) {e.preventDefault() }); is the way I went, as it works for already existing content, and any elements added to the DOM after load.

Specifically, I needed to do this in a bootstrap dropdown-menu inside of a .btn-group(Reference), so I did:

$('body').click('.dropdown-menu li a[href="#"]', function(e) {e.preventDefault() });

This way it was targeted, and didn't affect anything thing else on the page.

C pointer to array/array of pointers disambiguation

I don't know if it has an official name, but I call it the Right-Left Thingy(TM).

Start at the variable, then go right, and left, and right...and so on.

int* arr1[8];

arr1 is an array of 8 pointers to integers.

int (*arr2)[8];

arr2 is a pointer (the parenthesis block the right-left) to an array of 8 integers.

int *(arr3[8]);

arr3 is an array of 8 pointers to integers.

This should help you out with complex declarations.

git add only modified changes and ignore untracked files

You didn't say what's currently your .gitignore, but a .gitignore with the following contents in your root directory should do the trick.

.metadata
build

jQuery check if it is clicked or not

<script>
    var listh = document.getElementById( 'list-home-list' );
    var hb = document.getElementsByTagName('hb');
    $("#list-home-list").click(function(){
    $(this).style.color = '#2C2E33';
    hb.style.color = 'white';
    });
</script>

How can I access and process nested objects, arrays or JSON?

At times, accessing a nested object using a string can be desirable. The simple approach is the first level, for example

var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world

But this is often not the case with complex json. As json becomes more complex, the approaches for finding values inside of the json also become complex. A recursive approach for navigating the json is best, and how that recursion is leveraged will depend on the type of data being searched for. If there are conditional statements involved, a json search can be a good tool to use.

If the property being accessed is already known, but the path is complex, for example in this object

var obj = {
 arr: [
    { id: 1, name: "larry" },    
    { id: 2, name: "curly" },
    { id: 3, name: "moe" }
 ]
};

And you know you want to get the first result of the array in the object, perhaps you would like to use

var moe = obj["arr[0].name"];

However, that will cause an exception as there is no property of object with that name. The solution to be able to use this would be to flatten the tree aspect of the object. This can be done recursively.

function flatten(obj){
 var root = {};
 (function tree(obj, index){
   var suffix = toString.call(obj) == "[object Array]" ? "]" : "";
   for(var key in obj){
    if(!obj.hasOwnProperty(key))continue;
    root[index+key+suffix] = obj[key];
    if( toString.call(obj[key]) == "[object Array]" )tree(obj[key],index+key+suffix+"[");
    if( toString.call(obj[key]) == "[object Object]" )tree(obj[key],index+key+suffix+".");   
   }
 })(obj,"");
 return root;
}

Now, the complex object can be flattened

var obj = previous definition;
var flat = flatten(obj);
var moe = flat["arr[0].name"];//moe

Here is a jsFiddle Demo of this approach being used.

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

Add Legend to Seaborn point plot

I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date. This allows to set labels to the plots and have them automatically put into a legend with ax.legend().

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})

f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'

ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")

ax.legend()

plt.gcf().autofmt_xdate()
plt.show()

enter image description here


In case one is still interested in obtaining the legend for pointplots, here a way to go:

sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')

ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])

ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()

plt.show()

Android : Check whether the phone is dual SIM

I have a Samsung Duos device with Android 4.4.4 and the method suggested by Seetha in the accepted answer (i.e. call getDeviceIdDs) does not work for me, as the method does not exist. I was able to recover all the information I needed by calling method "getDefault(int slotID)", as shown below:

public static void samsungTwoSims(Context context) {
    TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    try{

        Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

        Class<?>[] parameter = new Class[1];
        parameter[0] = int.class;
        Method getFirstMethod = telephonyClass.getMethod("getDefault", parameter);

        Log.d(TAG, getFirstMethod.toString());

        Object[] obParameter = new Object[1];
        obParameter[0] = 0;
        TelephonyManager first = (TelephonyManager) getFirstMethod.invoke(null, obParameter);

        Log.d(TAG, "Device Id: " + first.getDeviceId() + ", device status: " + first.getSimState() + ", operator: " + first.getNetworkOperator() + "/" + first.getNetworkOperatorName());

        obParameter[0] = 1;
        TelephonyManager second = (TelephonyManager) getFirstMethod.invoke(null, obParameter);

        Log.d(TAG, "Device Id: " + second.getDeviceId() + ", device status: " + second.getSimState()+ ", operator: " + second.getNetworkOperator() + "/" + second.getNetworkOperatorName());
    } catch (Exception e) {
        e.printStackTrace();
    }   
}

Also, I rewrote the code that iteratively tests for methods to recover this information so that it uses an array of method names instead of a sequence of try/catch. For instance, to determine if we have two active SIMs we could do:

private static String[] simStatusMethodNames = {"getSimStateGemini", "getSimState"};


public static boolean hasTwoActiveSims(Context context) {
    boolean first = false, second = false;

    for (String methodName: simStatusMethodNames) {
        // try with sim 0 first
        try {
            first = getSIMStateBySlot(context, methodName, 0);
            // no exception thrown, means method exists
            second = getSIMStateBySlot(context, methodName, 1);
           return first && second;
        } catch (GeminiMethodNotFoundException e) {
            // method does not exist, nothing to do but test the next
        }
    }
    return false;
}

This way, if a new method name is suggested for some device, you can simply add it to the array and it should work.

jQuery detect if textarea is empty

This will check for empty textarea as well as will not allow only Spaces in textarea coz that looks empty too.

 var txt_msg = $("textarea").val();

 if (txt_msg.replace(/^\s+|\s+$/g, "").length == 0 || txt_msg=="") {
    return false;
  }

SQL Server Group By Month

I prefer combining DATEADD and DATEDIFF functions like this:

GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Created),0)

Together, these two functions zero-out the date component smaller than the specified datepart (i.e. MONTH in this example).

You can change the datepart bit to YEAR, WEEK, DAY, etc... which is super handy.

Your original SQL query would then look something like this (I can't test it as I don't have your data set, but it should put you on the right track).

DECLARE @start [datetime] = '2010-04-01';

SELECT
    ItemID,
    UserID,
    DATEADD(MONTH, DATEDIFF(MONTH, 0, Created),0) [Month],
    IsPaid,
    SUM(Amount)
FROM LIVE L
INNER JOIN Payments I ON I.LiveID = L.RECORD_KEY
WHERE UserID = 16178
AND PaymentDate > @start

One more thing: the Month column is typed as a DateTime which is also a nice advantage if you need to further process that data or map it .NET object for example.

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

My problem occurs when I try to open https. I don't use SSL.

It's Tomcat bug.

Today 12/02/2017 newest official version from Debian repositories is Tomcat 8.0.14

Solution is to download from official site and install newest package of Tomcat 8, 8.5, 9 or upgrade to newest version(8.5.x) from jessie-backports

Debian 8

Add to /etc/apt/sources.list

deb http://ftp.debian.org/debian jessie-backports main

Then update and install Tomcat from jessie-backports

sudo apt-get update && sudo apt-get -t jessie-backports install tomcat8

onSaveInstanceState () and onRestoreInstanceState ()

I just ran into this and was noticing that the documentation had my answer:

"This function will never be called with a null state."

https://developer.android.com/reference/android/view/View.html#onRestoreInstanceState(android.os.Parcelable)

In my case, I was wondering why the onRestoreInstanceState wasn't being called on initial instantiation. This also means that if you don't store anything, it'll not be called when you go to reconstruct your view.

how to show progress bar(circle) in an activity having a listview before loading the listview with data

You can add the ProgressBar to listview footer:

private ListView listview;
private ProgressBar progressBar;

...

progressBar = (ProgressBar) LayoutInflater.from(this).inflate(R.layout.progress_bar, null);

listview.addFooterView(progressBar);

layout/progress_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/load_progress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminate="true"
     />

when the data is loaded to the adapter view call:

        listview.removeFooterView(progressBar);

Datatable vs Dataset

It really depends on the sort of data you're bringing back. Since a DataSet is (in effect) just a collection of DataTable objects, you can return multiple distinct sets of data into a single, and therefore more manageable, object.

Performance-wise, you're more likely to get inefficiency from unoptimized queries than from the "wrong" choice of .NET construct. At least, that's been my experience.

Java synchronized block vs. Collections.synchronizedMap

Check out Google Collections' Multimap, e.g. page 28 of this presentation.

If you can't use that library for some reason, consider using ConcurrentHashMap instead of SynchronizedHashMap; it has a nifty putIfAbsent(K,V) method with which you can atomically add the element list if it's not already there. Also, consider using CopyOnWriteArrayList for the map values if your usage patterns warrant doing so.

useState set method not reflecting change immediately

useEffect has its own state/lifecycle, it will not update until you pass a function in parameters or effect destroyed.

object and array spread or rest will not work inside useEffect.

React.useEffect(() => {
    console.log("effect");
    (async () => {
        try {
            let result = await fetch("/query/countries");
            const res = await result.json();
            let result1 = await fetch("/query/projects");
            const res1 = await result1.json();
            let result11 = await fetch("/query/regions");
            const res11 = await result11.json();
            setData({
                countries: res,
                projects: res1,
                regions: res11
            });
        } catch {}
    })(data)
}, [setData])
# or use this
useEffect(() => {
    (async () => {
        try {
            await Promise.all([
                fetch("/query/countries").then((response) => response.json()),
                fetch("/query/projects").then((response) => response.json()),
                fetch("/query/regions").then((response) => response.json())
            ]).then(([country, project, region]) => {
                // console.log(country, project, region);
                setData({
                    countries: country,
                    projects: project,
                    regions: region
                });
            })
        } catch {
            console.log("data fetch error")
        }
    })()
}, [setData]);

How to use "svn export" command to get a single file from the repository?

I know the OP was asking about doing the export from the command line, but just in case this is helpful to anyone else out there...

You could just let Eclipse (plus one of the plugins discussed here) do the work for you.

Obviously, downloading Eclipse just for doing a single export is overkill, but if you are already using it for development, you can also do an svn export simply from your IDE's context menu when browsing an SVN repository.

Advantages:

  • easier for those not so familiar with using SVN at the command-line level (but you can learn about what happens at the command-line level by looking at the SVN console with a range of commands)
  • you'd already have your SVN details set up and wouldn't have to worry about authenticating, etc.
  • you don't have to worry about mistyping the URL, or remembering the order of parameters
  • you can specify in a dialog which directory you'd like to export to
  • you can specify in a dialog whether you'd like to export from TRUNK/HEAD or use a specific revision

How to insert special characters into a database?

$var = mysql_real_escape_string("data & the base");
$result = mysql_query('SELECT * FROM php_bugs WHERE php_bugs_category like  "%' .$var.'%"');

TypeScript error TS1005: ';' expected (II)

If you're getting error TS1005: 'finally' expected., it means you forgot to implement catch after try. Generally, it means the syntax you attempted to use was incorrect.

How do I trim whitespace?

(re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()

This will remove all the unwanted spaces and newline characters. Hope this help

import re
my_str = '   a     b \n c   '
formatted_str = (re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()

This will result :

' a      b \n c ' will be changed to 'a b c'

align divs to the bottom of their container

The way I solved this was using flexbox. By using flexbox to layout the contents of your container div, you can have flexbox automatically distribute free space to an item above the one you want to have "stick to the bottom".

For example, say this is your container div with some other block elements inside it, and that the blue box (third one down) is a paragraph and the purple box (last one) is the one you want to have "stick to the bottom".

enter image description here

By setting this layout up with flexbox, you can set flex-grow: 1; on just the paragraph (blue box) and, if it is the only thing with flex-grow: 1;, it will be allocated ALL of the remaining space, pushing the element(s) after it to the bottom of the container like this:

enter image description here

(apologies for the terrible, quick-and-dirty graphics)

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution

  1. Right click on installer(.exe)
  2. Select properties option.
  3. Click on checkbox to check Unblock at the bottom of Properties.

This solution work for Heroku CLI (heroku-x64) installer(.exe)

Using variables inside strings

This functionality is not built-in to C# 5 or below.
Update: C# 6 now supports string interpolation, see newer answers.

The recommended way to do this would be with String.Format:

string name = "Scott";
string output = String.Format("Hello {0}", name);

However, I wrote a small open-source library called SmartFormat that extends String.Format so that it can use named placeholders (via reflection). So, you could do:

string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".

Hope you like it!

How to efficiently calculate a running standard deviation?

n=int(raw_input("Enter no. of terms:"))

L=[]

for i in range (1,n+1):

    x=float(raw_input("Enter term:"))

    L.append(x)

sum=0

for i in range(n):

    sum=sum+L[i]

avg=sum/n

sumdev=0

for j in range(n):

    sumdev=sumdev+(L[j]-avg)**2

dev=(sumdev/n)**0.5

print "Standard deviation is", dev

Lambda function in list comprehensions

The first one creates a single lambda function and calls it ten times.

The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:

[(lambda x: x*x)(x) for x in range(10)]

Or better yet:

[x*x for x in range(10)]

Angular 2 declaring an array of objects

First, generate an Interface

Assuming you are using TypeScript & Angular CLI, you can generate one by using the following command

ng g interface car

After that set the data types of its properties

// car.interface.ts
export interface car {
  id: number;
  eco: boolean;
  wheels: number;
  name: string;
}

You can now import your interface in the class that you want.

import {car} from "app/interfaces/car.interface";

And update the collection/array of car objects by pushing items in the array.

this.car.push({
  id: 12345,
  eco: true,
  wheels: 4,
  name: 'Tesla Model S',
});

More on interfaces:

An interface is a TypeScript artifact, it is not part of ECMAScript. An interface is a way to define a contract on a function with respect to the arguments and their type. Along with functions, an interface can also be used with a Class as well to define custom types. An interface is an abstract type, it does not contain any code as a class does. It only defines the 'signature' or shape of an API. During transpilation, an interface will not generate any code, it is only used by Typescript for type checking during development. - https://angular-2-training-book.rangle.io/handout/features/interfaces.html

WebService Client Generation Error with JDK8

A very simple portable solution would be, to place the following line of code somewhere in a crucial part of your code, a part of which you are sure that it will be run (for example right in the main method):

System.setProperty("javax.xml.accessExternalDTD", "all");

This sets the needed system property programmatically, without having to do tricky maven pom.xml changes (which for some reason didn't work for me).

Tracking changes in Windows registry

There is a python-hids called sobek ( http://code.google.com/p/sobek-hids/ ) that is able to monitor some parts of the SO. It's working fine for my for monitoring file changes, and although the doc sais that it's able to monitor registry changes it does not work for me.

Good piece of software for easily deplay a python based hids.

git replacing LF with CRLF

Git has three modes of how it treats line endings:

$ git config core.autocrlf
# that command will print "true" or "false" or "input"

You can set the mode to use by adding an additional parameter of true or false to the above command line.

If core.autocrlf is set to true, that means that any time you add a file to the git repo that git thinks is a text file, it will turn all CRLF line endings to just LF before it stores it in the commit. Whenever you git checkout something, all text files automatically will have their LF line endings converted to CRLF endings. This allows development of a project across platforms that use different line-ending styles without commits being very noisy because each editor changes the line ending style as the line ending style is always consistently LF.

The side-effect of this convenient conversion, and this is what the warning you're seeing is about, is that if a text file you authored originally had LF endings instead of CRLF, it will be stored with LF as usual, but when checked out later it will have CRLF endings. For normal text files this is usually just fine. The warning is a "for your information" in this case, but in case git incorrectly assesses a binary file to be a text file, it is an important warning because git would then be corrupting your binary file.

If core.autocrlf is set to false, no line-ending conversion is ever performed, so text files are checked in as-is. This usually works ok, as long as all your developers are either on Linux or all on Windows. But in my experience I still tend to get text files with mixed line endings that end up causing problems.

My personal preference is to leave the setting turned ON, as a Windows developer.

See http://kernel.org/pub/software/scm/git/docs/git-config.html for updated info that includes the "input" value.

How to emulate a do-while loop in Python?

Python 3.8 has the answer.

It's called assignment expressions. from the documentation:

# Loop over fixed length blocks
while (block := f.read(256)) != '':
    process(block)

Use Mockito to mock some methods but not others

According to docs :

Foo mock = mock(Foo.class, CALLS_REAL_METHODS);

// this calls the real implementation of Foo.getSomething()
value = mock.getSomething();

when(mock.getSomething()).thenReturn(fakeValue);

// now fakeValue is returned
value = mock.getSomething();

Traverse a list in reverse order in Python

The other answers are good, but if you want to do as List comprehension style

collection = ['a','b','c']
[item for item in reversed( collection ) ]

How do I add python3 kernel to jupyter (IPython)

The solution is well documented in the official docs: https://ipython.readthedocs.org/en/latest/install/kernel_install.html

I tried the first approach. Since I already had ipykernel installed, simply running python3 -m ipykernel install --user solved the problem.

Good MapReduce examples

From time to time I present MR concepts to people. I find processing tasks familiar to people and then map them to the MR paradigm.

Usually I take two things:

  1. Group By / Aggregations. Here the advantage of the shuffling stage is clear. An explanation that shuffling is also distributed sort + an explanation of distributed sort algorithm also helps.

  2. Join of two tables. People working with DB are familiar with the concept and its scalability problem. Show how it can be done in MR.

With CSS, how do I make an image span the full width of the page as a background image?

If you're hoping to use background-image: url(...);, I don't think you can. However, if you want to play with layering, you can do something like this:

<img class="bg" src="..." />

And then some CSS:

.bg
{
  width: 100%;
  z-index: 0;
}

You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%; to apply to the whole page.

Here's a quick demo if you can't rely on background-size: http://jsfiddle.net/bB3Uc/

Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

How to let PHP to create subdomain automatically for each user?

You're looking to create a custom A record.

I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:

*.mywebsite.com       IN  A       127.0.0.1

127.0.0.1 would be the IP address of your webserver. The method of actually adding the record will depend on your host.


Doing it like http://mywebsite.com/user would be a lot easier to set up if it's an option.

Then you could just add a .htaccess file that looks like this:

Options +FollowSymLinks

RewriteEngine On
RewriteRule ^([aA-zZ])$  dostuff.php?username=$1

In the above, usernames are limited to the characters a-z


The rewrite rule for grabbing the subdomain would look like this:

RewriteCond %{HTTP_HOST} ^(^.*)\.mywebsite.com
RewriteRule (.*)  dostuff.php?username=%1

However, you don't really need any rewrite rules. The HTTP_HOST header is available in PHP as well, so you can get it already, like

$username = strtok($_SERVER['HTTP_HOST'], ".");

How can I copy data from one column to another in the same table?

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

VBA Excel - Insert row below with same format including borders and frames

The easiest option is to make use of the Excel copy/paste.

Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub

Show space, tab, CRLF characters in editor of Visual Studio

Edit > Advanced > View White Space. The keyboard shortcut is CTRL+R, CTRL+W. The command is called Edit.ViewWhiteSpace.

It works in all Visual Studio versions at least since Visual Studio 2010, the current one being Visual Studio 2019 (at time of writing). In Visual Studio 2013, you can also use CTRL+E, S or CTRL+E, CTRL+S.

By default, end of line markers are not visualized. This functionality is provided by the End of the Line extension.

How to make sure docker's time syncs with that of the host?

docker-compose usage:

Add /etc/localtime:/etc/localtime:ro to the volumes attribute:

version: '3'

services:
  a-service:
      image: service-name
      container_name: container-name
      volumes:
        - /etc/localtime:/etc/localtime:ro

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

In many cases, the needed 'current time' is rather $^T, which is the time at which the script started running, in whole seconds (assuming only 60 second minutes) since the UNIX epoch.

This to prevent that an early part of a script uses a different date (or daylight-saving status) than a later part of a script, for example in query-conditions and other derived values.

For that variant of 'current time', one can use a constant, also to document that it was frozen at compile time:

use constant YMD_HMS_AT_START => POSIX::strftime( "%F %T", localtime $^T );

Alternative higher resolution startup time:

0+ [ Time::HiRes::stat("/proc/$$") ]->[10]

TypeError: 'module' object is not callable

Assume that the content of YourClass.py is:

class YourClass:
    # ......

If you use:

from YourClassParentDir import YourClass  # means YourClass.py

In this way, I got TypeError: 'module' object is not callable if you then tried to use YourClass().

But, if you use:

from YourClassParentDir.YourClass import YourClass   # means Class YourClass

or use YourClass.YourClass(), it works for me.

JPA : How to convert a native query result set to POJO class collection

If you use Spring-jpa, this is a supplement to the answers and this question. Please correct this if any flaws. I have mainly used three methods to achieve "mapping result Object[] to a pojo" based on what practical need I meet:

  1. JPA built in method is enough.
  2. JPA built in method is not enough, but a customized sql with its Entity are enough.
  3. The former 2 failed, and I have to use a nativeQuery. Here are the examples. The pojo expected:

    public class Antistealingdto {
    
        private String secretKey;
    
        private Integer successRate;
    
        // GETTERs AND SETTERs
    
        public Antistealingdto(String secretKey, Integer successRate) {
            this.secretKey = secretKey;
            this.successRate = successRate;
        }
    }
    

Method 1: Change the pojo into an interface:

public interface Antistealingdto {
    String getSecretKey();
    Integer getSuccessRate();
}

And repository:

interface AntiStealingRepository extends CrudRepository<Antistealing, Long> {
    Antistealingdto findById(Long id);
}

Method 2: Repository:

@Query("select new AntistealingDTO(secretKey, successRate) from Antistealing where ....")
Antistealing whatevernamehere(conditions);

Note: parameter sequence of POJO constructor must be identical in both POJO definition and sql.

Method 3: Use @SqlResultSetMapping and @NamedNativeQuery in Entity as the example in Edwin Dalorzo's answer.

The first two methods would call many in-the-middle handlers, like customized converters. For example, AntiStealing defines a secretKey, before it is persisted, a converter is inserted to encrypt it. This would result in the first 2 methods returning a converted back secretKey which is not what I want. While the method 3 would overcome the converter, and returned secretKey would be the same as it is stored (an encrypted one).

How to determine SSL cert expiration date from a PEM encoded certificate?

If (for some reason) you want to use a GUI application in Linux, use gcr-viewer (in most distributions it is installed by the package gcr (otherwise in package gcr-viewer))

gcr-viewer file.pem
# or
gcr-viewer file.crt

check android application is in foreground or not?

Below solution works from API level 14+

Backgrounding ComponentCallbacks2 — Looking at the documentation is not 100% clear on how you would use this. However, take a closer look and you will noticed the onTrimMemory method passes in a flag. These flags are typically to do with the memory availability but the one we care about is TRIM_MEMORY_UI_HIDDEN. By checking if the UI is hidden we can potentially make an assumption that the app is now in the background. Not exactly obvious but it should work.

Foregrounding ActivityLifecycleCallbacks — We can use this to detect foreground by overriding onActivityResumed and keeping track of the current application state (Foreground/Background).

Create our interface that will be implemented by a custom Application class

interface LifecycleDelegate {
    fun onAppBackgrounded()
    fun onAppForegrounded()
}

Create a class that is going to implement the ActivityLifecycleCallbacks and ComponentCallbacks2 and override onActivityResumed and onTrimMemory methods

// Take an instance of our lifecycleHandler as a constructor parameter
class AppLifecycleHandler(private val lifecycleDelegate: LifecycleDelegate) 
: Application.ActivityLifecycleCallbacks, ComponentCallbacks2 // <-- Implement these 
  {
private var appInForeground = false

      // Override from Application.ActivityLifecycleCallbacks
    override fun onActivityResumed(p0: Activity?) {
       if (!appInForeground) {
          appInForeground = true
          lifecycleDelegate.onAppForegrounded()
       }
    }

      // Override from ComponentCallbacks2
    override fun onTrimMemory(level: Int) { 
       if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
       // lifecycleDelegate instance was passed in on the constructor
          lifecycleDelegate.onAppBackgrounded()
       }
    }
}

Now all we need to do is have our custom Application class implement our LifecycleDelegate interface and register.

class App : Application(), LifeCycleDelegate {

    override fun onCreate() {
        super.onCreate()
        val lifeCycleHandler = AppLifecycleHandler(this)
        registerLifecycleHandler(lifeCycleHandler)
    }

    override fun onAppBackgrounded() {
        Log.d("Awww", "App in background")
    }

    override fun onAppForegrounded() {
        Log.d("Yeeey", "App in foreground")
    }

    private fun registerLifecycleHandler(lifeCycleHandler: AppLifecycleHandler) {
        registerActivityLifecycleCallbacks(lifeCycleHandler)
        registerComponentCallbacks(lifeCycleHandler)
    }

}

In Manifest set the CustomApplicationClass

<application
        android:name=".App"

Invalid column count in CSV input on line 1 Error

If your DB table already exists and you do NOT want to include all the table's columns in your CSV file, then when you run PHP Admin Import, you'll need fill in the Column Names field in the Format-Specific Options for CSV - Shown here at the bottom of the following screenshot.

In summary:

  • Choose a CSV file
  • Set the Format to CSV
  • Fill in the Column Names field with the names of the columns in your CSV
  • If your CSV file has the column names listed in row 1, set "Skip this number of queries (for SQL) or lines (for other formats), starting from the first one" to 1

enter image description here

read input separated by whitespace(s) or newline...?

Use 'q' as the the optional argument to getline.

#include <iostream>
#include <sstream>

int main() {
    std::string numbers_str;
    getline( std::cin, numbers_str, 'q' );

    int number;
    for ( std::istringstream numbers_iss( numbers_str );
          numbers_iss >> number; ) {
        std::cout << number << ' ';
    }
}

http://ideone.com/I2vWl

OS detecting makefile

Update: I now consider this answer to be obsolete. I posted a new perfect solution further down.

If your makefile may be running on non-Cygwin Windows, uname may not be available. That's awkward, but this is a potential solution. You have to check for Cygwin first to rule it out, because it has WINDOWS in its PATH environment variable too.

ifneq (,$(findstring /cygdrive/,$(PATH)))
    UNAME := Cygwin
else
ifneq (,$(findstring WINDOWS,$(PATH)))
    UNAME := Windows
else
    UNAME := $(shell uname -s)
endif
endif

Comparing two strings in C?

To compare two C strings (char *), use strcmp(). The function returns 0 when the strings are equal, so you would need to use this in your code:

if (strcmp(namet2, nameIt2) != 0)

If you (wrongly) use

if (namet2 != nameIt2)

you are comparing the pointers (addresses) of both strings, which are unequal when you have two different pointers (which is always the case in your situation).

Line continue character in C#

String Constants

Just use the + operator and break the string up into human-readable lines. The compiler will pick up that the strings are constant and concatenate them at compile time. See the MSDN C# Programming Guide here.

e.g.

const string myVeryLongString = 
    "This is the opening paragraph of my long string. " +
    "Which is split over multiple lines to improve code readability, " +
    "but is in fact, just one long string.";

IL_0003: ldstr "This is the opening paragraph of my long string. Which is split over multiple lines to improve code readability, but is in fact, just one long string."

String Variables

Note that when using string interpolation to substitute values into your string, that the $ character needs to precede each line where a substitution needs to be made:

var interpolatedString = 
    "This line has no substitutions. " +
    $" This line uses {count} widgets, and " +
    $" {CountFoos()} foos were found.";

However, this has the negative performance consequence of multiple calls to string.Format and eventual concatenation of the strings (marked with ***)

IL_002E:  ldstr       "This line has no substitutions. "
IL_0033:  ldstr       " This line uses {0} widgets, and "
IL_0038:  ldloc.0     // count
IL_0039:  box         System.Int32
IL_003E:  call        System.String.Format ***
IL_0043:  ldstr       " {0} foos were found."
IL_0048:  ldloc.1     // CountFoos
IL_0049:  callvirt    System.Func<System.Int32>.Invoke
IL_004E:  box         System.Int32
IL_0053:  call        System.String.Format ***
IL_0058:  call        System.String.Concat ***

Although you could either use $@ to provide a single string and avoid the performance issues, unless the whitespace is placed inside {} (which looks odd, IMO), this has the same issue as Neil Knight's answer, as it will include any whitespace in the line breakdowns:

var interpolatedString = $@"When breaking up strings with `@` it introduces
    <- [newLine and whitespace here!] each time I break the string.
    <- [More whitespace] {CountFoos()} foos were found.";

The injected whitespace is easy to spot:

IL_002E:  ldstr       "When breaking up strings with `@` it introduces
    <- [newLine and whitespace here!] each time I break the string.
    <- [More whitespace] {0} foos were found."

An alternative is to revert to string.Format. Here, the formatting string is a single constant as per my initial answer:

const string longFormatString = 
    "This is the opening paragraph of my long string with {0} chars. " +
    "Which is split over multiple lines to improve code readability, " +
    "but is in fact, just one long string with {1} widgets.";

And then evaluated as such:

string.Format(longFormatString, longFormatString.Length, CountWidgets());

However this can still be tricky to maintain given the potential separation between the formatting string and the substitution tokens.

What is the most efficient way to concatenate N arrays?

where 'n' is some number of arrays, maybe an array of arrays . . .

var answer = _.reduce(n, function(a, b){ return a.concat(b)})