Programs & Examples On #Slug

part of a URL that makes it more human readable or SEO-friendly, but without necessarily being required by the web server.

What is a "slug" in Django?

It's a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server - in What is a "slug" in Django? the slug is 'in-django-what-is-a-slug', but the slug is not used to determine the page served (on this site at least)

How do I create a slug in Django?

You can look at the docs for the SlugField to get to know more about it in more descriptive way.

Remove all special characters from a string

Update

The solution below has a "SEO friendlier" version:

function hyphenize($string) {
    $dict = array(
        "I'm"      => "I am",
        "thier"    => "their",
        // Add your own replacements here
    );
    return strtolower(
        preg_replace(
          array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
          array( '-', '' ),
          // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
          cleanString(
              str_replace( // preg_replace can be used to support more complicated replacements
                  array_keys($dict),
                  array_values($dict),
                  urldecode($string)
              )
          )
        )
    );
}

function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.

After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru "behaved better" than viaggi-economy-per (the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).

There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.

In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict needs to be hand tailored, of course.

Previous answer

A simple approach:

// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped

$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);

// Replace sequences of spaces with hyphen
$str = preg_replace('/  */', '-', $str);

// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)

// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);

// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything

Note that you might have to first urldecode() the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.

So the finished function along with test cases:

function hyphenize($string) {
    return 
    ## strtolower(
          preg_replace(
            array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
            array('-', ''),
        ##     cleanString(
              urldecode($string)
        ##     )
        )
    ## )
    ;
}

print implode("\n", array_map(
    function($s) {
            return $s . ' becomes ' . hyphenize($s);
    },
    array(
    'Never%20gonna%20give%20you%20up',
    "I'm not the man I was",
    "'Légeresse', dit sa majesté",
    )));


Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
I'm not the man I was              becomes  im-not-the-man-I-was
'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste

To handle UTF-8 I used a cleanString implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.

The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.

PHP function to make slug (URL string)

If you have intl extension installed, you can use Transliterator::transliterate function to create a slug easily.

<?php
$string = 'Namnet på bildtävlingen';
$slug = \Transliterator::createFromRules(
    ':: Any-Latin;'
    . ':: NFD;'
    . ':: [:Nonspacing Mark:] Remove;'
    . ':: NFC;'
    . ':: [:Punctuation:] Remove;'
    . ':: Lower();'
    . '[:Separator:] > \'-\''
)
    ->transliterate( $string );
echo $slug; // namnet-pa-bildtavlingen
?>

Turn a string into a valid filename?

>>> import string
>>> safechars = bytearray(('_-.()' + string.digits + string.ascii_letters).encode())
>>> allchars = bytearray(range(0x100))
>>> deletechars = bytearray(set(allchars) - set(safechars))
>>> filename = u'#ab\xa0c.$%.txt'
>>> safe_filename = filename.encode('ascii', 'ignore').translate(None, deletechars).decode()
>>> safe_filename
'abc..txt'

It doesn't handle empty strings, special filenames ('nul', 'con', etc).

How to generate a random string in Ruby

This solution generates a string of easily readable characters for activation codes; I didn't want people confusing 8 with B, 1 with I, 0 with O, L with 1, etc.

# Generates a random string from a set of easily readable characters
def generate_activation_code(size = 6)
  charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z}
  (0...size).map{ charset.to_a[rand(charset.size)] }.join
end

How to get cell value from DataGridView in VB.Net?

To get the value of cell, use the following syntax,

datagridviewName(columnFirst, rowSecond).value

But the intellisense and MSDN documentation is wrongly saying rowFirst, colSecond approach...

Centering a button vertically in table cell, using Twitter Bootstrap

So why is td default set to vertical-align: top;? I really don't know that yet. I would not dare to touch it. Instead add this to your stylesheet. It alters the buttons in the tables.

table .btn{
  vertical-align: top;
}

Choice between vector::resize() and vector::reserve()

The two functions do vastly different things!

The resize() method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect the size(), iteration will go over all those elements, push_back will insert after them and you can directly access them using the operator[].

The reserve() method only allocates memory, but leaves it uninitialized. It only affects capacity(), but size() will be unchanged. There is no value for the objects, because nothing is added to the vector. If you then insert the elements, no reallocation will happen, because it was done in advance, but that's the only effect.

So it depends on what you want. If you want an array of 1000 default items, use resize(). If you want an array to which you expect to insert 1000 items and want to avoid a couple of allocations, use reserve().

EDIT: Blastfurnace's comment made me read the question again and realize, that in your case the correct answer is don't preallocate manually. Just keep inserting the elements at the end as you need. The vector will automatically reallocate as needed and will do it more efficiently than the manual way mentioned. The only case where reserve() makes sense is when you have reasonably precise estimate of the total size you'll need easily available in advance.

EDIT2: Ad question edit: If you have initial estimate, then reserve() that estimate. If it turns out to be not enough, just let the vector do it's thing.

Static method in a generic class?

Something like the following would get you closer

class Clazz
{
   public static <U extends Clazz> void doIt(U thing)
   {
   }
}

EDIT: Updated example with more detail

public abstract class Thingo 
{

    public static <U extends Thingo> void doIt(U p_thingo)
    {
        p_thingo.thing();
    }

    protected abstract void thing();

}

class SubThingoOne extends Thingo
{
    @Override
    protected void thing() 
    {
        System.out.println("SubThingoOne");
    }
}

class SubThingoTwo extends Thingo
{

    @Override
    protected void thing() 
    {
        System.out.println("SuThingoTwo");
    }

}

public class ThingoTest 
{

    @Test
    public void test() 
    {
        Thingo t1 = new SubThingoOne();
        Thingo t2 = new SubThingoTwo();

        Thingo.doIt(t1);
        Thingo.doIt(t2);

        // compile error -->  Thingo.doIt(new Object());
    }
}

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

How to scroll up or down the page to an anchor using jQuery?

$(function() {
    $('a#top').click(function() {
        $('html,body').animate({'scrollTop' : 0},1000);
    });
});

Test it here:

http://jsbin.com/ucati4

Could not reserve enough space for object heap to start JVM

I had the same problem when using a 32 bit version of java in a 64 bit environment. When using 64 java in a 64 OS it was ok.

List<T> OrderBy Alphabetical Order

private void SortGridGenerico< T >(
          ref List< T > lista       
    , SortDirection sort
    , string propriedadeAOrdenar)
{

    if (!string.IsNullOrEmpty(propriedadeAOrdenar)
    && lista != null
    && lista.Count > 0)
    {

        Type t = lista[0].GetType();

        if (sort == SortDirection.Ascending)
        {

            lista = lista.OrderBy(
                a => t.InvokeMember(
                    propriedadeAOrdenar
                    , System.Reflection.BindingFlags.GetProperty
                    , null
                    , a
                    , null
                )
            ).ToList();
        }
        else
        {
            lista = lista.OrderByDescending(
                a => t.InvokeMember(
                    propriedadeAOrdenar
                    , System.Reflection.BindingFlags.GetProperty
                    , null
                    , a
                    , null
                )
            ).ToList();
        }
    }
}

Calling a Fragment method from a parent Activity

If you're using a support library, you'll want to do something like this:

FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.my_fragment);
fragment.myMethod();

Fastest check if row exists in PostgreSQL

If you think about the performace ,may be you can use "PERFORM" in a function just like this:

 PERFORM 1 FROM skytf.test_2 WHERE id=i LIMIT 1;
  IF FOUND THEN
      RAISE NOTICE ' found record id=%', i;  
  ELSE
      RAISE NOTICE ' not found record id=%', i;  
 END IF;

What is the different between RESTful and RESTless

REST stands for REpresentational State Transfer and goes a little something like this:

We have a bunch of uniquely addressable 'entities' that we want made available via a web application. Those entities each have some identifier and can be accessed in various formats. REST defines a bunch of stuff about what GET, POST, etc mean for these purposes.

the basic idea with REST is that you can attach a bunch of 'renderers' to different entities so that they can be available in different formats easily using the same HTTP verbs and url formats.

For more clarification on what RESTful means and how it is used google rails. Rails is a RESTful framework so there's loads of good information available in its docs and associated blog posts. Worth a read even if you arent keen to use the framework. For example: http://www.sitepoint.com/restful-rails-part-i/

RESTless means not restful. If you have a web app that does not adhere to RESTful principles then it is not RESTful

What is a software framework?

A simple explanation is: A framework is a scaffold that you can you build applications around.

A framework generally provides some base functionality which you can use and extend to make more complex applications from, there are frameworks for all sorts of things. Microsofts MVC framework is a good example of this. It provides everything you need to get off the ground building website using the MVC pattern, it handles web requests, routes and the like. All you have to do is implement "Controllers" and provide "Views" which are two constructs defined by the MVC framework. The MVC framework then handles calling your controllers and rendering your views.

Perhaps not the best wording but I hope it helps

Lightweight workflow engine for Java

I would like to add my comments. When you choose a ready engine, such as jBPM, Activity and others (there are plenty of them), then you have to spend some time learning the system itself, this may not be an easy task. Especially, when you need only to automate small piece of code.

Then, when an issue occurs you have to deal with the vendor's support, which is not as speedy as you would imagine. Even pay for some consultancy.

And, last, a most important reason, you have to develop in the ecosystem of the engine. Although, the vendors tend to say that their system are flexible to be incorporated into any systems, this may not be case. Eventually you end up re-writing your application to match with the BPM ecosystem.

Double array initialization in Java

It is called an array initializer and can be explained in the Java specification 10.6.

This can be used to initialize any array, but it can only be used for initialization (not assignment to an existing array). One of the unique things about it is that the dimensions of the array can be determined from the initializer. Other methods of creating an array require you to manually insert the number. In many cases, this helps minimize trivial errors which occur when a programmer modifies the initializer and fails to update the dimensions.

Basically, the initializer allocates a correctly sized array, then goes from left to right evaluating each element in the list. The specification also states that if the element type is an array (such as it is for your case... we have an array of double[]), that each element may, itself be an initializer list, which is why you see one outer set of braces, and each line has inner braces.

Vector of structs initialization

After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element

But I found new to do this using default_structure_element like following...

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;

typedef struct subject {
  string name;
  int marks;
  int credits;
}subject;

int main(){
  subject default_subject;
  default_subject.name="NONE";
  default_subject.marks = 0;
  default_subject.credits = 0;

  vector <subject> sub(10,default_subject);         // default_subject to initialize

  //to check is it initialised
  for(ll i=0;i<sub.size();i++) {
    cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
  } 
}

Then I think its good to way to initialize a vector of the struct, isn't it?

How to commit and rollback transaction in sql server?

Don't use @@ERROR, use BEGIN TRY/BEGIN CATCH instead. See this article: Exception handling and nested transactions for a sample procedure:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

How to do the equivalent of pass by reference for primitives in Java

You cannot pass primitives by reference in Java. All variables of object type are actually pointers, of course, but we call them "references", and they are also always passed by value.

In a situation where you really need to pass a primitive by reference, what people will do sometimes is declare the parameter as an array of primitive type, and then pass a single-element array as the argument. So you pass a reference int[1], and in the method, you can change the contents of the array.

java collections - keyset() vs entrySet() in map

To make things simple , please note that every time you do itr2.next() the pointer moves to the next element i.e. here if you notice carefully, then the output is perfectly fine according to the logic you have written .
This may help you in understanding better:

1st Iteration of While loop(pointer is before the 1st element):
Key: if ,value: 2 {itr2.next()=if; m.get(itr2.next()=it)=>2}

2nd Iteration of While loop(pointer is before the 3rd element):
Key: is ,value: 2 {itr2.next()=is; m.get(itr2.next()=to)=>2}

3rd Iteration of While loop(pointer is before the 5th element):
Key: be ,value: 1 {itr2.next()="be"; m.get(itr2.next()="up")=>"1"}

4th Iteration of While loop(pointer is before the 7th element):
Key: me ,value: 1 {itr2.next()="me"; m.get(itr2.next()="delegate")=>"1"}

Key: if ,value: 1
Key: it ,value: 2
Key: is ,value: 2
Key: to ,value: 2
Key: be ,value: 1
Key: up ,value: 1
Key: me ,value: 1
Key: delegate ,value: 1

It prints:

Key: if ,value: 2
Key: is ,value: 2
Key: be ,value: 1
Key: me ,value: 1

How to build a DataTable from a DataGridView?

Well, you can do

DataTable data = (DataTable)(dgvMyMembers.DataSource);

and then use

data.Columns.Remove(...);

I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that DataGridView.DataSource is not necessarily of DataTable type.

How to make the main content div fill height of screen with css

Not sure exactly what your after, but I think I get it.

A header - stays at the top of the screen? A footer - stays at the bottom of the screen? Content area -> fits the space between the footer and the header?

You can do this by absolute positioning or with fixed positioning.

Here is an example with absolute positioning: http://jsfiddle.net/FMYXY/1/

Markup:

<div class="header">Header</div>
<div class="mainbody">Main Body</div>
<div class="footer">Footer</div>

CSS:

.header {outline:1px solid red; height: 40px; position:absolute; top:0px; width:100%;}
.mainbody {outline:1px solid green; min-height:200px; position:absolute; top:40px; width:100%; height:90%;}
.footer {outline:1px solid blue; height:20px; position:absolute; height:25px;bottom:0; width:100%; } 

To make it work best, I'd suggest using % instead of pixels, as you will run into problems with different screen/device sizes.

How do you uninstall a python package that was installed using distutils?

install --record + xargs rm

sudo python setup.py install --record files.txt
xargs sudo rm -rf < files.txt

removes all files and but leaves empty directories behind.

That is not ideal, it should be enough to avoid package conflicts.

And then you can finish the job manually if you want by reading files.txt, or be braver and automate empty directory removal as well.

A safe helper would be:

python-setup-uninstall() (
  sudo rm -f files.txt
  sudo python setup.py install --record files.txt && \
  xargs rm -rf < files.txt
  sudo rm -f files.txt
)

Tested in Python 2.7.6, Ubuntu 14.04.

How to call servlet through a JSP page

You can use RequestDispatcher as you usually use it in Servlet:

<%@ page contentType="text/html"%>
<%@ page import = "javax.servlet.RequestDispatcher" %>
<%
     RequestDispatcher rd = request.getRequestDispatcher("/yourServletUrl");
     request.setAttribute("msg","HI Welcome");
     rd.forward(request, response);
%>

Always be aware that don't commit any response before you use forward, as it will lead to IllegalStateException.

How do you get git to always pull from a specific branch?

Under [branch "master"], try adding the following to the repo's Git config file (.git/config):

[branch "master"]
    remote = origin
    merge = refs/heads/master

This tells Git 2 things:

  1. When you're on the master branch, the default remote is origin.
  2. When using git pull on the master branch, with no remote and branch specified, use the default remote (origin) and merge in the changes from the remote master branch.

I'm not sure why this setup would've been removed from your configuration, though. You may have to follow the suggestions that other people have posted, too, but this may work (or help at least).

If you don't want to edit the config file by hand, you can use the command-line tool instead:

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

expand/collapse table rows with JQuery

The easiest way to achieve this, without changing the HTML table-based structure, is to use a class-name on the tr elements containing a header, such as .header, to give:

<table border="0">
  <tr class="header">
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr class="header">
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>date</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
</table>

And the jQuery:

// bind a click-handler to the 'tr' elements with the 'header' class-name:
$('tr.header').click(function(){
    /* get all the subsequent 'tr' elements until the next 'tr.header',
       set the 'display' property to 'none' (if they're visible), to 'table-row'
       if they're not: */
    $(this).nextUntil('tr.header').css('display', function(i,v){
        return this.style.display === 'table-row' ? 'none' : 'table-row';
    });
});

JS Fiddle demo.

In the linked demo I've used CSS to hide the tr elements that don't have the header class-name; in practice though (despite the relative rarity of users with JavaScript disabled) I'd suggest using JavaScript to add the relevant class-names, hiding and showing as appropriate:

// hide all 'tr' elements, then filter them to find...
$('tr').hide().filter(function () {
    // only those 'tr' elements that have 'td' elements with a 'colspan' attribute:
    return $(this).find('td[colspan]').length;
    // add the 'header' class to those found 'tr' elements
}).addClass('header')
    // set the display of those elements to 'table-row':
  .css('display', 'table-row')
    // bind the click-handler (as above)
  .click(function () {
    $(this).nextUntil('tr.header').css('display', function (i, v) {
        return this.style.display === 'table-row' ? 'none' : 'table-row';
    });
});

JS Fiddle demo.

References:

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Little Edit

Try adding

return new JavascriptResult() { Script = "alert('Successfully registered');" };

in place of

return RedirectToAction("Index");

Cygwin Make bash command not found

I had the same problem and it was due to several installations of cygwin.

Check the link (the icon) that you click on to start the terminal. In case it does not point to the directory of your updated cygwin installation, you have the wrong installation of cygwin. When updating, double check the location of cygwin, and start exactly this instance of cygwin.

REST API Token-based Authentication

Let me seperate up everything and solve approach each problem in isolation:

Authentication

For authentication, baseauth has the advantage that it is a mature solution on the protocol level. This means a lot of "might crop up later" problems are already solved for you. For example, with BaseAuth, user agents know the password is a password so they don't cache it.

Auth server load

If you dispense a token to the user instead of caching the authentication on your server, you are still doing the same thing: Caching authentication information. The only difference is that you are turning the responsibility for the caching to the user. This seems like unnecessary labor for the user with no gains, so I recommend to handle this transparently on your server as you suggested.

Transmission Security

If can use an SSL connection, that's all there is to it, the connection is secure*. To prevent accidental multiple execution, you can filter multiple urls or ask users to include a random component ("nonce") in the URL.

url = username:[email protected]/api/call/nonce

If that is not possible, and the transmitted information is not secret, I recommend securing the request with a hash, as you suggested in the token approach. Since the hash provides the security, you could instruct your users to provide the hash as the baseauth password. For improved robustness, I recommend using a random string instead of the timestamp as a "nonce" to prevent replay attacks (two legit requests could be made during the same second). Instead of providing seperate "shared secret" and "api key" fields, you can simply use the api key as shared secret, and then use a salt that doesn't change to prevent rainbow table attacks. The username field seems like a good place to put the nonce too, since it is part of the auth. So now you have a clean call like this:

nonce = generate_secure_password(length: 16);
one_time_key = nonce + '-' + sha1(nonce+salt+shared_key);
url = username:[email protected]/api/call

It is true that this is a bit laborious. This is because you aren't using a protocol level solution (like SSL). So it might be a good idea to provide some kind of SDK to users so at least they don't have to go through it themselves. If you need to do it this way, I find the security level appropriate (just-right-kill).

Secure secret storage

It depends who you are trying to thwart. If you are preventing people with access to the user's phone from using your REST service in the user's name, then it would be a good idea to find some kind of keyring API on the target OS and have the SDK (or the implementor) store the key there. If that's not possible, you can at least make it a bit harder to get the secret by encrypting it, and storing the encrypted data and the encryption key in seperate places.

If you are trying to keep other software vendors from getting your API key to prevent the development of alternate clients, only the encrypt-and-store-seperately approach almost works. This is whitebox crypto, and to date, no one has come up with a truly secure solution to problems of this class. The least you can do is still issue a single key for each user so you can ban abused keys.

(*) EDIT: SSL connections should no longer be considered secure without taking additional steps to verify them.

How to make shadow on border-bottom?

New method for an old question

enter image description here

It seems like in the answers provided the issue was always how the box border would either be visible on the left and right of the object or you'd have to inset it so far that it didn't shadow the whole length of the container properly.

This example uses the :after pseudo element along with a linear gradient with transparency in order to put a drop shadow on a container that extends exactly to the sides of the element you wish to shadow.

Worth noting with this solution is that if you use padding on the element that you wish to drop shadow, it won't display correctly. This is because the after pseudo element appends it's content directly after the elements inner content. So if you have padding, the shadow will appear inside the box. This can be overcome by eliminating padding on outer container (where the shadow applies) and using an inner container where you apply needed padding.

Example with padding and background color on the shadowed div:

enter image description here

If you want to change the depth of the shadow, simply increase the height style in the after pseudo element. You can also obviously darken, lighten, or change colors in the linear gradient styles.

_x000D_
_x000D_
body {_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
.bottom-shadow {_x000D_
  width: 80%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
.bottom-shadow:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  height: 8px;_x000D_
  background: transparent;_x000D_
  background: -moz-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%); /* FF3.6-15 */_x000D_
  background: -webkit-linear-gradient(top, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* Chrome10-25,Safari5.1-6 */_x000D_
  background: linear-gradient(to bottom, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(   startColorstr='#a6000000', endColorstr='#00000000',GradientType=0 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.bottom-shadow div {_x000D_
  padding: 18px;_x000D_
  background: #fff;_x000D_
}
_x000D_
<div class="bottom-shadow">_x000D_
  <div>_x000D_
    Shadows, FTW!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to download a file from a website in C#

Use WebClient.DownloadFile:

using (WebClient client = new WebClient())
{
    client.DownloadFile("http://csharpindepth.com/Reviews.aspx", 
                        @"c:\Users\Jon\Test\foo.txt");
}

read.csv warning 'EOF within quoted string' prevents complete reading of file

You need to disable quoting.

cit <- read.csv("citations.CSV", quote = "", 
                 row.names = NULL, 
                 stringsAsFactors = FALSE)

str(cit)
## 'data.frame':    112543 obs. of  13 variables:
##  $ row.names    : chr  "10.2307/675394" "10.2307/30007362" "10.2307/4254931" "10.2307/20537934" ...
##  $ id           : chr  "10.2307/675394\t" "10.2307/30007362\t" "10.2307/4254931\t" "10.2307/20537934\t" ...
##  $ doi          : chr  "Archaeological Inference and Inductive Confirmation\t" "Sound and Sense in Cath Almaine\t" "Oak Galls Preserved by the Eruption of Mount Vesuvius in A.D. 79_ and Their Probable Use\t" "The Arts Four Thousand Years Ago\t" ...
##  $ title        : chr  "Bruce D. Smith\t" "Tomás Ó Cathasaigh\t" "Hiram G. Larew\t" "\t" ...
##  $ author       : chr  "American Anthropologist\t" "Ériu\t" "Economic Botany\t" "The Illustrated Magazine of Art\t" ...
##  $ journaltitle : chr  "79\t" "54\t" "41\t" "1\t" ...
##  $ volume       : chr  "3\t" "\t" "1\t" "3\t" ...
##  $ issue        : chr  "1977-09-01T00:00:00Z\t" "2004-01-01T00:00:00Z\t" "1987-01-01T00:00:00Z\t" "1853-01-01T00:00:00Z\t" ...
##  $ pubdate      : chr  "pp. 598-617\t" "pp. 41-47\t" "pp. 33-40\t" "pp. 171-172\t" ...
##  $ pagerange    : chr  "American Anthropological Association\tWiley\t" "Royal Irish Academy\t" "New York Botanical Garden Press\tSpringer\t" "\t" ...
##  $ publisher    : chr  "fla\t" "fla\t" "fla\t" "fla\t" ...
##  $ type         : logi  NA NA NA NA NA NA ...
##  $ reviewed.work: logi  NA NA NA NA NA NA ...

I think is because of this kind of lines (check "Thorn" and "Minus")

 readLines("citations.CSV")[82]
[1] "10.2307/3642839,10.2307/3642839\t,\"Thorn\" and \"Minus\" in Hieroglyphic Luvian Orthography\t,H. Craig Melchert\t,Anatolian Studies\t,38\t,\t,1988-01-01T00:00:00Z\t,pp. 29-42\t,British Institute at Ankara\t,fla\t,\t,"

How to import XML file into MySQL database table using XML_LOAD(); function

you can specify fields like this:

LOAD XML LOCAL INFILE '/pathtofile/file.xml' 
INTO TABLE my_tablename(personal_number, firstname, ...); 

Convert timestamp to readable date/time PHP

You can try this:

   $mytimestamp = 1465298940;

   echo gmdate("m-d-Y", $mytimestamp);

Output :

06-07-2016

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

I created a more comprehensive and cleaner version that some people might find useful for remembering which name corresponds to which value. I used Chrome Dev Tool's color code and labels are organized symmetrically to pick up analogies faster:

enter image description here

  • Note 1: clientLeft also includes the width of the vertical scroll bar if the direction of the text is set to right-to-left (since the bar is displayed to the left in that case)

  • Note 2: the outermost line represents the closest positioned parent (an element whose position property is set to a value different than static or initial). Thus, if the direct container isn’t a positioned element, then the line doesn’t represent the first container in the hierarchy but another element higher in the hierarchy. If no positioned parent is found, the browser will take the html or body element as reference


Hope somebody finds it useful, just my 2 cents ;)

How to wrap text of HTML button with fixed width?

If we have some inner divisions inside <button> tag like this-

<button class="top-container">
    <div class="classA">
       <div class="classB">
           puts " some text to get print." 
       </div>
     </div>
     <div class="class1">
       <div class="class2">
           puts " some text to get print." 
       </div>
     </div>
</button>

Sometime Text of class A get overlap on class1 data because these both are in a single button tag. I try to break the tex using-

 word-wrap: break-word;         /* All browsers since IE 5.5+ */
 overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */ 

But this won't worked then I try this-

white-space: normal;

after removing above css properties and got my task done.

Hope will work for all !!!

How do I connect to a SQL Server 2008 database using JDBC?

You can try configure SQL server:

  1. Step 1: Open SQL server 20xx Configuration Manager
  2. Step 2: Click Protocols for SQL.. in SQL server configuration. Then, right click TCP/IP, choose Properties
  3. Step 3: Click tab IP Address, Edit All TCP. Port is 1433

NOTE: ALL TCP port is 1433 Finally, restart the server.

Android Push Notifications: Icon not displaying in notification, white square shown instead

If you are using Google Cloud Messaging, then this issue will not be solved by simply changing your icon. For example, this will not work:

 Notification notification  = new Notification.Builder(this)
                .setContentTitle(title)
                .setContentText(text)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentIntent(pIntent)
                .setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE)
                .setAutoCancel(true)
                .build();

Even if ic_notification is transparant and white. It must be also defined in the Manifest meta data, like so:

  <meta-data android:name="com.google.firebase.messaging.default_notification_icon"

            android:resource="@drawable/ic_notification" />

Meta-data goes under the application tag, for reference.

Get input value from TextField in iOS alert in Swift

In Swift5 ans Xcode 10

Add two textfields with Save and Cancel actions and read TextFields text data

func alertWithTF() {
    //Step : 1
    let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle: UIAlertController.Style.alert )
    //Step : 2
    let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
        let textField = alert.textFields![0] as UITextField
        let textField2 = alert.textFields![1] as UITextField
        if textField.text != "" {
            //Read TextFields text data
            print(textField.text!)
            print("TF 1 : \(textField.text!)")
        } else {
            print("TF 1 is Empty...")
        }

        if textField2.text != "" {
            print(textField2.text!)
            print("TF 2 : \(textField2.text!)")
        } else {
            print("TF 2 is Empty...")
        }
    }

    //Step : 3
    //For first TF
    alert.addTextField { (textField) in
        textField.placeholder = "Enter your first name"
        textField.textColor = .red
    }
    //For second TF
    alert.addTextField { (textField) in
        textField.placeholder = "Enter your last name"
        textField.textColor = .blue
    }

    //Step : 4
    alert.addAction(save)
    //Cancel action
    let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in }
    alert.addAction(cancel)
    //OR single line action
    //alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })

    self.present(alert, animated:true, completion: nil)

}

For more explanation https://medium.com/@chan.henryk/alert-controller-with-text-field-in-swift-3-bda7ac06026c

Bootstrap 3 and Youtube in Modal

Try this For Bootstrap 4

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container-fluid">
<h2>Embedding YouTube Videos</h2>
<p>Embedding YouTube videos in modals requires additional JavaScript/jQuery:</p>

<!-- Buttons -->
<div class="btn-group">
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/lQAUq_zs-XU">Launch Video 1</button>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/pvODsb_-mls">Launch Video 2</button>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/4m3dymGEN5E">Launch Video 3</button>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/uyw0VZsO3I0">Launch Video 4</button>
</div>

<!-- Modal -->
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-dark border-dark">
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body bg-dark p-0">
                <div class="embed-responsive embed-responsive-16by9">
                  <iframe class="embed-responsive-item" allowfullscreen></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

</div>

<script>
$(document).ready(function() {
    // Set iframe attributes when the show instance method is called
    $("#videoModal").on("show.bs.modal", function(event) {
        let button = $(event.relatedTarget); // Button that triggered the modal
        let url = button.data("video");      // Extract url from data-video attribute
        $(this).find("iframe").attr({
            src : url,
            allow : "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
        });
    });

    // Remove iframe attributes when the modal has finished being hidden from the user
    $("#videoModal").on("hidden.bs.modal", function() {
        $("#videoModal iframe").removeAttr("src allow");
    });
});
</script>

</body>
</html>

visit (link broken): https://parrot-tutorial.com/run_code.php?snippet=bs4_modal_youtube

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

At least in Firefox (v3.5), cache seems to be disabled rather than simply cleared. If there are multiple instances of the same image on a page, it will be transferred multiple times. That is also the case for img tags that are added subsequently via Ajax/JavaScript.

So in case you're wondering why the browser keeps downloading the same little icon a few hundred times on your auto-refresh Ajax site, it's because you initially loaded the page using CTRL-F5.

Google Geocoding API - REQUEST_DENIED

Google is returning a very useful error message, which helps to correct the issue!

Dim Request         As New XMLHTTP30
Dim Results         As New DOMDocument30
Dim StatusNode      As IXMLDOMNode
Request.Open "GET", "https://maps.googleapis.com/maps/api/geocode/xml?" _
  & "&address=xxx", False
Request.Send
Results.LoadXML Request.responseText
Set StatusNode = Results.SelectSingleNode("//status")
Select Case UCase(StatusNode.Text)
    Case "REQUEST_DENIED"
          Debug.Print StatusNode.NextSibling.nodeTypedValue
    ... 

Error Message Examples

Message 1: Requests to this API must be over SSL. Load the API with "https://" instead of "http://".

Message 2: Server denied the request: You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please ...

node.js remove file

2019 and Node 10+ is here. Below the version using sweet async/await way.

Now no need to wrap fs.unlink into Promises nor to use additional packages (like fs-extra) anymore.

Just use native fs Promises API.

const fs = require('fs').promises;

(async () => {
  try {
    await fs.unlink('~/any/file');
  } catch (e) {
    // file doesn't exist, no permissions, etc..
    // full list of possible errors is here 
    // http://man7.org/linux/man-pages/man2/unlink.2.html#ERRORS
    console.log(e);
  }
})();

Here is fsPromises.unlink spec from Node docs.

Also please note that fs.promises API marked as experimental in Node 10.x.x (but works totally fine, though), and no longer experimental since 11.14.0.

Android device does not show up in adb list

In Android 8 Oreo:

  1. go into Settings / Developer Options / Select USB Configuration;
  2. Select PTP (Picture Transfer Protocol).

Select Top and Last rows in a table (SQL server)

To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.

SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC

If you care for it to be in the same order as before you can use a common table expression for that:

;WITH CTE AS (
    SELECT TOP 1000 *
    FROM [SomeTable]
    ORDER BY MySortColumn DESC
)

SELECT * 
FROM CTE
ORDER BY MySortColumn

Get pixel color from canvas, on mousemove

Quick Answer

context.getImageData(x, y, 1, 1).data; returns an rgba array. e.g. [50, 50, 50, 255]


Here's a version of @lwburk's rgbToHex function that takes the rgba array as an argument.

function rgbToHex(rgb){
  return '#' + ((rgb[0] << 16) | (rgb[1] << 8) | rgb[2]).toString(16);
};

How are environment variables used in Jenkins with Windows Batch Command?

I should this On Windows, environment variable expansion is %BUILD_NUMBER%

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

If you are using the emulator, you may try the following. The below worked for me. Go to Tools --> AVD Manager --> (Pick Your emulator) --> Wipe Data. The error went away.

Check if a key is down?

In addition to using keyup and keydown listeners to track when is key goes down and back up, there are actually some properties that tell you if certain keys are down.

window.onmousemove = function (e) {
  if (!e) e = window.event;
  if (e.shiftKey) {/*shift is down*/}
  if (e.altKey) {/*alt is down*/}
  if (e.ctrlKey) {/*ctrl is down*/}
  if (e.metaKey) {/*cmd is down*/}
}

This are available on all browser generated event objects, such as those from keydown, keyup, and keypress, so you don't have to use mousemove.

I tried generating my own event objects with document.createEvent('KeyboardEvent') and document.createEvent('KeyboardEvent') and looking for e.shiftKey and such, but I had no luck.

I'm using Chrome 17 on Mac

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

MYSQL import data from csv using LOAD DATA INFILE

You can use LOAD DATA INFILE command to import csv file into table.

Check this link MySQL - LOAD DATA INFILE.

LOAD DATA LOCAL INFILE 'abc.csv' INTO TABLE abc
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(col1, col2, col3, col4, col5...);

For MySQL 8.0 users:

Using the LOCAL keyword hold security risks and as of MySQL 8.0 the LOCAL capability is set to False by default. You might see the error:

ERROR 1148: The used command is not allowed with this MySQL version

You can overwrite it by following the instructions in the docs. Beware that such overwrite does not solve the security issue but rather just an acknowledge that you are aware and willing to take the risk.

Vagrant error : Failed to mount folders in Linux guest

I experienced the same issue with Centos 7, I assume due to an outdated kernel in combination with an updated version of VirtualBox. Based on Blizz's update, this is what worked for me (vagrant-vbguest plugin already installed):

vagrant ssh
sudo yum -y install kernel-devel
sudo yum -y update
exit
vagrant reload --provision

How to set the max size of upload file

You need to set the multipart.maxFileSize and multipart.maxRequestSize parameters to higher values than the default. This can be done in your spring boot configuration yml files. For example, adding the following to application.yml will allow users to upload 10Mb files:

multipart:
    maxFileSize: 10Mb
    maxRequestSize: 10Mb

If the user needs to be able to upload multiple files in a single request and they may total more than 10Mb, then you will need to configure multipart.maxRequestSize to a higher value:

multipart:
    maxFileSize: 10Mb
    maxRequestSize: 100Mb

Source: https://spring.io/guides/gs/uploading-files/

Reinitialize Slick js after successful ajax call

The best way would be to use the unslick setting or function(depending on your version of slick) as stated in the other answers but that did not work for me. I'm getting some errors from slick that seem to be related to this.

What did work for now, however, is removing the slick-initialized and slick-slider classes from the container before reinitializing slick, like so:

function slickCarousel() {
    $('.skills_section').removeClass("slick-initialized slick-slider");
    $('.skills_section').slick({
        infinite: true,
        slidesToShow: 3,
        slidesToScroll: 1
    });
}

Removing the classes doesn't seem to initiate the destroy event(not tested but makes sense) but does cause the later slick() call to behave properly so as long as you don't have any triggers on destroy, you should be good.

Why use the 'ref' keyword when passing an object?

Pass a ref if you want to change what the object is:

TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);

void DoSomething(ref TestRef t)
{
  t = new TestRef();
  t.Something = "Not just a changed t, but a completely different TestRef object";
}

After calling DoSomething, t does not refer to the original new TestRef, but refers to a completely different object.

This may be useful too if you want to change the value of an immutable object, e.g. a string. You cannot change the value of a string once it has been created. But by using a ref, you could create a function that changes the string for another one that has a different value.

It is not a good idea to use ref unless it is needed. Using ref gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.

Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the ref keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. int), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:

int x = 1;
Change(ref x);
Debug.Assert(x == 5);
WillNotChange(x);
Debug.Assert(x == 5); // Note: x doesn't become 10

void Change(ref int x)
{
  x = 5;
}

void WillNotChange(int x)
{
  x = 10;
}

How to add an item to an ArrayList in Kotlin?

If you want to specifically use java ArrayList then you can do something like this:

fun initList(){
    val list: ArrayList<String> = ArrayList()
    list.add("text")
    println(list)
}

Otherwise @guenhter answer is the one you are looking for.

How to remove last n characters from a string in Bash?

First, it's usually better to be explicit about your intent. So if you know the string ends in .rtf, and you want to remove that .rtf, you can just use var2=${var%.rtf}. One potentially-useful aspect of this approach is that if the string doesn't end in .rtf, it is not changed at all; var2 will contain an unmodified copy of var.

If you want to remove a filename suffix but don't know or care exactly what it is, you can use var2=${var%.*} to remove everything starting with the last .. Or, if you only want to keep everything up to but not including the first ., you can use var2=${var%%.*}. Those options have the same result if there's only one ., but if there might be more than one, you get to pick which end of the string to work from. On the other hand, if there's no . in the string at all, var2 will again be an unchanged copy of var.

If you really want to always remove a specific number of characters, here are some options.

You tagged this bash specifically, so we'll start with bash builtins. The one which has worked the longest is the same suffix-removal syntax I used above: to remove four characters, use var2=${var%????}. Or to remove four characters only if the first one is a dot, use var2=${var%.???}, which is like var2=${var%.*} but only removes the suffix if the part after the dot is exactly three characters. As you can see, to count characters this way, you need one question mark per unknown character removed, so this approach gets unwieldy for larger substring lengths.

An option in newer shell versions is substring extraction: var2=${var:0:${#var}-4}. Here you can put any number in place of the 4 to remove a different number of characters. The ${#var} is replaced by the length of the string, so this is actually asking to extract and keep (length - 4) characters starting with the first one (at index 0). With this approach, you lose the option to make the change only if the string matches a pattern; no matter what the actual value of the string is, the copy will include all but its last four characters.

Bash lets you leave the start index out; it defaults to 0, so you can shorten that to just var2=${var::${#var}-4}. In fact, newer versions of bash (specifically 4+, which means the one that ships with MacOS won't work) recognize negative lengths as end indexes counting back from the end of the string, so you can get rid of the string-length expression, too: var2=${var::-4}.

If you're not actually using bash but some other POSIX-type shell, the pattern-based suffix removal with % will still work – even in plain old dash, where the index-based substring extraction won't. Ksh and zsh do both support substring extraction, but require the explicit 0 start index; zsh also supports the negative end index, while ksh requires the length expression. Note that zsh, which indexes arrays starting at 1, nonetheless indexes strings starting at 0 if you use this bash-compatible syntax; but you can also treat parameters as arrays of characters, in which case it uses a 1-based count and expects a start and inclusive end position in brackets: var2=$var[1,-5].

Instead of using built-in shell parameter expansion, you can of course run some utility program to modify the string and capture its output with command substitution. There are several commands that will work; one is var2=$(sed 's/.\{4\}$//' <<<"$var").

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

It is ES-6 feature. It means you extract all the properties of props in div.{... }

operator is used to extract properties of an object.

Django - Did you forget to register or load this tag?

The app that contains the custom tags must be in INSTALLED_APPS. So Are you sure that your directory is in INSTALLED_APPS ?

From the documentation:

The app that contains the custom tags must be in INSTALLED_APPS in order for the {% load %} tag to work. This is a security feature: It allows you to host Python code for many template libraries on a single host machine without enabling access to all of them for every Django installation.

Compare string with all values in list

If you only want to know if any item of d is contained in paid[j], as you literally say:

if any(x in paid[j] for x in d): ...

If you also want to know which items of d are contained in paid[j]:

contained = [x for x in d if x in paid[j]]

contained will be an empty list if no items of d are contained in paid[j].

There are other solutions yet if what you want is yet another alternative, e.g., get the first item of d contained in paid[j] (and None if no item is so contained):

firstone = next((x for x in d if x in paid[j]), None)

BTW, since in a comment you mention sentences and words, maybe you don't necessarily want a string check (which is what all of my examples are doing), because they can't consider word boundaries -- e.g., each example will say that 'cat' is in 'obfuscate' (because, 'obfuscate' contains 'cat' as a substring). To allow checks on word boundaries, rather than simple substring checks, you might productively use regular expressions... but I suggest you open a separate question on that, if that's what you require -- all of the code snippets in this answer, depending on your exact requirements, will work equally well if you change the predicate x in paid[j] into some more sophisticated predicate such as somere.search(paid[j]) for an appropriate RE object somere. (Python 2.6 or better -- slight differences in 2.5 and earlier).

If your intention is something else again, such as getting one or all of the indices in d of the items satisfying your constrain, there are easy solutions for those different problems, too... but, if what you actually require is so far away from what you said, I'd better stop guessing and hope you clarify;-).

Linq select objects in list where exists IN (A,B,C)

NB: this is LINQ to objects, I am not 100% sure if it work in LINQ to entities, and have no time to check it right now. In fact it isn't too difficult to translate it to x in [A, B, C] but you have to check for yourself.

So, instead of Contains as a replacement of the ???? in your code you can use Any which is more LINQ-uish:

// Filter the orders based on the order status
var filteredOrders = from order in orders.Order
                     where new[] { "A", "B", "C" }.Any(s => s == order.StatusCode)
                     select order;

It's the opposite to what you know from SQL this is why it is not so obvious.

Of course, if you prefer fluent syntax here it is:

var filteredOrders = orders.Order.Where(order => new[] {"A", "B", "C"}.Any(s => s == order.StatusCode));

Here we again see one of the LINQ surprises (like Joda-speech which puts select at the end). However it is quite logical in this sense that it checks if at least one of the items (that is any) in a list (set, collection) matches a single value.

Clear screen in shell

Command+K works fine in OSX to clear screen.

Shift+Command+K to clear only the scrollback buffer.

How to change identity column values programmatically?

This can be done using a temporary table.

The idea

  • disable constraints (in case your id is referenced by a foreign key)
  • create a temp table with the new id
  • delete the table content
  • copy back data from the copied table to your original table
  • enable previsously disabled constraints

SQL Queries

Let's say your test table have two additional columns (column2 and column3) and that there are 2 tables having foreign keys referencing test called foreign_table1 and foreign_table2 (because real life issues are never simple).

alter table test nocheck constraint all;
alter table foreign_table1 nocheck constraint all;
alter table foreign_table2 nocheck constraint all;
set identity_insert test on;

select id + 1 as id, column2, column3 into test_copy from test v;
delete from test;
insert into test(id, column2, column3)
select id, column2, column3 from test_copy

alter table test check constraint all;
alter table foreign_table1 check constraint all;
alter table foreign_table2 check constraint all;
set identity_insert test off;
drop table test_copy;

That's it.

Where can I find jenkins restful api reference?

Additional Solution: use Restul api wrapper libraries written in Java / python / Ruby - An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.

For documentation and links: Remote Access API

Push commits to another branch

I got a bad result with git push origin branch1:branch2 command:

In my case, branch2 is deleted and branch1 has been updated with some new changes.

Hence, if you want only the changes push on the branch2 from the branch1, try procedures below:

  • On branch1: git add .
  • On branch1: git commit -m 'comments'
  • On branch1: git push origin branch1

  • On branch2: git pull origin branch1

  • On branch1: revert to the previous commit.

Change value of input and submit form in JavaScript

You can use the onchange event:

<form name="myform" id="myform" action="action.php">
    <input type="hidden" name="myinput" value="0" onchange="this.form.submit()"/>
    <input type="text" name="message" value="" />
    <input type="submit" name="submit" onclick="DoSubmit()" />
</form>

Remove spacing between table cells and rows

Put display:block on the css for the cell, and valign="top" that should do the trick

How to find longest string in the table column data

You can:

SELECT CR 
FROM table1 
WHERE len(CR) = (SELECT max(len(CR)) FROM table1)

Having just recieved an upvote more than a year after posting this, I'd like to add some information.

  • This query gives all values with the maximum length. With a TOP 1 query you get only one of these, which is usually not desired.
  • This query must probably read the table twice: a full table scan to get the maximum length and another full table scan to get all values of that length. These operations, however, are very simple operations and hence rather fast. With a TOP 1 query a DBMS reads all records from the table and then sorts them. So the table is read only once, but a sort operation on a whole table is quite some task and can be very slow on large tables.
  • One would usually add DISTINCT to my query (SELECT DISTINCT CR FROM ...), so as to get every value just once. That would be a sort operation, but only on the few records already found. Again, no big deal.
  • If the string lengths have to be dealt with quite often, one might think of creating a computed column (calculated field) for it. This is available as of Ms Access 2010. But reading up on this shows that you cannot index calculated fields in MS Access. As long as this holds true, there is hardly any benefit from them. Applying LEN on the strings is usually not what makes such queries slow.

How to make a class JSON serializable

There are many approaches to this problem. 'ObjDict' (pip install objdict) is another. There is an emphasis on providing javascript like objects which can also act like dictionaries to best handle data loaded from JSON, but there are other features which can be useful as well. This provides another alternative solution to the original problem.

Enabling SSL with XAMPP

Found the answer. In the file xampp\apache\conf\extra\httpd-ssl.conf, under the comment SSL Virtual Host Context pages on port 443 meaning https is looked up under different document root.

Simply change the document root to the same one and problem is fixed.

Emulator error: This AVD's configuration is missing a kernel file

I tried what ChrLipp suggested, but that wasn't the problem, as the image was already installed. What I did was run:

android avd

to start the emulator manually. Then I stopped the emulator, and form that point on the

cca emulate android

app started working, without the "missing a kernel file" error.

How to test if a double is zero?

Yes, it's a valid test although there's an implicit conversion from int to double. For clarity/simplicity you should use (foo.x == 0.0) to test. That will hinder NAN errors/division by zero, but the double value can in some cases be very very very close to 0, but not exactly zero, and then the test will fail (I'm talking about in general now, not your code). Division by that will give huge numbers.

If this has anything to do with money, do not use float or double, instead use BigDecimal.

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

Try:

SELECT convert(datetime, '23/07/2009', 103)

this is British/French standard.

PHP find difference between two datetimes

I collected many topics to make universal function with many outputs (years, months, days, hours, minutes, seconds) with string or parse to int and direction +- if you need to know what side is direction of the difference.

Use example:



    $date1='2016-05-27 02:00:00';
    $format='Y-m-d H:i:s';

    echo timeDifference($date1, $format, '2017-08-30 00:01:59', $format); 
    #1 years 3 months 2 days 22 hours 1 minutes 59 seconds (string)

    echo timeDifference($date1, $format, '2017-08-30 00:01:59', $format,false, '%a days %h hours');
    #459 days 22 hours (string)

    echo timeDifference('2016-05-27 00:00:00', $format, '2017-08-30 00:01:59', $format,true, '%d days -> %H:%I:%S', true);
    #-3 days -> 00:01:59 (string)

    echo timeDifference($date1, $format, '2016-05-27 00:05:51', $format, false, 'seconds');
    #9 (string)

    echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, false, 'hours');
    #5 (string)

    echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, true, 'hours');
    #-5 (string)

    echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, true, 'hours',true);
    #-5 (int)

Function



    function timeDifference($date1_pm_checked, $date1_format,$date2, $date2_format, $plus_minus=false, $return='all', $parseInt=false)
    {
        $strtotime1=strtotime($date1_pm_checked);
        $strtotime2=strtotime($date2);
        $date1 = new DateTime(date($date1_format, $strtotime1));
        $date2 = new DateTime(date($date2_format, $strtotime2));
        $interval=$date1->diff($date2);

        $plus_minus=(empty($plus_minus)) ? '' : ( ($strtotime1 > $strtotime2) ? '+' : '-'); # +/-/no_sign before value 

        switch($return)
        {
            case 'y';
            case 'year';
            case 'years';
                $elapsed = $interval->format($plus_minus.'%y');
                break;

            case 'm';
            case 'month';
            case 'months';
                $elapsed = $interval->format($plus_minus.'%m');
                break;

            case 'a';
            case 'day';
            case 'days';
                $elapsed = $interval->format($plus_minus.'%a');
                break;

            case 'd';
                $elapsed = $interval->format($plus_minus.'%d');
                break;

            case 'h';       
            case 'hour';        
            case 'hours';       
                $elapsed = $interval->format($plus_minus.'%h');
                break;

            case 'i';
            case 'minute';
            case 'minutes';
                $elapsed = $interval->format($plus_minus.'%i');
                break;

            case 's';
            case 'second';
            case 'seconds';
                $elapsed = $interval->format($plus_minus.'%s');
                break;

            case 'all':
                $parseInt=false;
                $elapsed = $plus_minus.$interval->format('%y years %m months %d days %h hours %i minutes %s seconds');
                break;

            default:
                $parseInt=false;
                $elapsed = $plus_minus.$interval->format($return);
        }

        if($parseInt)
            return (int) $elapsed;
        else
            return $elapsed;

    }

Run text file as commands in Bash

Execute

. example.txt

That does exactly what you ask for, without setting an executable flag on the file or running an extra bash instance.

For a detailed explanation see e.g. https://unix.stackexchange.com/questions/43882/what-is-the-difference-between-sourcing-or-source-and-executing-a-file-i

How can I define an array of objects?

You can also try

    interface IData{
        id: number;
        name:string;
    }

    let userTestStatus:Record<string,IData> = {
        "0": { "id": 0, "name": "Available" },
        "1": { "id": 1, "name": "Ready" },
        "2": { "id": 2, "name": "Started" }
    };

To check how record works: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

Here in our case Record is used to declare an object whose key will be a string and whose value will be of type IData so now it will provide us intellisense when we will try to access its property and will throw type error in case we will try something like userTestStatus[0].nameee

Why can't Python find shared objects that are in directories in sys.path?

I use python setup.py build_ext -R/usr/local/lib -I/usr/local/include/libcalg-1.0 and the compiled .so file is under the build folder. you can type python setup.py --help build_ext to see the explanations of -R and -I

Capturing mobile phone traffic on Wireshark

For iOS Devices:

? Open Terminal and simply write:

rvictl -s udid

it'll open an interface on Wireshark with a name, In my case its rvi0.

enter image description here

udid is iPhone's unique device id.

(How to find my iOS Device UDID)

How to use underscore.js as a template engine?

I wanted to share one more important finding.

use of <%= variable => would result in cross-site scripting vulnerability. So its more safe to use <%- variable -> instead.

We had to replace <%= with <%- to prevent cross-site scripting attacks. Not sure, whether this will it have any impact on the performance

org.xml.sax.SAXParseException: Content is not allowed in prolog

I took code of Dineshkumar and modified to Validate my XML file correctly:

_x000D_
_x000D_
import org.apache.log4j.Logger;_x000D_
_x000D_
public class Myclass{_x000D_
_x000D_
private static final Logger LOGGER = Logger.getLogger(Myclass.class);_x000D_
_x000D_
/**_x000D_
 * Validate XML file against Schemas XSD in pathEsquema directory_x000D_
 * @param pathEsquema directory that contains XSD Schemas to validate_x000D_
 * @param pathFileXML XML file to validate_x000D_
 * @throws BusinessException if it throws any Exception_x000D_
 */_x000D_
public static void validarXML(String pathEsquema, String pathFileXML) _x000D_
 throws BusinessException{ _x000D_
 String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";_x000D_
 String nameFileXSD = "file.xsd";_x000D_
 String MY_SCHEMA1 = pathEsquema+nameFileXSD);_x000D_
 ParserErrorHandler parserErrorHandler;_x000D_
 try{_x000D_
  SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);_x000D_
  _x000D_
  Source [] source = { _x000D_
   new StreamSource(new File(MY_SCHEMA1))_x000D_
   };_x000D_
  Schema schemaGrammar = schemaFactory.newSchema(source);_x000D_
_x000D_
  Validator schemaValidator = schemaGrammar.newValidator();_x000D_
  schemaValidator.setErrorHandler(_x000D_
   parserErrorHandler= new ParserErrorHandler());_x000D_
  _x000D_
  /** validate xml instance against the grammar. */_x000D_
  File file = new File(pathFileXML);_x000D_
  InputStream isS= new FileInputStream(file);_x000D_
  Reader reader = new InputStreamReader(isS,"UTF-8");_x000D_
  schemaValidator.validate(new StreamSource(reader));_x000D_
  _x000D_
  if(parserErrorHandler.getErrorHandler().isEmpty()&& _x000D_
   parserErrorHandler.getFatalErrorHandler().isEmpty()){_x000D_
   if(!parserErrorHandler.getWarningHandler().isEmpty()){_x000D_
    LOGGER.info(_x000D_
    String.format("WARNING validate XML:[%s] Descripcion:[%s]",_x000D_
     pathFileXML,parserErrorHandler.getWarningHandler()));_x000D_
   }else{_x000D_
    LOGGER.info(_x000D_
    String.format("OK validate  XML:[%s]",_x000D_
     pathFileXML));_x000D_
   }_x000D_
  }else{_x000D_
   throw new BusinessException(_x000D_
    String.format("Error validate  XML:[%s], FatalError:[%s], Error:[%s]",_x000D_
    pathFileXML,_x000D_
    parserErrorHandler.getFatalErrorHandler(),_x000D_
    parserErrorHandler.getErrorHandler()));_x000D_
  }  _x000D_
 }_x000D_
 catch(SAXParseException e){_x000D_
  throw new BusinessException(String.format("Error validate XML:[%s], SAXParseException:[%s]",_x000D_
   pathFileXML,e.getMessage()),e);_x000D_
 }_x000D_
 catch (SAXException e){_x000D_
  throw new BusinessException(String.format("Error validate XML:[%s], SAXException:[%s]",_x000D_
   pathFileXML,e.getMessage()),e);_x000D_
 }_x000D_
 catch (IOException e) {_x000D_
  throw new BusinessException(String.format("Error validate XML:[%s], _x000D_
   IOException:[%s]",pathFileXML,e.getMessage()),e);_x000D_
 }_x000D_
 _x000D_
}_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

Set HTML dropdown selected option using JSTL

Real simple. You just need to have the string 'selected' added to the right option. In the following code, ${myBean.foo == val ? 'selected' : ' '} will add the string 'selected' if the option's value is the same as the bean value;

<select name="foo" id="foo" value="${myBean.foo}">
    <option value="">ALL</option>
    <c:forEach items="${fooList}" var="val"> 
        <option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>   
    </c:forEach>                     
</select>

sed with literal string--not input file

Works like you want:

echo "A,B,C" | sed s/,/\',\'/g

Apply CSS to jQuery Dialog Buttons

If still noting is working for you add the following styles on your page style sheet

.ui-widget-content .ui-state-default {
  border: 0px solid #d3d3d3;
  background: #00ACD6 50% 50% repeat-x;
  font-weight: normal;
  color: #fff;
}

It will change the background color of the dialog buttons.

How do I restart a service on a remote machine in Windows?

One way would be to enable telnet server on the machin you want to control services on (add/remove windows components)

Open dos prompt
Type telnet yourmachineip/name
Log on
type net start &serviceName* e.g. w3svc

This will start IIS or you can use net stop to stop a service.

Depending on your setup you need to look at a way of securing the telnet connection as I think its unencrypted.

How to set a timeout on a http.request() in Node?

Elaborating on the answer @douwe here is where you would put a timeout on a http request.

// TYPICAL REQUEST
var req = https.get(http_options, function (res) {                                                                                                             
    var data = '';                                                                                                                                             

    res.on('data', function (chunk) { data += chunk; });                                                                                                                                                                
    res.on('end', function () {
        if (res.statusCode === 200) { /* do stuff with your data */}
        else { /* Do other codes */}
    });
});       
req.on('error', function (err) { /* More serious connection problems. */ }); 

// TIMEOUT PART
req.setTimeout(1000, function() {                                                                                                                              
    console.log("Server connection timeout (after 1 second)");                                                                                                                  
    req.abort();                                                                                                                                               
});

this.abort() is also fine.

How to use multiprocessing queue in Python?

A multi-producers and multi-consumers example, verified. It should be easy to modify it to cover other cases, single/multi producers, single/multi consumers.

from multiprocessing import Process, JoinableQueue
import time
import os

q = JoinableQueue()

def producer():
    for item in range(30):
        time.sleep(2)
        q.put(item)
    pid = os.getpid()
    print(f'producer {pid} done')


def worker():
    while True:
        item = q.get()
        pid = os.getpid()
        print(f'pid {pid} Working on {item}')
        print(f'pid {pid} Finished {item}')
        q.task_done()

for i in range(5):
    p = Process(target=worker, daemon=True).start()

# send thirty task requests to the worker
producers = []
for i in range(2):
    p = Process(target=producer)
    producers.append(p)
    p.start()

# make sure producers done
for p in producers:
    p.join()

# block until all workers are done
q.join()
print('All work completed')

Explanation:

  1. Two producers and five consumers in this example.
  2. JoinableQueue is used to make sure all elements stored in queue will be processed. 'task_done' is for worker to notify an element is done. 'q.join()' will wait for all elements marked as done.
  3. With #2, there is no need to join wait for every worker.
  4. But it is important to join wait for every producer to store element into queue. Otherwise, program exit immediately.

Adjust table column width to content size

If you want the table to still be 100% then set one of the columns to have a width:100%; That will extend that column to fill the extra space and allow the other columns to keep their auto width :)

How remove border around image in css?

it's a good idea to use a reset CSS. add this at the top of your CSS file

img, a {border:none, outline: none;}

hope this helps

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Try to open Services Window, by writing services.msc into Start->Run and hit Enter.

When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

This fixed my problem.. All I needed to do was to downgrade my google-services plugin in buildscript in the build.gradle(Project) level file as follows

buildscript{
     dependencies {
        // From =>
        classpath 'com.google.gms:google-services:4.3.0'
        // To =>
        classpath 'com.google.gms:google-services:4.2.0'
        // Add dependency
        classpath 'io.fabric.tools:gradle:1.28.1'
    }
}

Matplotlib - global legend and title aside subplots

Global title: In newer releases of matplotlib one can use Figure.suptitle() method of Figure:

import matplotlib.pyplot as plt
fig = plt.gcf()
fig.suptitle("Title centered above all subplots", fontsize=14)

Alternatively (based on @Steven C. Howell's comment below (thank you!)), use the matplotlib.pyplot.suptitle() function:

 import matplotlib.pyplot as plt
 # plot stuff
 # ...
 plt.suptitle("Title centered above all subplots", fontsize=14)

Print: Entry, ":CFBundleIdentifier", Does Not Exist

I faced the same problem with iOS 14 and Xcode 12.

Error: Command failed: ...../Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

I solved it by removing my yarn.lock file and node_modules folder. Then install everything again with yarn install. The logic behind it is that this will upgrade your react-native-cli which fixes this error.

How do I find the current directory of a batch file, and then use it for the path?

Try in yourbatch

set "batchisin=%~dp0"

which should set the variable to your batch's location.

How to merge remote changes at GitHub?

You can force it to push, but please do this ONLY when you're quite sure what you are doing.

The command is:

git push -f 

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

It seems like you are not going to your specific folder. For example, if I am working on a project named bugsBunny and it is saved in the folder d:/work:code , so first you have to go to that folder using cd d:/work/code/bugsBunny , then after that you can continue using your git commands.

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

How can I get query string values in JavaScript?

var getUrlParameters = function (name, url) {
    if (!name) {
        return undefined;
    }

    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    url = url || location.search;

    var regex = new RegExp('[\\?&#]' + name + '=?([^&#]*)', 'gi'), result, resultList = [];

    while (result = regex.exec(url)) {
        resultList.push(decodeURIComponent(result[1].replace(/\+/g, ' ')));
    }

    return resultList.length ? resultList.length === 1 ? resultList[0] : resultList : undefined;
};

Is it possible that one domain name has multiple corresponding IP addresses?

You can do it. That is what big guys do as well.

First query:

» host google.com 
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229

Next query:

» host google.com
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238

As you see, the list of IPs rotated around, but the relative order between two IPs stayed the same.

Update: I see several comments bragging about how DNS round-robin is not convenient for fail-over, so here is the summary: DNS is not for fail-over. So it is obviously not good for fail-over. It was never designed to be a solution for fail-over.

Python iterating through object attributes

Iterate over an objects attributes in python:

class C:
    a = 5
    b = [1,2,3]
    def foobar():
        b = "hi"    

for attr, value in C.__dict__.iteritems():
    print "Attribute: " + str(attr or "")
    print "Value: " + str(value or "")

Prints:

python test.py
Attribute: a
Value: 5
Attribute: foobar
Value: <function foobar at 0x7fe74f8bfc08>
Attribute: __module__
Value: __main__
Attribute: b
Value: [1, 2, 3]
Attribute: __doc__
Value:

Autoplay an audio with HTML5 embed tag while the player is invisible

"Sensitive" era

Modern browsers today seem to block (by default) these autoplay features. They are somewhat treated as pop-ops. Very intrusive. So yeah, users now have the complete control on when the sounds are played. [1,2,3]

HTML5 era

<audio controls autoplay loop hidden>
    <source src="audio.mp3" type="audio/mpeg">
</audio>

Early days of HTML

<embed src="audio.mp3" style="visibility:hidden" />

References

  1. Jer Noble, New <video> Policies for iOS, WebKit, link
  2. Allow or block media autoplay in Firefox, FireFox Help, link
  3. Mounir Lamouri, Unified autoplay, Chromium Blog, link
  4. Embedded content, World Wide Web Consortium, link

How to create a Jar file in Netbeans

I also tried to make an executable jar file that I could run with the following command:

java -jar <jarfile>

After some searching I found the following link:

Packaging and Deploying Desktop Java Applications

I set the project's main class:

  1. Right-click the project's node and choose Properties
  2. Select the Run panel and enter the main class in the Main Class field
  3. Click OK to close the Project Properties dialog box
  4. Clean and build project

Then in the fodler dist the newly created jar should be executable with the command I mentioned above.

Need to combine lots of files in a directory

Assuming these are text files (since you are using notepad++) and that you are on Windows, you could fashion a simple batch script to concatenate them together.

For example, in the directory with all the text files, execute the following:

for %f in (*.txt) do type "%f" >> combined.txt

This will merge all files matching *.txt into one file called combined.txt.

For more information:

http://www.howtogeek.com/howto/keyboard-ninja/keyboard-ninja-concatenate-multiple-text-files-in-windows/

List<object>.RemoveAll - How to create an appropriate Predicate

The RemoveAll() methods accept a Predicate<T> delegate (until here nothing new). A predicate points to a method that simply returns true or false. Of course, the RemoveAll will remove from the collection all the T instances that return True with the predicate applied.

C# 3.0 lets the developer use several methods to pass a predicate to the RemoveAll method (and not only this one…). You can use:

Lambda expressions

vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);

Anonymous methods

vehicles.RemoveAll(delegate(Vehicle v) {
  return v.EnquiryID == 123;
});

Normal methods

vehicles.RemoveAll(VehicleCustomPredicate);
private static bool
VehicleCustomPredicate (Vehicle v) {
    return v.EnquiryID == 123; 
}

Can I assume (bool)true == (int)1 for any C++ compiler?

Yes. The casts are redundant. In your expression:

true == 1

Integral promotion applies and the bool value will be promoted to an int and this promotion must yield 1.

Reference: 4.7 [conv.integral] / 4: If the source type is bool... true is converted to one.

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

Bookmarking this URL should give you a full-screen compose window, without any distractions:

https://mail.google.com/mail/?view=cm&fs=1&tf=1

Additionally, if you want to be future-proof (see for instance how other URLs in this question stopped working) you can bookmark a link to:

mailto:

It will open your default email client and you probably already have Gmail configured for that purpose.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

In short, git is trying to access a repo it considers on another filesystem and to tell it explicitly that you're okay with this, you must set the environment variable GIT_DISCOVERY_ACROSS_FILESYSTEM=1

I'm working in a CI/CD environment and using a dockerized git so I have to set it in that environment docker run -e GIT_DISCOVERY_ACROSS_FILESYSTEM=1 -v $(pwd):/git --rm alpine/git rev-parse --short HEAD\'

If you're curious: Above mounts $(pwd) into the git docker container and passes "rev-parse --short HEAD" to the git command in the container, which it then runs against that mounted volums.

"Exception has been thrown by the target of an invocation" error (mscorlib)

I know its kind of odd but I experienced this error for a c# application and finally I found out the problem is the Icon of the form! when I changed it everything just worked fine.

I should say that I had this error just in XP not in 7 or 8 .

Convert IQueryable<> type object to List<T> type?

The List class's constructor can convert an IQueryable for you:

public static List<TResult> ToList<TResult>(this IQueryable source)
{
    return new List<TResult>(source);
}

or you can just convert it without the extension method, of course:

var list = new List<T>(queryable);

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

the time signal is not built into network antennas: you have to use the NTP protocol in order to retrieve the time on a ntp server. there are plenty of ntp clients, available as standalone executables or libraries.

the gps signal does indeed include a precise time signal, which is available with any "fix".

however, if nor the network, nor the gps are available, your only choice is to resort on the time of the phone... your best solution would be to use a system wide setting to synchronize automatically the phone time to the gps or ntp time, then always use the time of the phone.

note that the phone time, if synchronized regularly, should not differ much from the gps or ntp time. also note that forcing a user to synchronize its time may be intrusive, you 'd better ask your user if he accepts synchronizing. at last, are you sure you absolutely need a time that precise ?

Where does application data file actually stored on android device?

Use Context.getDatabasePath(databasename). The context can be obtained from your application.

If you get previous data back it can be either a) the data was stored in an unconventional location and therefore not deleted with uninstall or b) Titanium backed up the data with the app (it can do that).

Spring's overriding bean

Another good approach not mentioned in other posts is to use PropertyOverrideConfigurer in case you just want to override properties of some beans.

For example if you want to override the datasource for testing (i.e. use an in-memory database) in another xml config, you just need to use <context:property-override ..."/> in new config and a .properties file containing key-values taking the format beanName.property=newvalue overriding the main props.

application-mainConfig.xml:

<bean id="dataSource" 
    class="org.apache.commons.dbcp.BasicDataSource" 
    p:driverClassName="org.postgresql.Driver"
    p:url="jdbc:postgresql://localhost:5432/MyAppDB" 
    p:username="myusername" 
    p:password="mypassword"
    destroy-method="close" />

application-testConfig.xml:

<import resource="classpath:path/to/file/application-mainConfig.xml"/>

<!-- override bean props -->
<context:property-override location="classpath:path/to/file/beanOverride.properties"/>

beanOverride.properties:

dataSource.driverClassName=org.h2.Driver
dataSource.url=jdbc:h2:mem:MyTestDB

How can I pass arguments to anonymous functions in JavaScript?

What you have done is created a new anonymous function that takes a single parameter which then gets assigned to the local variable myMessage inside the function. Since no arguments are actually passed, and arguments which aren't passed a value become null, your function just does alert(null).

HTML5: Slider with two inputs possible?

No, the HTML5 range input only accepts one input. I would recommend you to use something like the jQuery UI range slider for that task.

Java correct way convert/cast object to Double

You can use the instanceof operator to test to see if it is a double prior to casting. You can then safely cast it to a double. In addition you can test it against other known types (e.g. Integer) and then coerce them into a double manually if desired.

    Double d = null;
    if (obj instanceof Double) {
        d = (Double) obj;
    }

How to get a list of current open windows/process with Java?

This might be useful for apps with a bundled JRE: I scan for the folder name that i'm running the application from: so if you're application is executing from:

C:\Dev\build\SomeJavaApp\jre-9.0.1\bin\javaw.exe

then you can find if it's already running in J9, by:

public static void main(String[] args) {
    AtomicBoolean isRunning = new AtomicBoolean(false);
    ProcessHandle.allProcesses()
            .filter(ph -> ph.info().command().isPresent() && ph.info().command().get().contains("SomeJavaApp"))
            .forEach((process) -> {
                isRunning.set(true);
            });
    if (isRunning.get()) System.out.println("SomeJavaApp is running already");
}

How to access array elements in a Django template?

when you render a request tou coctext some information: for exampel:

return render(request, 'path to template',{'username' :username , 'email'.email})

you can acces to it on template like this : for variabels :

{% if username %}{{ username }}{% endif %}

for array :

{% if username %}{{ username.1 }}{% endif %}
{% if username %}{{ username.2 }}{% endif %}

you can also name array objects in views.py and ten use it like:

{% if username %}{{ username.first }}{% endif %}

if there is other problem i wish to help you

Laravel Fluent Query Builder Join with subquery

Query with sub query in Laravel

$resortData = DB::table('resort')
        ->leftJoin('country', 'resort.country', '=', 'country.id')
        ->leftJoin('states', 'resort.state', '=', 'states.id')
        ->leftJoin('city', 'resort.city', '=', 'city.id')
        ->select('resort.*', 'country.name as country_name', 'states.name as state_name','city.name as city_name', DB::raw("(SELECT GROUP_CONCAT(amenities.name) from resort_amenities LEFT JOIN amenities on amenities.id= resort_amenities.amenities_id WHERE resort_amenities.resort_id=resort.id) as amenities_name"))->groupBy('resort.id')
        ->orderBy('resort.id', 'DESC')
       ->get();

How to find the size of a table in SQL?

And in PostgreSQL:

SELECT pg_size_pretty(pg_relation_size('tablename'));

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Start with the triangle...

    *
   **
  ***
 ****

representing 1+2+3+4 so far. Cut the triangle in half along one dimension...

     *
    **
  * **
 ** **

Rotate the smaller part 180 degrees, and stick it on top of the bigger part...

    **
    * 

     *
    **
    **
    **

Close the gap to get a rectangle.

At first sight this only works if the base of the rectangle has an even length - but if it has an odd length, you just cut the middle column in half - it still works with a half-unit-wide twice-as-tall (still integer area) strip on one side of your rectangle.

Whatever the base of the triangle, the width of your rectangle is (base / 2) and the height is (base + 1), giving ((base + 1) * base) / 2.

However, my base is your n-1, since the bubble sort compares a pair of items at a time, and therefore iterates over only (n-1) positions for the first loop.

How do I save and restore multiple variables in python?

Another approach to saving multiple variables to a pickle file is:

import pickle

a = 3; b = [11,223,435];
pickle.dump([a,b], open("trial.p", "wb"))

c,d = pickle.load(open("trial.p","rb"))

print(c,d) ## To verify

Put byte array to JSON and vice versa

Here is a good example of base64 encoding byte arrays. It gets more complicated when you throw unicode characters in the mix to send things like PDF documents. After encoding a byte array the encoded string can be used as a JSON property value.

Apache commons offers good utilities:

 byte[] bytes = getByteArr();
 String base64String = Base64.encodeBase64String(bytes);
 byte[] backToBytes = Base64.decodeBase64(base64String);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding

Java server side example:

public String getUnsecureContentBase64(String url)
        throws ClientProtocolException, IOException {

            //getUnsecureContent will generate some byte[]
    byte[] result = getUnsecureContent(url);

            // use apache org.apache.commons.codec.binary.Base64
            // if you're sending back as a http request result you may have to
            // org.apache.commons.httpclient.util.URIUtil.encodeQuery
    return Base64.encodeBase64String(result);
}

JavaScript decode:

//decode URL encoding if encoded before returning result
var uriEncodedString = decodeURIComponent(response);

var byteArr = base64DecToArr(uriEncodedString);

//from mozilla
function b64ToUint6 (nChr) {

  return nChr > 64 && nChr < 91 ?
      nChr - 65
    : nChr > 96 && nChr < 123 ?
      nChr - 71
    : nChr > 47 && nChr < 58 ?
      nChr + 4
    : nChr === 43 ?
      62
    : nChr === 47 ?
      63
    :
      0;

}

function base64DecToArr (sBase64, nBlocksSize) {

  var
    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
    nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);

  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
    nMod4 = nInIdx & 3;
    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
    if (nMod4 === 3 || nInLen - nInIdx === 1) {
      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
        taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
      }
      nUint24 = 0;

    }
  }

  return taBytes;
}

Your project contains error(s), please fix it before running it

it can also happen if you move required files. Simply check Problems View (menu window -> show view -> Problems) as told here

Forking vs. Branching in GitHub

It has to do with the general workflow of Git. You're unlikely to be able to push directly to the main project's repository. I'm not sure if GitHub project's repository support branch-based access control, as you wouldn't want to grant anyone the permission to push to the master branch for example.

The general pattern is as follows:

  • Fork the original project's repository to have your own GitHub copy, to which you'll then be allowed to push changes.
  • Clone your GitHub repository onto your local machine
  • Optionally, add the original repository as an additional remote repository on your local repository. You'll then be able to fetch changes published in that repository directly.
  • Make your modifications and your own commits locally.
  • Push your changes to your GitHub repository (as you generally won't have the write permissions on the project's repository directly).
  • Contact the project's maintainers and ask them to fetch your changes and review/merge, and let them push back to the project's repository (if you and them want to).

Without this, it's quite unusual for public projects to let anyone push their own commits directly.

Xcode 4: create IPA file instead of .xcarchive

For Xcode 4.6 (and Xcode 5) archives

  • In Organizer, right-click an archive, select Show in Finder
  • In Finder, right-click an archive, select Show Package Contents
  • Open the folder Products > Applications
  • The application is there
  • Drag the application into iTunes Apps folder

    enter image description here

  • Right-click on the application in iTunes Apps, select Show in Finder

  • The .ipa is there!

HTML <sup /> tag affecting line height, how to make it consistent?

The reason why the <sup> tag is affecting the spacing between two lines has to do with a number of factors. The factors are: line height, size of the superscript in relation to the regular font, the line height of the superscript and last but not least what is the bottom of the superscript aligning with... If you set... the line height of regular text to be in a "tunnel band" (that's what I call it) of 135% then regular text (the 100%) gets white padded by 35% of more white. For a paragraph this looks like this:

 p
    {
            line-height: 135%;
    }

If you then do not white pad the superscript...(i.e. keep its line height to 0) the superscript only has the width of its own text... if you then ask the superscript to be a percentage of the regular font (for example 70%) and you align it with the middle of the regular text (text-middle), you can eliminate the problem and get a superscript that looks like a superscript. Here it is:

sup
{
    font-size: 70%;
    vertical-align: text-middle;
    line-height: 0;
}

Unexpected token ILLEGAL in webkit

You can use online Minify, it removes these invisible characters efficiently but also changes your code. So be careful.

http://jscompress.com/

RecyclerView expand/collapse items

Not saying this is the best approach, but it seems to work for me.

The full code may be found at: Example code at: https://github.com/dbleicher/recyclerview-grid-quickreturn

First off, add the expanded area to your cell/item layout, and make the enclosing cell layout animateLayoutChanges="true". This will ensure that the expand/collapse is animated:

<LinearLayout
    android:id="@+id/llCardBack"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:animateLayoutChanges="true"
    android:padding="4dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|fill_horizontal"
        android:padding="10dp"
        android:gravity="center"
        android:background="@android:color/holo_green_dark"
        android:text="This is a long title to show wrapping of text in the view."
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tvSubTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|fill_horizontal"
        android:background="@android:color/holo_purple"
        android:padding="6dp"
        android:text="My subtitle..."
        android:textColor="@android:color/white"
        android:textSize="12sp" />

    <LinearLayout
        android:id="@+id/llExpandArea"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dp"
            android:text="Item One" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dp"
            android:text="Item Two" />

    </LinearLayout>
</LinearLayout>

Then, make your RV Adapter class implement View.OnClickListener so that you can act on the item being clicked. Add an int field to hold the position of the one expanded view, and initialize it to a negative value:

private int expandedPosition = -1;

Finally, implement your ViewHolder, onBindViewHolder() methods and override the onClick() method. You will expand the view in onBindViewHolder if it's position is equal to "expandedPosition", and hide it if not. You set the value of expandedPosition in the onClick listener:

@Override
public void onBindViewHolder(RVAdapter.ViewHolder holder, int position) {

    int colorIndex = randy.nextInt(bgColors.length);
    holder.tvTitle.setText(mDataset.get(position));
    holder.tvTitle.setBackgroundColor(bgColors[colorIndex]);
    holder.tvSubTitle.setBackgroundColor(sbgColors[colorIndex]);

    if (position == expandedPosition) {
        holder.llExpandArea.setVisibility(View.VISIBLE);
    } else {
        holder.llExpandArea.setVisibility(View.GONE);
    }
}

@Override
public void onClick(View view) {
    ViewHolder holder = (ViewHolder) view.getTag();
    String theString = mDataset.get(holder.getPosition());

    // Check for an expanded view, collapse if you find one
    if (expandedPosition >= 0) {
        int prev = expandedPosition;
        notifyItemChanged(prev);
    }
    // Set the current position to "expanded"
    expandedPosition = holder.getPosition();
    notifyItemChanged(expandedPosition);

    Toast.makeText(mContext, "Clicked: "+theString, Toast.LENGTH_SHORT).show();
}

/**
 * Create a ViewHolder to represent your cell layout
 * and data element structure
 */
public static class ViewHolder extends RecyclerView.ViewHolder {
    TextView tvTitle;
    TextView tvSubTitle;
    LinearLayout llExpandArea;

    public ViewHolder(View itemView) {
        super(itemView);

        tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
        tvSubTitle = (TextView) itemView.findViewById(R.id.tvSubTitle);
        llExpandArea = (LinearLayout) itemView.findViewById(R.id.llExpandArea);
    }
}

This should expand only one item at a time, using the system-default animation for the layout change. At least it works for me. Hope it helps.

What's the best way to build a string of delimited items in Java?

Use StringBuilder and class Separator

StringBuilder buf = new StringBuilder();
Separator sep = new Separator(", ");
for (String each : list) {
    buf.append(sep).append(each);
}

Separator wraps a delimiter. The delimiter is returned by Separator's toString method, unless on the first call which returns the empty string!

Source code for class Separator

public class Separator {

    private boolean skipFirst;
    private final String value;

    public Separator() {
        this(", ");
    }

    public Separator(String value) {
        this.value = value;
        this.skipFirst = true;
    }

    public void reset() {
        skipFirst = true;
    }

    public String toString() {
        String sep = skipFirst ? "" : value;
        skipFirst = false;
        return sep;
    }

}

Convert RGBA PNG to RGB with PIL

import numpy as np
import PIL

def convert_image(image_file):
    image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
    original_width, original_height = image.size

    np_image = np.array(image)
    new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3)) 
    # create 3D array

    for each_channel in range(3):
        new_image[:,:,each_channel] = np_image[:,:,each_channel]  
        # only copy first 3 channels.

    # flushing
    np_image = []
    return new_image

SyntaxError: unexpected EOF while parsing

elec_and_weather['DEMAND_t-%i'% k] = np.zeros(len(elec_and_weather['DEMAND']))'

The error comes at the end of the line where you have the (') sign; this error always means that you have a syntax error.

ThreeJS: Remove object from scene

When you use : scene.remove(object); The object is removed from the scene, but the collision with it is still enabled !

To remove also the collsion with the object, you can use that (for an array) : objectsArray.splice(i, 1);

Example :

for (var i = 0; i < objectsArray.length; i++) {
//::: each object ::://
var object = objectsArray[i]; 
//::: remove all objects from the scene ::://
scene.remove(object); 
//::: remove all objects from the array ::://
objectsArray.splice(i, 1); 

}

Organizing a multiple-file Go project

Keep the files in the same directory and use package main in all files.

myproj/
   your-program/
      main.go
      lib.go

Then run:

~/myproj/your-program$ go build && ./your-program

iOS application: how to clear notifications?

When you logout from your app, at that time you have to use a below line of code on your logout button click method.

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];

[[UIApplication sharedApplication] cancelAllLocalNotifications];

and this works perfectly in my app.

Paritition array into N chunks with Numpy

Just some examples on usage of array_split, split, hsplit and vsplit:

n [9]: a = np.random.randint(0,10,[4,4])

In [10]: a
Out[10]: 
array([[2, 2, 7, 1],
       [5, 0, 3, 1],
       [2, 9, 8, 8],
       [5, 7, 7, 6]])

Some examples on using array_split:
If you give an array or list as second argument you basically give the indices (before) which to 'cut'

# split rows into 0|1 2|3
In [4]: np.array_split(a, [1,3])
Out[4]:                                                                                                                       
[array([[2, 2, 7, 1]]),                                                                                                       
 array([[5, 0, 3, 1],                                                                                                         
       [2, 9, 8, 8]]),                                                                                                        
 array([[5, 7, 7, 6]])]

# split columns into 0| 1 2 3
In [5]: np.array_split(a, [1], axis=1)                                                                                           
Out[5]:                                                                                                                       
[array([[2],                                                                                                                  
       [5],                                                                                                                   
       [2],                                                                                                                   
       [5]]),                                                                                                                 
 array([[2, 7, 1],                                                                                                            
       [0, 3, 1],
       [9, 8, 8],
       [7, 7, 6]])]

An integer as second arg. specifies the number of equal chunks:

In [6]: np.array_split(a, 2, axis=1)
Out[6]: 
[array([[2, 2],
       [5, 0],
       [2, 9],
       [5, 7]]),
 array([[7, 1],
       [3, 1],
       [8, 8],
       [7, 6]])]

split works the same but raises an exception if an equal split is not possible

In addition to array_split you can use shortcuts vsplit and hsplit.
vsplit and hsplit are pretty much self-explanatry:

In [11]: np.vsplit(a, 2)
Out[11]: 
[array([[2, 2, 7, 1],
       [5, 0, 3, 1]]),
 array([[2, 9, 8, 8],
       [5, 7, 7, 6]])]

In [12]: np.hsplit(a, 2)
Out[12]: 
[array([[2, 2],
       [5, 0],
       [2, 9],
       [5, 7]]),
 array([[7, 1],
       [3, 1],
       [8, 8],
       [7, 6]])]

Python equivalent of D3.js

Check out python-nvd3. It is a python wrapper for nvd3. Looks cooler than d3.py and also has more chart options.

How to get Selected Text from select2 when using <input>

This one is working fine using V 4.0.3

var vv = $('.mySelect2');     
var label = $(vv).children("option[value='"+$(vv).select2("val")+"']").first().html();
console.log(label); 

Remove empty space before cells in UITableView

In My Case I had a UILabel under the UITableView in view hierarchy.

I moved it "forward" and the blank space appeared. Not sure why but it works like this, if theres anything under the tableView, it hides the blank space.

Also you can try checking/uncheking "Adjust Scroll View Insets" on your view controller inspector on storyboard.

enter image description here

Can I change the color of Font Awesome's icon color?

To hit only cog-icons in that kind of button, you can give the button a class, and set the color for the icon only when inside the button.

HTML:

<a class="my-nice-button" href="/users/edit">
    <i class="icon-cog"></i>
    Edit profile
</a>

CSS:

.my-nice-button>i { color: black; }

This will make any icon that is a direct descendant of your button black.

How to Create an excel dropdown list that displays text with a numeric hidden value

There are two types of drop down lists available (I am not sure since which version).

ActiveX Drop Down
You can set the column widths, so your hidden column can be set to 0.

Form Drop Down
You could set the drop down range to a hidden sheet and reference the cell adjacent to the selected item. This would also work with the ActiveX type control.

How to convert Nonetype to int or string?

int(value or 0)

This will use 0 in the case when you provide any value that Python considers False, such as None, 0, [], "", etc. Since 0 is False, you should only use 0 as the alternative value (otherwise you will find your 0s turning into that value).

int(0 if value is None else value)

This replaces only None with 0. Since we are testing for None specifically, you can use some other value as the replacement.

Core dump file analysis

Steps to debug coredump using GDB:

Some generic help:

gdb start GDB, with no debugging les

gdb program begin debugging program

gdb program core debug coredump core produced by program

gdb --help describe command line options

  1. First of all, find the directory where the corefile is generated.

  2. Then use ls -ltr command in the directory to find the latest generated corefile.

  3. To load the corefile use

    gdb binary path of corefile
    

    This will load the corefile.

  4. Then you can get the information using the bt command.

    For a detailed backtrace use bt full.

  5. To print the variables, use print variable-name or p variable-name

  6. To get any help on GDB, use the help option or use apropos search-topic

  7. Use frame frame-number to go to the desired frame number.

  8. Use up n and down n commands to select frame n frames up and select frame n frames down respectively.

  9. To stop GDB, use quit or q.

Controller 'ngModel', required by directive '...', can't be found

As described here: Angular NgModelController, you should provide the <input with the required controller ngModel

<input submit-required="true" ng-model="user.Name"></input>

Loop through an array of strings in Bash?

You can use the syntax of ${arrayName[@]}

#!/bin/bash
# declare an array called files, that contains 3 values
files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
for i in "${files[@]}"
do
    echo "$i"
done

Why doesn't JUnit provide assertNotEquals methods?

The obvious reason that people wanted assertNotEquals() was to compare builtins without having to convert them to full blown objects first:

Verbose example:

....
assertThat(1, not(equalTo(Integer.valueOf(winningBidderId))));
....

vs.

assertNotEqual(1, winningBidderId);

Sadly since Eclipse doesn't include JUnit 4.11 by default you must be verbose.

Caveat I don't think the '1' needs to be wrapped in an Integer.valueOf() but since I'm newly returned from .NET don't count on my correctness.

Only numbers. Input number in React

The most effective and simple solution I found:

<input
    type="number"
    name="phone"
    placeholder="Phone number"
    onKeyDown={e => /[\+\-\.\,]$/.test(e.key) && e.preventDefault()}
/>

Retrieving subfolders names in S3 bucket from boto3

The big realisation with S3 is that there are no folders/directories just keys. The apparent folder structure is just prepended to the filename to become the 'Key', so to list the contents of myBucket's some/path/to/the/file/ you can try:

s3 = boto3.client('s3')
for obj in s3.list_objects_v2(Bucket="myBucket", Prefix="some/path/to/the/file/")['Contents']:
    print(obj['Key'])

which would give you something like:

some/path/to/the/file/yo.jpg
some/path/to/the/file/meAndYou.gif
...

How to shrink temp tablespace in oracle?

The options for managing tablespaces have got a lot better over the versions starting with 8i. This is especially true if you are using the appropriate types of file for a temporary tablespace (i.e. locally managed tempfiles).

So, it could be as simple as this command, which will shrink your tablespace to 128 meg...

alter tablespace <your_temp_ts> shrink space keep 128M;

The Oracle online documentation is pretty good. Find out more.

edit

It would appear the OP has an earlier version of the database. With earlier versions we have to resize individual datafiles. So, first of all, find the file names. One or other of these queries should do it...

select file_name from dba_data_files where tablespace_name = '<your_temp_ts>'
/

select file_name from dba_temp_files where tablespace_name = '<your_temp_ts>'
/ 

Then use that path in this command:

alter database datafile '/full/file/path/temp01.dbf'  resize 128m
/

Show/Hide Div on Scroll

Here is my answer when you want to animate it and start fading it out after couple of seconds. I used opacity because first of all i didn't want to fade it out completely, second, it does not go back and force after many scrolls.

$(window).scroll(function () {
    var elem = $('div');
    setTimeout(function() {
        elem.css({"opacity":"0.2","transition":"2s"});
    },4000);            
    elem.css({"opacity":"1","transition":"1s"});    
});

"Series objects are mutable and cannot be hashed" error

Shortly: gene_name[x] is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.

Further explanation:

Mutable objects are objects which value can be changed. For example, list is a mutable object, since you can append to it. int is an immutable object, because you can't change it. When you do:

a = 5;
a = 3;

You don't change the value of a, you create a new object and make a point to its value.

Mutable objects cannot be hashed. See this answer.

To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple, string, int.

Erase the current printed console line

This script is hardcoded for your example.

#include <stdio.h>

int main ()
{

    //write some input  
    fputs("hello\n",stdout);

    //wait one second to change line above
    sleep(1);

    //remove line
    fputs("\033[A\033[2K",stdout);
    rewind(stdout);

    //write new line
    fputs("bye\n",stdout);

    return 0;
}

Click here for source.

@selector() in Swift?

you create the Selector like below.
1.

UIBarButtonItem(
    title: "Some Title",
    style: UIBarButtonItemStyle.Done,
    target: self,
    action: "flatButtonPressed"
)

2.

flatButton.addTarget(self, action: "flatButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)

Take note that the @selector syntax is gone and replaced with a simple String naming the method to call. There’s one area where we can all agree the verbosity got in the way. Of course, if we declared that there is a target method called flatButtonPressed: we better write one:

func flatButtonPressed(sender: AnyObject) {
  NSLog("flatButtonPressed")
}

set the timer:

    var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, 
                    target: self, 
                    selector: Selector("flatButtonPressed"), 
                    userInfo: userInfo, 
                    repeats: true)
    let mainLoop = NSRunLoop.mainRunLoop()  //1
    mainLoop.addTimer(timer, forMode: NSDefaultRunLoopMode) //2 this two line is optinal

In order to be complete, here’s the flatButtonPressed

func flatButtonPressed(timer: NSTimer) {
}

Open Url in default web browser

You should use Linking.

Example from the docs:

class OpenURLButton extends React.Component {
  static propTypes = { url: React.PropTypes.string };
  handleClick = () => {
    Linking.canOpenURL(this.props.url).then(supported => {
      if (supported) {
        Linking.openURL(this.props.url);
      } else {
        console.log("Don't know how to open URI: " + this.props.url);
      }
    });
  };
  render() {
    return (
      <TouchableOpacity onPress={this.handleClick}>
        {" "}
        <View style={styles.button}>
          {" "}<Text style={styles.text}>Open {this.props.url}</Text>{" "}
        </View>
        {" "}
      </TouchableOpacity>
    );
  }
}

Here's an example you can try on Expo Snack:

import React, { Component } from 'react';
import { View, StyleSheet, Button, Linking } from 'react-native';
import { Constants } from 'expo';

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
       <Button title="Click me" onPress={ ()=>{ Linking.openURL('https://google.com')}} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
});

MySQL Select Date Equal to Today

Sounds like you need to add the formatting to the WHERE:

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE DATE_FORMAT(users.signup_date, '%Y-%m-%d') = CURDATE()

See SQL Fiddle with Demo

Setting focus to a textbox control

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    TextBox1.Select()
End Sub

How can I undo git reset --hard HEAD~1?

I know this is an old thread... but as many people are searching for ways to undo stuff in Git, I still think it may be a good idea to continue giving tips here.

When you do a "git add" or move anything from the top left to the bottom left in git gui the content of the file is stored in a blob and the file content is possible to recover from that blob.

So it is possible to recover a file even if it was not committed but it has to have been added.

git init  
echo hello >> test.txt  
git add test.txt  

Now the blob is created but it is referenced by the index so it will no be listed with git fsck until we reset. So we reset...

git reset --hard  
git fsck  

you will get a dangling blob ce013625030ba8dba906f756967f9e9ca394464a

git show ce01362  

will give you the file content "hello" back

To find unreferenced commits I found a tip somewhere suggesting this.

gitk --all $(git log -g --pretty=format:%h)  

I have it as a tool in git gui and it is very handy.

Export pictures from excel file into jpg using VBA

Dim filepath as string
Sheets("Sheet 1").ChartObjects("Chart 1").Chart.Export filepath & "Name.jpg"

Slimmed down the code to the absolute minimum if needed.

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I've managed to find the fix for this. It was found courtesy of this blog post:

http://vandadnp.wordpress.com/2012/03/18/xcode-4-3-1-cannot-attach-to-ios-simulator/

The solution is to press cmd+shift+, (command, shift and then comma ",").. that loads some options for release or debugging.

Change the debugger from LLDB to GDB. This fixes the issue.

RVM is not a function, selecting rubies with 'rvm use ...' will not work

FWIW- I just ran across this as well, it was in the context of a cancelled selenium run. Perhaps there was a sub-shell being instantiated and left in place. Closing that terminal window and opening a new one was all I needed to do. (macOS Sierra)

How do I remove an array item in TypeScript?

It is my solution for that:

onDelete(id: number) {
    this.service.delete(id).then(() => {
        let index = this.documents.findIndex(d => d.id === id); //find index in your array
        this.documents.splice(index, 1);//remove element from array
    });

    event.stopPropagation();
}

DOM element to corresponding vue.js component

If you want listen an event (i.e OnClick) on an input with "demo" id, you can use:

new Vue({
  el: '#demo',
  data: {
    n: 0
  },
  methods: {
   onClick: function (e) {
     console.log(e.target.tagName) // "A"
     console.log(e.targetVM === this) // true
  }
 }
})

sys.argv[1] meaning in script

sys.argv is a list.

This list is created by your command line, it's a list of your command line arguments.

For example:

in your command line you input something like this,

python3.2 file.py something

sys.argv will become a list ['file.py', 'something']

In this case sys.argv[1] = 'something'

Get access to parent control from user control - C#

Description

You can get the parent control using Control.Parent.

Sample

So if you have a Control placed on a form this.Parent would be your Form.

Within your Control you can do

Form parentForm = (this.Parent as Form);

More Information

Update after a comment by Farid-ur-Rahman (He was asking the question)

My Control and a listbox (listBox1) both are place on a Form (Form1). I have to add item in a listBox1 when user press a button placed in my Control.

You have two possible ways to get this done.

1. Use `Control.Parent

Sample

MyUserControl

    private void button1_Click(object sender, EventArgs e)
    {
        if (this.Parent == null || this.Parent.GetType() != typeof(MyForm))
            return;

        ListBox listBox = (this.Parent as MyForm).Controls["listBox1"] as ListBox;
        listBox.Items.Add("Test");
    }

or

2.

  • put a property public MyForm ParentForm { get; set; } to your UserControl
  • set the property in your Form
  • assuming your ListBox is named listBox1 otherwise change the name

Sample

MyForm

public partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();
        this.myUserControl1.ParentForm = this;
    }
}

MyUserControl

public partial class MyUserControl : UserControl
{
    public MyForm ParentForm { get; set; }

    public MyUserControl()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (ParentForm == null)
            return;

        ListBox listBox = (ParentForm.Controls["listBox1"] as ListBox);
        listBox.Items.Add("Test");

    }
}

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

Simply creating a filter will do the trick. (Answered for Angular 1.6)

.filter('trustHtml', [
        '$sce',
        function($sce) {
            return function(value) {
                return $sce.trustAs('html', value);
            }
        }
    ]);

And use this as follow in the html.

<h2 ng-bind-html="someScopeValue | trustHtml"></h2>

How can I find all the subsets of a set, with exactly n elements?

itertools.combinations is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function.

import itertools
def findsubsets(S,m):
    return set(itertools.combinations(S, m))

S: The set for which you want to find subsets
m: The number of elements in the subset

Loading an image to a <img> from <input file>

As iEamin said in his answer, HTML 5 does now support this. The link he gave, http://www.html5rocks.com/en/tutorials/file/dndfiles/ , is excellent. Here is a minimal sample based on the samples at that site, but see that site for more thorough examples.

Add an onchange event listener to your HTML:

<input type="file" onchange="onFileSelected(event)">

Make an image tag with an id (I'm specifying height=200 to make sure the image isn't too huge onscreen):

<img id="myimage" height="200">

Here is the JavaScript of the onchange event listener. It takes the File object that was passed as event.target.files[0], constructs a FileReader to read its contents, and sets up a new event listener to assign the resulting data: URL to the img tag:

function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var imgtag = document.getElementById("myimage");
  imgtag.title = selectedFile.name;

  reader.onload = function(event) {
    imgtag.src = event.target.result;
  };

  reader.readAsDataURL(selectedFile);
}

Maven: add a folder or jar file into current classpath

From docs and example it is not clear that classpath manipulation is not allowed.

<configuration>
 <compilerArgs>
  <arg>classpath=${basedir}/lib/bad.jar</arg>
 </compilerArgs>
</configuration>

But see Java docs (also https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/solaris/javac.html)

-classpath path Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set.

Maybe it is possible to get current classpath and extend it,
see in maven, how output the classpath being used?

    <properties>
      <cpfile>cp.txt</cpfile>
    </properties>

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.9</version>
    <executions>
      <execution>
        <id>build-classpath</id>
        <phase>generate-sources</phase>
        <goals>
          <goal>build-classpath</goal>
        </goals>
        <configuration>
          <outputFile>${cpfile}</outputFile>
        </configuration>
      </execution>
    </executions>
  </plugin>

Read file (Read a file into a Maven property)

<plugin>
  <groupId>org.codehaus.gmaven</groupId>
  <artifactId>gmaven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <phase>generate-resources</phase>
      <goals>
        <goal>execute</goal>
      </goals>
      <configuration>
        <source>
          def file = new File(project.properties.cpfile)
          project.properties.cp = file.getText()
        </source>
      </configuration>
    </execution>
  </executions>
</plugin>

and finally

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
      <compilerArgs>
         <arg>classpath=${cp}:${basedir}/lib/bad.jar</arg>
      </compilerArgs>
    </configuration>
   </plugin>

How can I read SMS messages from the device programmatically in Android?

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final String myPackageName = getPackageName();
        if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {

            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
            startActivityForResult(intent, 1);
        }else {
            List<Sms> lst = getAllSms();
        }
    }else {
        List<Sms> lst = getAllSms();
    }

Set app as default SMS app

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
    if (resultCode == RESULT_OK) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final String myPackageName = getPackageName();
            if (Telephony.Sms.getDefaultSmsPackage(mActivity).equals(myPackageName)) {

                List<Sms> lst = getAllSms();
            }
        }
    }
}
}

Function to get SMS

public List<Sms> getAllSms() {
    List<Sms> lstSms = new ArrayList<Sms>();
    Sms objSms = new Sms();
    Uri message = Uri.parse("content://sms/");
    ContentResolver cr = mActivity.getContentResolver();

    Cursor c = cr.query(message, null, null, null, null);
    mActivity.startManagingCursor(c);
    int totalSMS = c.getCount();

    if (c.moveToFirst()) {
        for (int i = 0; i < totalSMS; i++) {

            objSms = new Sms();
            objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
            objSms.setAddress(c.getString(c
                    .getColumnIndexOrThrow("address")));
            objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
            objSms.setReadState(c.getString(c.getColumnIndex("read")));
            objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
            if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
                objSms.setFolderName("inbox");
            } else {
                objSms.setFolderName("sent");
            }

            lstSms.add(objSms);
            c.moveToNext();
        }
    }
    // else {
    // throw new RuntimeException("You have no SMS");
    // }
    c.close();

    return lstSms;
}

Sms class is below:

public class Sms{
private String _id;
private String _address;
private String _msg;
private String _readState; //"0" for have not read sms and "1" for have read sms
private String _time;
private String _folderName;

public String getId(){
return _id;
}
public String getAddress(){
return _address;
}
public String getMsg(){
return _msg;
}
public String getReadState(){
return _readState;
}
public String getTime(){
return _time;
}
public String getFolderName(){
return _folderName;
}


public void setId(String id){
_id = id;
}
public void setAddress(String address){
_address = address;
}
public void setMsg(String msg){
_msg = msg;
}
public void setReadState(String readState){
_readState = readState;
}
public void setTime(String time){
_time = time;
}
public void setFolderName(String folderName){
_folderName = folderName;
}

}

Don't forget to define permission in your AndroidManifest.xml

<uses-permission android:name="android.permission.READ_SMS" />

Try catch statements in C

In C99, you can use setjmp/longjmp for non-local control flow.

Within a single scope, the generic, structured coding pattern for C in the presence of multiple resource allocations and multiple exits uses goto, like in this example. This is similar to how C++ implements destructor calls of automatic objects under the hood, and if you stick to this diligently, it should allow you for a certain degree of cleanness even in complex functions.

Python logging not outputting anything

Many years later there seems to still be a usability problem with the Python logger. Here's some explanations with examples:

import logging
# This sets the root logger to write to stdout (your console).
# Your script/app needs to call this somewhere at least once.
logging.basicConfig()

# By default the root logger is set to WARNING and all loggers you define
# inherit that value. Here we set the root logger to NOTSET. This logging
# level is automatically inherited by all existing and new sub-loggers
# that do not set a less verbose level.
logging.root.setLevel(logging.NOTSET)

# The following line sets the root logger level as well.
# It's equivalent to both previous statements combined:
logging.basicConfig(level=logging.NOTSET)


# You can either share the `logger` object between all your files or the
# name handle (here `my-app`) and call `logging.getLogger` with it.
# The result is the same.
handle = "my-app"
logger1 = logging.getLogger(handle)
logger2 = logging.getLogger(handle)
# logger1 and logger2 point to the same object:
# (logger1 is logger2) == True


# Convenient methods in order of verbosity from highest to lowest
logger.debug("this will get printed")
logger.info("this will get printed")
logger.warning("this will get printed")
logger.error("this will get printed")
logger.critical("this will get printed")


# In large applications where you would like more control over the logging,
# create sub-loggers from your main application logger.
component_logger = logger.getChild("component-a")
component_logger.info("this will get printed with the prefix `my-app.component-a`")

# If you wish to control the logging levels, you can set the level anywhere 
# in the hierarchy:
#
# - root
#   - my-app
#     - component-a
#

# Example for development:
logger.setLevel(logging.DEBUG)

# If that prints too much, enable debug printing only for your component:
component_logger.setLevel(logging.DEBUG)


# For production you rather want:
logger.setLevel(logging.WARNING)

A common source of confusion comes from a badly initialised root logger. Consider this:

import logging
log = logging.getLogger("myapp")
log.warning("woot")
logging.basicConfig()
log.warning("woot")

Output:

woot
WARNING:myapp:woot

Depending on your runtime environment and logging levels, the first log line (before basic config) might not show up anywhere.

how to add jquery in laravel project

To add jquery to laravel you first have to add the Scaffolded javascript file, app.js

This can easily be done adding this tag.

<script src="{{ asset('js/app.js') }}"></script>

There are two main procesess depending on the version but at the end of both you will have to execute:

npm run dev

That adds all the dependencies to the app.js file. But if you want this process to be done automatically for you, you can also run:

npm run watch

Wich will keep watching for changes and add them.

Version 5.*

jQuery is already included in this version of laravel as a dev dependency.

You just have to run:

npm install

This first command will install the dependencies. jquery will be added.

Version 6.* and 7*

jQuery has been taken out of laravel that means you need to import it manually.

I'll import it here as a development dependency:

npm i -D jquery

Then add it to the bootstrap.js file in resources/js/bootstrap.js You may notice that axios and lodash are imported there as well so in the same way we can import jquery.

Just add wherever you want there:

//In resources/js/bootstrap.js
window.$ = require('jquery');

If you follow this process in the 5.* version it won't affect laravel but it will install a more updated version of jquery.

unix sort descending order

To list files based on size in asending order.

find ./ -size +1000M -exec ls -tlrh {} \; |awk -F" " '{print $5,$9}'  | sort -n\

How to change UIPickerView height

As far as I know, it's impossible to shrink the UIPickerView. I also haven't actually seen a shorter one used anywhere. My guess is that it was a custom implementation if they did manage to shrink it.

How to loop through key/value object in Javascript?

Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty() method. This is generally a good idea when using for...in loops:

var user = {};

function setUsers(data) {
    for (var k in data) {
        if (data.hasOwnProperty(k)) {
           user[k] = data[k];
        }
    }
}

Amazon AWS Filezilla transfer permission denied

In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.

jquery how to use multiple ajax calls one after the end of the other

$(document).ready(function(){
 $('#category').change(function(){  
  $("#app").fadeOut();
$.ajax({
type: "POST",
url: "themes/ajax.php",
data: "cat="+$(this).val(),
cache: false,
success: function(msg)
    {
    $('#app').fadeIn().html(msg);
    $('#app').change(function(){    
    $("#store").fadeOut();
        $.ajax({
        type: "POST",
        url: "themes/ajax.php",
        data: "app="+$(this).val(),
        cache: false,
        success: function(ms)
            {
            $('#store').fadeIn().html(ms);

            }
            });// second ajAx
        });// second on change


     }// first  ajAx sucess
  });// firs ajAx
 });// firs on change

});

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

s = "I     am having  a   very  nice  23!@$      day. "
sum([i.strip(string.punctuation).isalpha() for i in s.split()])

The statement above will go through each chunk of text and remove punctuations before verifying if the chunk is really string of alphabets.

When should I use cross apply over inner join?

This is perhaps an old question, but I still love the power of CROSS APPLY to simplify the re-use of logic and to provide a "chaining" mechanism for results.

I've provided a SQL Fiddle below which shows a simple example of how you can use CROSS APPLY to perform complex logical operations on your data set without things getting at all messy. It's not hard to extrapolate from here more complex calculations.

http://sqlfiddle.com/#!3/23862/2

Please initialize the log4j system properly warning

Alright, so I got it working by changing this

log4j.rootLogger=DebugAppender

to this

log4j.rootLogger=DEBUG, DebugAppender

Apparently you have to specify the logging level to the rootLogger first? I apologize if I wasted anyone's time.

Also, I decided to answer my own question because this wasn't a classpath issue.

Splitting a string into separate variables

An array is created with the -split operator. Like so,

$myString="Four score and seven years ago"
$arr = $myString -split ' '
$arr # Print output
Four
score
and
seven
years
ago

When you need a certain item, use array index to reach it. Mind that index starts from zero. Like so,

$arr[2] # 3rd element
and
$arr[4] # 5th element
years

How to evaluate http response codes from bash/shell script?

curl --write-out "%{http_code}\n" --silent --output /dev/null "$URL"

works. If not, you have to hit return to view the code itself.

LaTeX table positioning

You may want to add this to your preamble, and adjust the values as necessary:

 %------------begin Float Adjustment
%two column float page must be 90% full
\renewcommand\dblfloatpagefraction{.90}
%two column top float can cover up to 80% of page
\renewcommand\dbltopfraction{.80}
%float page must be 90% full
\renewcommand\floatpagefraction{.90}
%top float can cover up to 80% of page
\renewcommand\topfraction{.80}
%bottom float can cover up to 80% of page
\renewcommand\bottomfraction{.80}
%at least 10% of a normal page must contain text
\renewcommand\textfraction{.1}
%separation between floats and text
\setlength\dbltextfloatsep{9pt plus 5pt minus 3pt }
%separation between two column floats and text
\setlength\textfloatsep{4pt plus 2pt minus 1.5pt}

Particularly, the \floatpagefraction may be of interest.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Turns out that the problem was with face that the script was running from a cPanel "email piped to script", so was running as the user, so is was a user problem, but was not affecting the web server at all.

The cause for the user not being able to access the /etc/pki directory was due to them only having jailed ssh access. Once I granted full access, it all worked fine.

Thanks for the info though, Remi.

Cannot use string offset as an array in php

I just want to explain my solving for the same problem.

my code before(given same error):

$arr2= ""; // this is the problem and solve by replace this $arr2 = array();
for($i=2;$i<count($arrdata);$i++){
    $rowx = explode(" ",$arrdata[$i]);
    $arr1= ""; // and this is too
    for($x=0;$x<count($rowx);$x++){
        if($rowx[$x]!=""){
            $arr1[] = $rowx[$x];
        }
    }
    $arr2[] = $arr1;
}
for($i=0;$i<count($arr2);$i++){
    $td .="<tr>";
    for($j=0;$j<count($hcol)-1;$j++){
        $td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>"; //and it's($arr2[$i][$j]) give an error: Cannot use string offset as an array
    }
    $td .="</tr>";
}

my code after and solved it:

$arr2= array(); //change this from $arr2="";
for($i=2;$i<count($arrdata);$i++){
    $rowx = explode(" ",$arrdata[$i]);
    $arr1=array(); //and this
    for($x=0;$x<count($rowx);$x++){
        if($rowx[$x]!=""){
            $arr1[] = $rowx[$x];
        }
    }
    $arr2[] = $arr1;
}
for($i=0;$i<count($arr2);$i++){
    $td .="<tr>";
    for($j=0;$j<count($hcol)-1;$j++){
        $td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>";
    }
    $td .="</tr>";
}

Thank's. Hope it's helped, and sorry if my english mess like boy's room :D

What does it mean to bind a multicast (UDP) socket?

Correction for What does it mean to bind a multicast (udp) socket? as long as it partially true at the following quote:

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application

There is one exception. Multiple applications can share the same port for listening (usually it has practical value for multicast datagrams), if the SO_REUSEADDR option applied. For example

int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // create UDP socket somehow
...
int set_option_on = 1;
// it is important to do "reuse address" before bind, not after
int res = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, 
    sizeof(set_option_on));
res = bind(sock, src_addr, len);

If several processes did such "reuse binding", then every UDP datagram received on that shared port will be delivered to each of the processes (providing natural joint with multicasts traffic).

Here are further details regarding what happens in a few cases:

  1. attempt of any bind ("exclusive" or "reuse") to free port will be successful

  2. attempt to "exclusive binding" will fail if the port is already "reuse-binded"

  3. attempt to "reuse binding" will fail if some process keeps "exclusive binding"

How to use PHP to connect to sql server

for further investigation: print out the mssql error message:

$dbhandle = mssql_connect($myServer, $myUser, $myPass) or die("Could not connect to database: ".mssql_get_last_message()); 

It is also important to specify the port: On MS SQL Server 2000, separate it with a comma:

$myServer = "10.85.80.229:1443";

or

$myServer = "10.85.80.229,1443";

How to use pull to refresh in Swift?

I suggest to make an Extension of pull To Refresh to use in every class.

1) Make an empty swift file : File - New - File - Swift File.

2) Add the Following

    //  AppExtensions.swift

    import Foundation
    import UIKit    

    var tableRefreshControl:UIRefreshControl = UIRefreshControl()    

    //MARK:- VIEWCONTROLLER EXTENSION METHODS
    public extension UIViewController
    {
        func makePullToRefreshToTableView(tableName: UITableView,triggerToMethodName: String){

            tableRefreshControl.attributedTitle = NSAttributedString(string: "TEST: Pull to refresh")
            tableRefreshControl.backgroundColor = UIColor.whiteColor()
            tableRefreshControl.addTarget(self, action: Selector(triggerToMethodName), forControlEvents: UIControlEvents.ValueChanged)
            tableName.addSubview(tableRefreshControl)
        }
        func makePullToRefreshEndRefreshing (tableName: String)
        {
            tableRefreshControl.endRefreshing()
//additional codes

        }
    }    

3) In Your View Controller call these methods as :

  override func viewWillAppear(animated: Bool) {

self.makePullToRefreshToTableView(bidderListTable, triggerToMethodName: "pullToRefreshBidderTable")
}

4) At some point you wanted to end refreshing:

  func pullToRefreshBidderTable() {
self.makePullToRefreshEndRefreshing("bidderListTable")    
//Code What to do here.
}
OR    
self.makePullToRefreshEndRefreshing("bidderListTable")

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

How to call a SOAP web service on Android

SOAP is an ill-suited technology for use on Android (or mobile devices in general) because of the processing/parsing overhead that's required. A REST services is a lighter weight solution and that's what I would suggest. Android comes with a SAX parser, and it's fairly trivial to use. If you are absolutely required to handle/parse SOAP on a mobile device then I feel sorry for you, the best advice I can offer is just not to use SOAP.

R: invalid multibyte string

If you want an R solution, here's a small convenience function I sometimes use to find where the offending (multiByte) character is lurking. Note that it is the next character to what gets printed. This works because print will work fine, but substr throws an error when multibyte characters are present.

find_offending_character <- function(x, maxStringLength=256){  
  print(x)
  for (c in 1:maxStringLength){
    offendingChar <- substr(x,c,c)
    #print(offendingChar) #uncomment if you want the indiv characters printed
    #the next character is the offending multibyte Character
  }    
}

string_vector <- c("test", "Se\x96ora", "works fine")

lapply(string_vector, find_offending_character)

I fix that character and run this again. Hope that helps someone who encounters the invalid multibyte string error.

AngularJS ng-style with a conditional expression

simple example:

<div ng-style="isTrue && {'background-color':'green'} || {'background-color': 'blue'}" style="width:200px;height:100px;border:1px solid gray;"></div>

{'background-color':'green'} RETURN true

OR the same result:

<div ng-style="isTrue && {'background-color':'green'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

other conditional possibility:

<div ng-style="count === 0 && {'background-color':'green'}  || count === 1 && {'background-color':'yellow'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

Calling UserForm_Initialize() in a Module

From a module:

UserFormName.UserForm_Initialize

Just make sure that in your userform, you update the sub like so:

Public Sub UserForm_Initialize() so it can be called from outside the form.

Alternately, if the Userform hasn't been loaded:

UserFormName.Show will end up calling UserForm_Initialize because it loads the form.

fatal error: iostream.h no such file or directory

You should be using iostream without the .h.

Early implementations used the .h variants but the standard mandates the more modern style.

List comprehension vs map

I find list comprehensions are generally more expressive of what I'm trying to do than map - they both get it done, but the former saves the mental load of trying to understand what could be a complex lambda expression.

There's also an interview out there somewhere (I can't find it offhand) where Guido lists lambdas and the functional functions as the thing he most regrets about accepting into Python, so you could make the argument that they're un-Pythonic by virtue of that.

URL Encoding using C#

Since .NET Framework 4.5 and .NET Standard 1.0 you should use WebUtility.UrlEncode. Advantages over alternatives:

  1. It is part of .NET Framework 4.5+, .NET Core 1.0+, .NET Standard 1.0+, UWP 10.0+ and all Xamarin platforms as well. HttpUtility, while being available in .NET Framework earlier (.NET Framework 1.1+), becomes available on other platforms much later (.NET Core 2.0+, .NET Standard 2.0+) and it still unavailable in UWP (see related question).

  2. In .NET Framework, it resides in System.dll, so it does not require any additional references, unlike HttpUtility.

  3. It properly escapes characters for URLs, unlike Uri.EscapeUriString (see comments to drweb86's answer).

  4. It does not have any limits on the length of the string, unlike Uri.EscapeDataString (see related question), so it can be used for POST requests, for example.