Programs & Examples On #Cssedit

CCSEdit is a program for web design totally focused on editing CSS owned by MacRabbit.

How to make php display \t \n as tab and new line instead of characters

Put it in double quotes:

echo "\t";

Single quotes do not expand escaped characters.

Use the documentation when in doubt.

How to copy directory recursively in python and overwrite all?

In Python 3.8 the dirs_exist_ok keyword argument was added to shutil.copytree():

dirs_exist_ok dictates whether to raise an exception in case dst or any missing parent directory already exists.

So, the following will work in recent versions of Python, even if the destination directory already exists:

shutil.copytree(src, dest, dirs_exist_ok=True)  # 3.8+ only!

One major benefit is that it's more flexible than distutils.dir_util.copy_tree() as it takes additional arguments on files to ignore, etc. There is also a draft PEP (PEP 632, associated discussion), which suggests that distutils may be deprecated and then removed in future versions of Python 3.

Java Comparator class to sort arrays

The answer from @aioobe is excellent. I just want to add another way for Java 8.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };

Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);

System.out.println(Arrays.deepToString(twoDim));

For me it's intuitive and easy to remember with Java 8 syntax.

How to change an Eclipse default project into a Java project

Open the .project file and add java nature and builders.

<projectDescription>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>

And in .classpath, reference the Java libs:

<classpath>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>

Moving x-axis to the top of a plot in matplotlib

tick_params is very useful for setting tick properties. Labels can be moved to the top with:

    ax.tick_params(labelbottom=False,labeltop=True)

Differences between contentType and dataType in jQuery ajax function

enter image description here

In English:

  • ContentType: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8, which is fine for most cases.
  • Accepts: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType.
  • DataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp.

Access an arbitrary element in a dictionary in Python

In python3, The way :

dict.keys() 

return a value in type : dict_keys(), we'll got an error when got 1st member of keys of dict by this way:

dict.keys()[0]
TypeError: 'dict_keys' object does not support indexing

Finally, I convert dict.keys() to list @1st, and got 1st member by list splice method:

list(dict.keys())[0]

Streaming Audio from A URL in Android using MediaPlayer?

I've had the same error as you have and it turned out that there was nothing wrong with the code. The problem was that the webserver was sending the wrong Content-Type header.

Try wireshark or something similar to see what content-type the webserver is sending.

How to create a numeric vector of zero length in R

Suppose you want to create a vector x whose length is zero. Now let v be any vector.

> v<-c(4,7,8)
> v
[1] 4 7 8
> x<-v[0]
> length(x)
[1] 0

Remove last characters from a string in C#. An elegant way?

You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.

string var = var.Substring(0, var.LastIndexOf(','));

PostgreSQL : cast string to date DD/MM/YYYY

In case you need to convert the returned date of a select statement to a specific format you may use the following:

select to_char(DATE (*date_you_want_to_select*)::date, 'DD/MM/YYYY') as "Formated Date"

Change value of input and submit form in JavaScript

No. When your input type is submit, you should have an onsubmit event declared in the markup and then do the changes you want. Meaning, have an onsubmit defined in your form tag.

Otherwise change the input type to a button and then define an onclick event for that button.

How to make a new List in Java

If you need a serializable, immutable list with a single entity you can use:

List<String> singList = Collections.singletonList("stackoverlow");

Pass entire form as data in jQuery Ajax function

You just have to post the data. and Using jquery ajax function set parameters. Here is an example.

<script>
        $(function () {

            $('form').on('submit', function (e) {

                e.preventDefault();

                $.ajax({
                    type: 'post',
                    url: 'your_complete url',
                    data: $('form').serialize(),
                    success: function (response) {
                        //$('form')[0].reset();
                       // $("#feedback").text(response);
                        if(response=="True") {
                            $('form')[0].reset();
                            $("#feedback").text("Your information has been stored.");
                        }
                        else
                            $("#feedback").text(" Some Error has occured Errror !!! ID duplicate");
                    }
                });

            });

        });
    </script>

How to remove extension from string (only real extension!)

The following code works well for me, and it's pretty short. It just breaks the file up into an array delimited by dots, deletes the last element (which is hypothetically the extension), and reforms the array with the dots again.

$filebroken = explode( '.', $filename);
$extension = array_pop($filebroken);
$fileTypeless = implode('.', $filebroken);

Add and remove attribute with jquery

Once you remove the ID "page_navigation" that element no longer has an ID and so cannot be found when you attempt to access it a second time.

The solution is to cache a reference to the element:

$(document).ready(function(){
    // This reference remains available to the following functions
    // even when the ID is removed.
    var page_navigation = $("#page_navigation1");

    $("#add").click(function(){
        page_navigation.attr("id","page_navigation1");
    });     

    $("#remove").click(function(){
        page_navigation.removeAttr("id");
    });     
});

How to change JFrame icon

This did the trick in my case super or this referes to JFrame in my class

URL url = getClass().getResource("gfx/hi_20px.png");
ImageIcon imgicon = new ImageIcon(url);
super.setIconImage(imgicon.getImage());

How do I empty an input value with jQuery?

$('.reset').on('click',function(){
           $('#upload input, #upload select').each(
                function(index){  
                    var input = $(this);
                    if(input.attr('type')=='text'){
                        document.getElementById(input.attr('id')).value = null;
                    }else if(input.attr('type')=='checkbox'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else if(input.attr('type')=='radio'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else{
                        document.getElementById(input.attr('id')).value = '';
                        //alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());
                    }
                }
            );
        });

Make a div into a link

Came here in the hope of finding a better solution that mine, but I don't like any of the ones on offer here. I think some of you have misunderstood the question. The OP wants to make a div full of content behave like a link. One example of this would be facebook ads - if you look, they're actually proper markup.

For me the no-nos are: javascript (shouldn't be needed just for a link, and very bad SEO/accessibility); invalid HTML.

In essence it's this:

  • Build your panel using normal CSS techniques and valid HTML.
  • Somewhere in there put a link that you want to be the default link if the user clicks on the panel (you can have other links too).
  • Inside that link, put an empty span tag (<span></span>, not <span /> - thanks @Campey)
  • give the panel position:relative
  • apply the following CSS to the empty span:

    { 
      position:absolute; 
      width:100%;
      height:100%;
      top:0;
      left: 0;
    
      z-index: 1;
    
      /* fixes overlap error in IE7/8, 
         make sure you have an empty gif */
      background-image: url('empty.gif');
    }   
    

    It will now cover the panel, and as it's inside an <A> tag, it's a clickable link

  • give any other links inside the panel position:relative and a suitable z-index (>1) to bring them in front of the default span link

Iterate keys in a C++ map

With C++11 the iteration syntax is simple. You still iterate over pairs, but accessing just the key is easy.

#include <iostream>
#include <map>

int main()
{
    std::map<std::string, int> myMap;

    myMap["one"] = 1;
    myMap["two"] = 2;
    myMap["three"] = 3;

    for ( const auto &myPair : myMap ) {
        std::cout << myPair.first << "\n";
    }
}

not:first-child selector

This CSS2 solution ("any ul after another ul") works, too, and is supported by more browsers.

div ul + ul {
  background-color: #900;
}

Unlike :not and :nth-sibling, the adjacent sibling selector is supported by IE7+.

If you have JavaScript changes these properties after the page loads, you should look at some known bugs in the IE7 and IE8 implementations of this. See this link.

For any static web page, this should work perfectly.

Extracting a parameter from a URL in WordPress

Why not just use the WordPress get_query_var() function? WordPress Code Reference

// Test if the query exists at the URL
if ( get_query_var('ppc') ) {

    // If so echo the value
    echo get_query_var('ppc');

}

Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php by adding an action during initialization:

add_action('init','add_get_val');
function add_get_val() { 
    global $wp; 
    $wp->add_query_var('ppc'); 
}

Or by adding a hook to the query_vars filter:

function add_query_vars_filter( $vars ){
  $vars[] = "ppc";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

Tokenizing strings in C

Here is another strtok() implementation, which has the ability to recognize consecutive delimiters (standard library's strtok() does not have this)

The function is a part of BSD licensed string library, called zString. You are more than welcome to contribute :)

https://github.com/fnoyanisi/zString

char *zstring_strtok(char *str, const char *delim) {
    static char *static_str=0;      /* var to store last address */
    int index=0, strlength=0;       /* integers for indexes */
    int found = 0;                  /* check if delim is found */

    /* delimiter cannot be NULL
    * if no more char left, return NULL as well
    */
    if (delim==0 || (str == 0 && static_str == 0))
        return 0;

    if (str == 0)
        str = static_str;

    /* get length of string */
    while(str[strlength])
        strlength++;

    /* find the first occurance of delim */
    for (index=0;index<strlength;index++)
        if (str[index]==delim[0]) {
            found=1;
            break;
        }

    /* if delim is not contained in str, return str */
    if (!found) {
        static_str = 0;
        return str;
    }

    /* check for consecutive delimiters
    *if first char is delim, return delim
    */
    if (str[0]==delim[0]) {
        static_str = (str + 1);
        return (char *)delim;
    }

    /* terminate the string
    * this assignmetn requires char[], so str has to
    * be char[] rather than *char
    */
    str[index] = '\0';

    /* save the rest of the string */
    if ((str + index + 1)!=0)
        static_str = (str + index + 1);
    else
        static_str = 0;

        return str;
}

As mentioned in previous posts, since strtok(), or the one I implmented above, relies on a static *char variable to preserve the location of last delimiter between consecutive calls, extra care should be taken while dealing with multi-threaded aplications.

Can constructors throw exceptions in Java?

Yes, constructors are allowed to throw exceptions.

However, be very wise in choosing what exceptions they should be - checked exceptions or unchecked. Unchecked exceptions are basically subclasses of RuntimeException.

In almost all cases (I could not come up with an exception to this case), you'll need to throw a checked exception. The reason being that unchecked exceptions (like NullPointerException) are normally due to programming errors (like not validating inputs sufficiently).

The advantage that a checked exception offers is that the programmer is forced to catch the exception in his instantiation code, and thereby realizes that there can be a failure to create the object instance. Of course, only a code review will catch the poor programming practice of swallowing an exception.

passing object by reference in C++

Passing by reference in the above case is just an alias for the actual object.

You'll be referring to the actual object just with a different name.

There are many advantages which references offer compared to pointer references.

Radio button validation in javascript

You could do something like this

var option=document.getElementsByName('Gender');

if (!(option[0].checked || option[1].checked)) {
    alert("Please Select Your Gender");
    return false;
}

How to create materialized views in SQL Server?

For MS T-SQL Server, I suggest looking into creating an index with the "include" statement. Uniqueness is not required, neither is the physical sorting of data associated with a clustered index. The "Index ... Include ()" creates a separate physical data storage automatically maintained by the system. It is conceptually very similar to an Oracle Materialized View.

https://msdn.microsoft.com/en-us/library/ms190806.aspx

https://technet.microsoft.com/en-us/library/ms189607(v=sql.105).aspx

How to rename with prefix/suffix?

Bulk rename files bash script

#!/bin/bash
# USAGE: cd FILESDIRECTORY; RENAMERFILEPATH/MultipleFileRenamer.sh FILENAMEPREFIX INITNUMBER
# USAGE EXAMPLE: cd PHOTOS; /home/Desktop/MultipleFileRenamer.sh 2016_
# VERSION: 2016.03.05.
# COPYRIGHT: Harkály Gergo | mangoRDI (https://wwww.mangordi.com/) 

# check isset INITNUMBER argument, if not, set 1 | INITNUMBER is the first number after renaming
if [ -z "$2" ]
    then i=1;
else
    i=$2;
fi

# counts the files to set leading zeros before number | max 1000 files
count=$(ls -l * | wc -l)
if [ $count -lt 10 ]
    then zeros=1;
else
    if [ $count -lt 100 ]
        then zeros=2;
    else
        zeros=3
    fi
fi

# rename script
for file in *
do
    mv $file $1_$(printf %0"$zeros"d.%s ${i%.*} ${file##*.})
    let i="$i+1"
done

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

You can try ES6 Modules in Google Chrome Beta (61) / Chrome Canary.

Reference Implementation of ToDo MVC by Paul Irish - https://paulirish.github.io/es-modules-todomvc/

I've basic demo -

//app.js
import {sum} from './calc.js'

console.log(sum(2,3));
//calc.js
let sum = (a,b) => { return a + b; }

export {sum};
<html> 
    <head>
        <meta charset="utf-8" />
    </head>

    <body>
        <h1>ES6</h1>
        <script src="app.js" type="module"></script>
    </body>

</html>

Hope it helps!

How to update/upgrade a package using pip?

import subprocess as sbp
import pip
pkgs = eval(str(sbp.run("pip3 list -o --format=json", shell=True,
                         stdout=sbp.PIPE).stdout, encoding='utf-8'))
for pkg in pkgs:
    sbp.run("pip3 install --upgrade " + pkg['name'], shell=True)

Save as xx.py
Then run Python3 xx.py
Environment: python3.5+ pip10.0+

Writing a Python list of lists to a csv file

You could use pandas:

In [1]: import pandas as pd

In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]

In [3]: my_df = pd.DataFrame(a)

In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)

specifying goal in pom.xml

  1. Go to Terminal
  2. Do mvn clean install

Better way to find control in ASP.NET

If you're looking for a specific type of control you could use a recursive loop like this one - http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx

Here's an example I made that returns all controls of the given type

/// <summary>
/// Finds all controls of type T stores them in FoundControls
/// </summary>
/// <typeparam name="T"></typeparam>
private class ControlFinder<T> where T : Control 
{
    private readonly List<T> _foundControls = new List<T>();
    public IEnumerable<T> FoundControls
    {
        get { return _foundControls; }
    }    

    public void FindChildControlsRecursive(Control control)
    {
        foreach (Control childControl in control.Controls)
        {
            if (childControl.GetType() == typeof(T))
            {
                _foundControls.Add((T)childControl);
            }
            else
            {
                FindChildControlsRecursive(childControl);
            }
        }
    }
}

CodeIgniter - return only one row?

To add on to what Alisson said you could check to see if a row is returned.

// Query stuff ...
$query = $this->db->get();

if ($query->num_rows() > 0)
{
    $row = $query->row(); 
    return $row->campaign_id;
}

return null; // or whatever value you want to return for no rows found

How to set the JSTL variable value in javascript?

You can save the whole jstl object as a Javascript object by converting the whole object to json. It is possible by Jackson in java.

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil{
   public static String toJsonString(Object obj){
      ObjectMapper objectMapper = ...; // jackson object mapper
      return objectMapper.writeValueAsString(obj);
   }
}

/WEB-INF/tags/util-functions.tld:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" 
  version="2.1"> 

  <tlib-version>1.0</tlib-version>
  <uri>http://www.your.url/util-functions</uri>

  <function>
      <name>toJsonString</name>
      <function-class>your.package.JsonUtil</function-class>
      <function-signature>java.lang.String toJsonString(java.lang.Object)</function-signature>
  </function>  

</taglib> 

web.xml

<jsp-config>
  <tablib>
    <taglib-uri>http://www.your.url/util-functions</taglib-uri>
    <taglib-location>/WEB-INF/tags/util-functions.tld</taglib-location>
  </taglib>
</jsp-confi>

mypage.jsp:

<%@ taglib prefix="uf" uri="http://www.your.url/util-functions" %> 

<script>
   var myJavaScriptObject = JSON.parse('${uf:toJsonString(myJstlObject)}');
</script>

Center icon in a div - horizontally and vertically

Horizontal centering is as easy as:

text-align: center

Vertical centering when the container is a known height:

height: 100px;
line-height: 100px;
vertical-align: middle

Vertical centering when the container isn't a known height AND you can set the image in the background:

background: url(someimage) no-repeat center center;

jquery datatables hide column

You can try as below to hide/show dynamically runtime

Hide : fnSetColumnVis( 1, false, false );

Example: oTable.fnSetColumnVis(item, false,false);

Show : fnSetColumnVis( 1, true, false );

Example: oTable.fnSetColumnVis(item, false,false);

Here, oTable is object of Datatable.

How to make an android app to always run in background?

In mi and vivo - Using the above solution is not enough. You must also tell the user to add permission manually. You can help them by opening the right location inside phone settings. Varies for different phone models.

Passing arguments to angularjs filters

Actually there is another (maybe better solution) where you can use the angular's native 'filter' filter and still pass arguments to your custom filter.

Consider the following code:

<div ng-repeat="group in groups">
    <li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
        <span>{{friend.name}}</span>
    <li>
</div>

To make this work you just define your filter as the following:

$scope.weDontLike = function(name) {
    return function(friend) {
        return friend.name != name;
    }
}

As you can see here, weDontLike actually returns another function which has your parameter in its scope as well as the original item coming from the filter.

It took me 2 days to realise you can do this, haven't seen this solution anywhere yet.

Checkout Reverse polarity of an angular.js filter to see how you can use this for other useful operations with filter.

Get a list of resources from classpath directory

I think you can leverage the [Zip File System Provider][1] to achieve this. When using FileSystems.newFileSystem it looks like you can treat the objects in that ZIP as a "regular" file.

In the linked documentation above:

Specify the configuration options for the zip file system in the java.util.Map object passed to the FileSystems.newFileSystem method. See the [Zip File System Properties][2] topic for information about the provider-specific configuration properties for the zip file system.

Once you have an instance of a zip file system, you can invoke the methods of the [java.nio.file.FileSystem][3] and [java.nio.file.Path][4] classes to perform operations such as copying, moving, and renaming files, as well as modifying file attributes.

The documentation for the jdk.zipfs module in [Java 11 states][5]:

The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider can be created by [FileSystems.newFileSystem][6] if installed.

Here is a contrived example I did using your example resources. Note that a .zip is a .jar, but you could adapt your code to instead use classpath resources:

Setup

cd /tmp
mkdir -p x/y/z
touch x/y/z/{a,b,c}.html
echo 'hello world' > x/y/z/d
zip -r example.zip x

Java

import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Collections;
import java.util.stream.Collectors;

public class MkobitZipRead {

  public static void main(String[] args) throws IOException {
    final URI uri = URI.create("jar:file:/tmp/example.zip");
    try (
        final FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.emptyMap());
    ) {
      Files.walk(zipfs.getPath("/")).forEach(path -> System.out.println("Files in zip:" + path));
      System.out.println("-----");
      final String manifest = Files.readAllLines(
          zipfs.getPath("x", "y", "z").resolve("d")
      ).stream().collect(Collectors.joining(System.lineSeparator()));
      System.out.println(manifest);
    }
  }

}

Output

Files in zip:/
Files in zip:/x/
Files in zip:/x/y/
Files in zip:/x/y/z/
Files in zip:/x/y/z/c.html
Files in zip:/x/y/z/b.html
Files in zip:/x/y/z/a.html
Files in zip:/x/y/z/d
-----
hello world

How to clone ArrayList and also clone its contents?

The package import org.apache.commons.lang.SerializationUtils;

There is a method SerializationUtils.clone(Object);

Example

this.myObjectCloned = SerializationUtils.clone(this.object);

In laymans terms, what does 'static' mean in Java?

In addition to what @inkedmn has pointed out, a static member is at the class level. Therefore, the said member is loaded into memory by the JVM once for that class (when the class is loaded). That is, there aren't n instances of a static member loaded for n instances of the class to which it belongs.

-bash: export: `=': not a valid identifier

I faced the same error and did some research to only see that there could be different scenarios to this error. Let me share my findings.

Scenario 1: There cannot be spaces beside the = (equals) sign

$ export TEMP_ENV = example-value
-bash: export: `=': not a valid identifier
// this is the answer to the question

$ export TEMP_ENV =example-value
-bash: export: `=example-value': not a valid identifier

$ export TEMP_ENV= example-value
-bash: export: `example-value': not a valid identifier

Scenario 2: Object value assignment should not have spaces besides quotes

$ export TEMP_ENV={ "key" : "json example" } 
-bash: export: `:': not a valid identifier
-bash: export: `json example': not a valid identifier
-bash: export: `}': not a valid identifier

Scenario 3: List value assignment should not have spaces between values

$ export TEMP_ENV=[1,2 ,3 ]
-bash: export: `,3': not a valid identifier
-bash: export: `]': not a valid identifier

I'm sharing these, because I was stuck for a couple of hours trying to figure out a workaround. Hopefully, it will help someone in need.

How to watch for a route change in AngularJS?

$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //if you want to interrupt going to another location.
  event.preventDefault();  });

HttpContext.Current.User.Identity.Name is Empty

I also had this problem recently. Working with a new client, trying to get a an old web forms app running from Visual Studio, with IISExpress using Windows Authentication. For me, the web.config was correctly configured

However, the IISExpress.config settings file had:

<windowsAuthentication enabled="false">

The user account the developer was logged in was very new, so unlikely it had been edited. Simple fix it turned out, change this to enabled=true and it all ran as it should then.

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

UDP vs TCP, how much faster is it?

It is meaningless to talk about TCP or UDP without taking the network condition into account. If the network between the two point have a very high quality, UDP is absolutely faster than TCP, but in some other case such as the GPRS network, TCP may been faster and more reliability than UDP.

Using C# to check if string contains a string in string array

If stringArray contains a large number of varied length strings, consider using a Trie to store and search the string array.

public static class Extensions
{
    public static bool ContainsAny(this string stringToCheck, IEnumerable<string> stringArray)
    {
        Trie trie = new Trie(stringArray);
        for (int i = 0; i < stringToCheck.Length; ++i)
        {
            if (trie.MatchesPrefix(stringToCheck.Substring(i)))
            {
                return true;
            }
        }

        return false;
    }
}

Here is the implementation of the Trie class

public class Trie
{
    public Trie(IEnumerable<string> words)
    {
        Root = new Node { Letter = '\0' };
        foreach (string word in words)
        {
            this.Insert(word);
        }
    }

    public bool MatchesPrefix(string sentence)
    {
        if (sentence == null)
        {
            return false;
        }

        Node current = Root;
        foreach (char letter in sentence)
        {
            if (current.Links.ContainsKey(letter))
            {
                current = current.Links[letter];
                if (current.IsWord)
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }

        return false;
    }

    private void Insert(string word)
    {
        if (word == null)
        {
            throw new ArgumentNullException();
        }

        Node current = Root;
        foreach (char letter in word)
        {
            if (current.Links.ContainsKey(letter))
            {
                current = current.Links[letter];
            }
            else
            {
                Node newNode = new Node { Letter = letter };
                current.Links.Add(letter, newNode);
                current = newNode;
            }
        }

        current.IsWord = true;
    }

    private class Node
    {
        public char Letter;
        public SortedList<char, Node> Links = new SortedList<char, Node>();
        public bool IsWord;
    }

    private Node Root;
}

If all strings in stringArray have the same length, you will be better off just using a HashSet instead of a Trie

public static bool ContainsAny(this string stringToCheck, IEnumerable<string> stringArray)
{
    int stringLength = stringArray.First().Length;
    HashSet<string> stringSet = new HashSet<string>(stringArray);
    for (int i = 0; i < stringToCheck.Length - stringLength; ++i)
    {
        if (stringSet.Contains(stringToCheck.Substring(i, stringLength)))
        {
            return true;
        }
    }

    return false;
}

Update some specific field of an entity in android Room

According to SQLite Update Docs :

<!-- language: lang-java -->
@Query("UPDATE tableName SET 
    field1 = :value1,
    field2 = :value2, 
    ...
    //some more fields to update
    ...
    field_N= :value_N
    WHERE id = :id)

int updateTour(long id, 
               Type value1, 
               Type value2, 
               ... ,
               // some more values here
               ... ,
               Type value_N);

Example:

Entity:

@Entity(tableName = "orders")
public class Order {

@NonNull
@PrimaryKey
@ColumnInfo(name = "order_id")
private int id;

@ColumnInfo(name = "order_title")
private String title;

@ColumnInfo(name = "order_amount")
private Float amount;

@ColumnInfo(name = "order_price")
private Float price;

@ColumnInfo(name = "order_desc")
private String description;

// ... methods, getters, setters
}

Dao:

@Dao
public interface OrderDao {

@Query("SELECT * FROM orders")
List<Order> getOrderList();

@Query("SELECT * FROM orders")
LiveData<List<Order>> getOrderLiveList();

@Query("SELECT * FROM orders WHERE order_id =:orderId")
LiveData<Order> getLiveOrderById(int orderId);

/**
* Updating only price
* By order id
*/
@Query("UPDATE orders SET order_price=:price WHERE order_id = :id")
void update(Float price, int id);

/**
* Updating only amount and price
* By order id
*/
@Query("UPDATE orders SET order_amount = :amount, price = :price WHERE order_id =:id")
void update(Float amount, Float price, int id);

/**
* Updating only title and description
* By order id
*/
@Query("UPDATE orders SET order_desc = :description, order_title= :title WHERE order_id =:id")
void update(String description, String title, int id);

@Update
void update(Order order);

@Delete
void delete(Order order);

@Insert(onConflict = REPLACE)
void insert(Order order);
}

Copy from one workbook and paste into another

You copied using Cells.
If so, no need to PasteSpecial since you are copying data at exactly the same format.
Here's your code with some fixes.

Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet

Set x = Workbooks.Open("path to copying book")
Set y = Workbooks.Open("path to pasting book")

Set ws1 = x.Sheets("Sheet you want to copy from")
Set ws2 = y.Sheets("Sheet you want to copy to")

ws1.Cells.Copy ws2.cells
y.Close True
x.Close False

If however you really want to paste special, use a dynamic Range("Address") to copy from.
Like this:

ws1.Range("Address").Copy: ws2.Range("A1").PasteSpecial xlPasteValues
y.Close True
x.Close False

Take note of the : colon after the .Copy which is a Statement Separating character.
Using Object.PasteSpecial requires to be executed in a new line.
Hope this gets you going.

Hide horizontal scrollbar on an iframe?

I'd suggest doing this with a combination of

  1. CSS overflow-y: hidden;
  2. scrolling="no" (for HTML4)
  3. and seamless="seamless" (for HTML5)*

* The seamless attribute has been removed from the standard, and no browsers support it.


_x000D_
_x000D_
.foo {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  overflow-y: hidden;_x000D_
}
_x000D_
<iframe src="https://bing.com" _x000D_
        class="foo" _x000D_
        scrolling="no" >_x000D_
</iframe>
_x000D_
_x000D_
_x000D_

UnicodeEncodeError: 'charmap' codec can't encode characters

I fixed it by adding .encode("utf-8") to soup.

That means that print(soup) becomes print(soup.encode("utf-8")).

Can't install nuget package because of "Failed to initialize the PowerShell host"

This started happening with 6.0.4 recently for me, I don't think this is a very good solution but here is what helped me. Close Visual Studio

  1. Open a Windows PowerShell prompt as Administrator (very important) and run the following command:Set-ExecutionPolicy Bypass
  2. Open Visual Studio, open your solution and use Nuget to install JSON.Net (or whatever package included it as a dependency).
  3. Once everything is working, I recommend setting the powershell execution policy back to restricted with the following command: Set-ExecutionPolicy Restricted

How to install package from github repo in Yarn

I use this short format for github repositories:

yarn add github_user/repository_name#commit_hash

Difference between onStart() and onResume()

The book "Hello, Android, Introducing Google's Mobile Development Platform" gives a nice explanation of the life cycle of android apps. Luckily they have the particular chapter online as an excerpt. See the graphic on page 39 in http://media.pragprog.com/titles/eband3/concepts.pdf

By the way, this book is highly recommendable for android beginners!

Simple way to create matrix of random numbers

x = np.int_(np.random.rand(10) * 10)

For random numbers out of 10. For out of 20 we have to multiply by 20.

How do I make CMake output into a 'bin' dir?

As to me I am using cmake 3.5, the below(set variable) does not work:

set(
      ARCHIVE_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
      LIBRARY_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
      RUNTIME_OUTPUT_DIRECTORY "/home/xy/cmake_practice/bin/"
)

but this works(set set_target_properties):

set_target_properties(demo5
    PROPERTIES
    ARCHIVE_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
    LIBRARY_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
    RUNTIME_OUTPUT_DIRECTORY "/home/xy/cmake_practice/bin/"
)

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

Regex for quoted string with escaping quotes

If your IDE is IntelliJ Idea, you can forget all these headaches and store your regex into a String variable and as you copy-paste it inside the double-quote it will automatically change to a regex acceptable format.

example in Java:

String s = "\"en_usa\":[^\\,\\}]+";

now you can use this variable in your regexp or anywhere.

How do I find out if first character of a string is a number?

To verify only first letter is number or character -- For number Character.isDigit(str.charAt(0)) --return true

For character Character.isLetter(str.charAt(0)) --return true

How to printf "unsigned long" in C?

int main()
{
    unsigned long long d;
    scanf("%llu",&d);
    printf("%llu",d);
    getch();
}

This will be helpful . . .

Detect the Enter key in a text input field

The solution that work for me is the following

$("#element").addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        // do something
    }
});

Regex pattern for checking if a string starts with a certain substring?

The following will match on any string that starts with mailto, ftp or http:

 RegEx reg = new RegEx("^(mailto|ftp|http)");

To break it down:

  • ^ matches start of line
  • (mailto|ftp|http) matches any of the items separated by a |

I would find StartsWith to be more readable in this case.

What is the default Jenkins password?

Here is how you can fix it:

  • Stop Jenkins
  • Go go edit /var/lib/jenkins/config.xml
  • Change <useSecurity>true</useSecurity> to false
  • Restart Jenkins: sudo service jenkins restart
  • Navigate to the Jenkins dashboard to the "Configure Security" option you likely used before. This time, setup security the same as before, BUT set it to allow anyone to do anything, and allow user signup.
  • Go to www.yoursite.com/securityRealm/addUser and create a user
  • Then go change allow anyone to do anything to whatever you actually want users to be able to do. In my case, it is allow logged in users to do anything.

Multiple inheritance for an anonymous class

I guess nobody understood the question. I guess what this guy wanted was something like this:

return new (class implements MyInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }
});

because this would allow things like multiple interface implementations:

return new (class implements MyInterface, AnotherInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }

    @Override
    public void anotherInterfaceMethod() { /*do something*/ }
});

this would be really nice indeed; but that's not allowed in Java.

What you can do is use local classes inside method blocks:

public AnotherInterface createAnotherInterface() {
    class LocalClass implements MyInterface, AnotherInterface {
        @Override
        public void myInterfaceMethod() { /*do something*/ }

        @Override
        public void anotherInterfaceMethod() { /*do something*/ }
    }
    return new LocalClass();
}

size of uint8, uint16 and uint32?

uint8, uint16, uint32, and uint64 are probably Microsoft-specific types.

As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>: uint8_t, uint16_t, uint32_t, and uint64_t. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>, at least as of Visual Studio 2010, but older code may use uint8 et al.

The predefined types char, short, int et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char is at least 8 bits, short and int are at least 16, long is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int is 16, 32, or 64 bits.

char is almost always exactly 8 bits, but it's permitted to be wider. And plain char may be either signed or unsigned.

uint8_t is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char, though it might be a typedef for plain char if plain char happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t will not be defined at all.

Similarly, each uintN_t type is an unsigned type that's exactly N bits wide.

In addition, <stdint.h> defines corresponding signed intN_t types, as well as int_fastN_t and int_leastN_t types that are at least the specified width.

The [u]intN_t types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t types are required to use a 2's-complement representation.

Although uint32_t might be the same as unsigned int, for example, you shouldn't assume that. Use unsigned int when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t when you need an unsigned integer type that's exactly 32 bits wide.

(And no, uint64 or uint64_t is not the same as double; double is a floating-point type.)

How do you calculate log base 2 in Java for integers?

This is the function that I use for this calculation:

public static int binlog( int bits ) // returns 0 for bits=0
{
    int log = 0;
    if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
    if( bits >= 256 ) { bits >>>= 8; log += 8; }
    if( bits >= 16  ) { bits >>>= 4; log += 4; }
    if( bits >= 4   ) { bits >>>= 2; log += 2; }
    return log + ( bits >>> 1 );
}

It is slightly faster than Integer.numberOfLeadingZeros() (20-30%) and almost 10 times faster (jdk 1.6 x64) than a Math.log() based implementation like this one:

private static final double log2div = 1.000000000001 / Math.log( 2 );
public static int log2fp0( int bits )
{
    if( bits == 0 )
        return 0; // or throw exception
    return (int) ( Math.log( bits & 0xffffffffL ) * log2div );
}

Both functions return the same results for all possible input values.

Update: The Java 1.7 server JIT is able to replace a few static math functions with alternative implementations based on CPU intrinsics. One of those functions is Integer.numberOfLeadingZeros(). So with a 1.7 or newer server VM, a implementation like the one in the question is actually slightly faster than the binlog above. Unfortunatly the client JIT doesn't seem to have this optimization.

public static int log2nlz( int bits )
{
    if( bits == 0 )
        return 0; // or throw exception
    return 31 - Integer.numberOfLeadingZeros( bits );
}

This implementation also returns the same results for all 2^32 possible input values as the the other two implementations I posted above.

Here are the actual runtimes on my PC (Sandy Bridge i7):

JDK 1.7 32 Bits client VM:

binlog:         11.5s
log2nlz:        16.5s
log2fp:        118.1s
log(x)/log(2): 165.0s

JDK 1.7 x64 server VM:

binlog:          5.8s
log2nlz:         5.1s
log2fp:         89.5s
log(x)/log(2): 108.1s

This is the test code:

int sum = 0, x = 0;
long time = System.nanoTime();
do sum += log2nlz( x ); while( ++x != 0 );
time = System.nanoTime() - time;
System.out.println( "time=" + time / 1000000L / 1000.0 + "s -> " + sum );

How to avoid "StaleElementReferenceException" in Selenium?

Kenny's solution is good, however it can be written in a more elegant way

new WebDriverWait(driver, timeout)
        .ignoring(StaleElementReferenceException.class)
        .until((WebDriver d) -> {
            d.findElement(By.id("checkoutLink")).click();
            return true;
        });

Or also:

new WebDriverWait(driver, timeout).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(By.id("checkoutLink")));
driver.findElement(By.id("checkoutLink")).click();

But anyway, best solution is to rely on Selenide library, it handles this kind of things and more. (instead of element references it handles proxies so you never have to deal with stale elements, which can be quite difficult). Selenide

Single huge .css file vs. multiple smaller specific .css files?

This is a hard one to answer. Both options have their pros and cons in my opinion.

I personally don't love reading through a single HUGE CSS file, and maintaining it is very difficult. On the other hand, splitting it out causes extra http requests which could potentially slow things down.

My opinion would be one of two things.

1) If you know that your CSS will NEVER change once you've built it, I'd build multiple CSS files in the development stage (for readability), and then manually combine them before going live (to reduce http requests)

2) If you know that you're going to change your CSS once in a while, and need to keep it readable, I would build separate files and use code (providing you're using some sort of programming language) to combine them at runtime build time (runtime minification/combination is a resource pig).

With either option I would highly recommend caching on the client side in order to further reduce http requests.

EDIT:
I found this blog that shows how to combine CSS at runtime using nothing but code. Worth taking a look at (though I haven't tested it myself yet).

EDIT 2:
I've settled on using separate files in my design time, and a build process to minify and combine. This way I can have separate (manageable) css while I develop and a proper monolithic minified file at runtime. And I still have my static files and less system overhead because I'm not doing compression/minification at runtime.

note: for you shoppers out there, I highly suggest using bundler as part of your build process. Whether you're building from within your IDE, or from a build script, bundler can be executed on Windows via the included exe or can be run on any machine that is already running node.js.

Difference between .dll and .exe?

The .exe is the program. The .dll is a library that a .exe (or another .dll) may call into.

What sakthivignesh says can be true in that one .exe can use another as if it were a library, and this is done (for example) with some COM components. In this case, the "slave" .exe is a separate program (strictly speaking, a separate process - perhaps running on a separate machine), but one that accepts and handles requests from other programs/components/whatever.

However, if you just pick a random .exe and .dll from a folder in your Program Files, odds are that COM isn't relevant - they are just a program and its dynamically-linked libraries.

Using Win32 APIs, a program can load and use a DLL using the LoadLibrary and GetProcAddress API functions, IIRC. There were similar functions in Win16.

COM is in many ways an evolution of the DLL idea, originally concieved as the basis for OLE2, whereas .NET is the descendant of COM. DLLs have been around since Windows 1, IIRC. They were originally a way of sharing binary code (particularly system APIs) between multiple running programs in order to minimise memory use.

Change Text Color of Selected Option in a Select Box

CSS
select{
  color:red;
 }

HTML
<select id="sel" onclick="document.getElementById('sel').style.color='green';">
 <option>Select Your Option</option>
 <option value="">INDIA</option>
 <option value="">USA</option>
</select>

The above code will change the colour of text on click of the select box.

and if you want every option different colour, give separate class or id to all options.

How to run a task when variable is undefined in ansible?

From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:

tasks:

- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
  when: foo is defined

- fail: msg="Bailing out. this play requires 'bar'"
  when: bar is not defined

So in your case, when: deployed_revision is not defined should work

Javascript loop through object array?

To reference the contents of the single array containing one or more objects i.e. everything in the brackets of something like this {messages: [{"a":1,"b":2}] } ,just add [0] to the query to get the first array element

e.g. messages[0] will reference the object {"a":1,"b":2} as opposed to just messages which would reference the entire array [{"a":1,"b":2}]

from there you can work with the result as typical object and use Object.keys for example to get "a" and "b".

Update values from one column in same table to another in SQL Server

UPDATE a
SET a.column1 = b.column2
FROM myTable a 
INNER JOIN myTable b
on a.myID = b.myID

in order for both "a" and "b" to work, both aliases must be defined

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

Replace the earlier function with the provided one. The simplest solution is:

def __unicode__(self):

    return unicode(self.nom_du_site)

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

Well i do it some thing like this.

        NormalWaitDialog/*your wait form*/ _frmWaitDialog = null;


        //Btn Load Click Event
        _frmWaitDialog = new NormalWaitDialog();
        _frmWaitDialog.Shown += async (s, ee) =>
        {
            await Task.Run(() =>
           {
               // DO YOUR STUFF HERE 

               //Made long running loop to imitate lengthy process
               int x = 0;
               for (int i = 0; i < int.MaxValue; i++)
               {
                   x += i;
               }

           }).ConfigureAwait(true);
            _frmWaitDialog.Close();
        };
        _frmWaitDialog.ShowDialog(this);

WinError 2 The system cannot find the file specified (Python)

I believe you need to .f file as a parameter, not as a command-single-string. same with the "--domain "+i, which i would split in two elements of the list. Assuming that:

  • you have the path set for FORTRAN executable,
  • the ~/ is indeed the correct way for the FORTRAN executable

I would change this line:

subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])

to

subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])

If that doesn't work, you should do a os.path.exists() for the .f file, and check that you can launch the FORTRAN executable without any path, and set the path or system path variable accordingly

[EDIT 6-Mar-2017]

As the exception, detailed in the original post, is a python exception from subprocess; it is likely that the WinError 2 is because it cannot find FORTRAN

I highly suggest that you specify full path for your executable:

for i in input:
    exe = r'c:\somedir\fortrandir\fortran.exe'
    fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
    subprocess.Popen([exe, fortran_script, "--domain", i])

if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:

for i in input:
    exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
    fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[EDIT 7-Mar-2017]

The following line is incorrect:

exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'

I am not sure why you have ~/ as a prefix for every path, don't do that.

for i in input:
    exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
    fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[2nd EDIT 7-Mar-2017]

I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:

subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)

You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess command.

Where does Visual Studio look for C++ header files?

Visual Studio looks for headers in this order:

  • In the current source directory.
  • In the Additional Include Directories in the project properties (Project -> [project name] Properties, under C/C++ | General).
  • In the Visual Studio C++ Include directories under Tools ? Options ? Projects and Solutions ? VC++ Directories.
  • In new versions of Visual Studio (2015+) the above option is deprecated and a list of default include directories is available at Project Properties ? Configuration ? VC++ Directories

In your case, add the directory that the header is to the project properties (Project Properties ? Configuration ? C/C++ ? General ? Additional Include Directories).

PHP Fatal Error Failed opening required File

If you have SELinux running, you might have to grant httpd permission to read from /home dir using:

 sudo setsebool httpd_read_user_content=1

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

- Another Update -

Since Twitter Bootstrap version 2.0 - which saw the removal of the .container-fluid class - it has not been possible to implement a two column fixed-fluid layout using just the bootstrap classes - however I have updated my answer to include some small CSS changes that can be made in your own CSS code that will make this possible

It is possible to implement a fixed-fluid structure using the CSS found below and slightly modified HTML code taken from the Twitter Bootstrap Scaffolding : layouts documentation page:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="fixed">  <!-- we want this div to be fixed width -->
            ...
        </div>
        <div class="hero-unit filler">  <!-- we have removed spanX class -->
            ...
        </div>
    </div>
</div>

CSS

/* CSS for fixed-fluid layout */

.fixed {
    width: 150px;  /* the fixed width required */
    float: left;
}

.fixed + div {
     margin-left: 150px;  /* must match the fixed width in the .fixed class */
     overflow: hidden;
}


/* CSS to ensure sidebar and content are same height (optional) */

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
    position: relative;
}

.filler:after{
    background-color:inherit;
    bottom: 0;
    content: "";
    height: auto;
    min-height: 100%;
    left: 0;
    margin:inherit;
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

I have kept the answer below - even though the edit to support 2.0 made it a fluid-fluid solution - as it explains the concepts behind making the sidebar and content the same height (a significant part of the askers question as identified in the comments)


Important

Answer below is fluid-fluid

Update As pointed out by @JasonCapriotti in the comments, the original answer to this question (created for v1.0) did not work in Bootstrap 2.0. For this reason, I have updated the answer to support Bootstrap 2.0

To ensure that the main content fills at least 100% of the screen height, we need to set the height of the html and body to 100% and create a new css class called .fill which has a minimum-height of 100%:

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
}

We can then add the .fill class to any element that we need to take up 100% of the sceen height. In this case we add it to the first div:

<div class="container-fluid fill">
    ...
</div>

To ensure that the Sidebar and the Content columns have the same height is very difficult and unnecessary. Instead we can use the ::after pseudo selector to add a filler element that will give the illusion that the two columns have the same height:

.filler::after {
    background-color: inherit;
    bottom: 0;
    content: "";
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

To make sure that the .filler element is positioned relatively to the .fill element we need to add position: relative to .fill:

.fill { 
    min-height: 100%;
    position: relative;
}

And finally add the .filler style to the HTML:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="span3">
            ...
        </div>
        <div class="span9 hero-unit filler">
            ...
        </div>
    </div>
</div>

Notes

  • If you need the element on the left of the page to be the filler then you need to change right: 0 to left: 0.

How to get pandas.DataFrame columns containing specific dtype

Someone will give you a better answe than this possibly, but one thing I tend to do is if all my numeric data are int64 or float64 objects, then you can create a dict of the column data types and then use the values to create your list of columns.

So for example, in a dataframe where I have columns of type float64, int64 and object firstly you can look at the data types as so:

DF.dtypes

and if they conform to the standard whereby the non-numeric columns of data are all object types (as they are in my dataframes), then you can do the following to get a list of the numeric columns:

[key for key in dict(DF.dtypes) if dict(DF.dtypes)[key] in ['float64', 'int64']]

Its just a simple list comprehension. Nothing fancy. Again, though whether this works for you will depend upon how you set up you dataframe...

Fatal error: Class 'PHPMailer' not found

I resolved error copying the files class.phpmailer.php , class.smtp.php to the folder where the file is PHPMailerAutoload.php, of course there should be the file that we will use to send the email.

Loading resources using getClass().getResource()

You can request a path in this format:

/package/path/to/the/resource.ext

Even the bytes for creating the classes in memory are found this way:

my.Class -> /my/Class.class

and getResource will give you a URL which can be used to retrieve an InputStream.

But... I'd recommend using directly getClass().getResourceAsStream(...) with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.

In short: try using getResourceAsStream and some constructor of ImageIcon that uses an InputStream as an argument.

Classloaders

Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon was capable of finding it.

Edit: classpath

getResource is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.

How to markdown nested list items in Bitbucket?

4 spaces do the trick even inside definition list:

Endpoint
: `/listAgencies`

Method
: `GET`

Arguments
:   * `level` - bla-bla.
    * `withDisabled` - should we include disabled `AGENT`s.
    * `userId` - bla-bla.

I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).

How to split one string into multiple strings separated by at least one space in bash shell?

For checking spaces just with bash:

[[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

I have also dealt with this exception after a fully working context.xml setup was adjusted. I didn't want environment details in the context.xml, so I took them out and saw this error. I realized I must fully create this datasource resource in code based on System Property JVM -D args.

Original error with just user/pwd/host removed: org.apache.tomcat.jdbc.pool.ConnectionPool init SEVERE: Unable to create initial connections of pool.

Removed entire contents of context.xml and try this: Initialize on startup of app server the datasource object sometime before using first connection. If using Spring this is good to do in an @Configuration bean in @Bean Datasource constructor.

package to use: org.apache.tomcat.jdbc.pool.*

PoolProperties p = new PoolProperties();
p.setUrl(jdbcUrl);
            p.setDriverClassName(driverClass);
            p.setUsername(user);
            p.setPassword(pwd);
            p.setJmxEnabled(true);
            p.setTestWhileIdle(false);
            p.setTestOnBorrow(true);
            p.setValidationQuery("SELECT 1");
            p.setTestOnReturn(false);
            p.setValidationInterval(30000);
            p.setValidationQueryTimeout(100);
            p.setTimeBetweenEvictionRunsMillis(30000);
            p.setMaxActive(100);
            p.setInitialSize(5);
            p.setMaxWait(10000);
            p.setRemoveAbandonedTimeout(60);
            p.setMinEvictableIdleTimeMillis(30000);
            p.setMinIdle(5);
            p.setLogAbandoned(true);
            p.setRemoveAbandoned(true);
            p.setJdbcInterceptors(
              "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
              "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
            org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
            ds.setPoolProperties(p);
            return ds;

How to use a TRIM function in SQL Server

Example:

DECLARE @Str NVARCHAR(MAX) = N'
            foo   bar
        Foo           Bar        

'

PRINT '[' + @Str + ']'

DECLARE @StrPrv NVARCHAR(MAX) = N''

WHILE ((@StrPrv <> @Str) AND (@Str IS NOT NULL)) BEGIN
    SET @StrPrv = @Str

    -- Beginning
    IF EXISTS (SELECT 1 WHERE @Str LIKE '[' + CHAR(13) + CHAR(10) + CHAR(9) + ']%')
        SET @Str = LTRIM(RIGHT(@Str, LEN(@Str) - 1))

    -- Ending
    IF EXISTS (SELECT 1 WHERE @Str LIKE '%[' + CHAR(13) + CHAR(10) + CHAR(9) + ']')
        SET @Str = RTRIM(LEFT(@Str, LEN(@Str) - 1))
END

PRINT '[' + @Str + ']'

Result

[
            foo   bar
        Foo           Bar        

]
[foo   bar
        Foo           Bar]

Using fnTrim

Source: https://github.com/reduardo7/fnTrim

SELECT dbo.fnTrim(colName)

Running Python code in Vim

Plugin: jupyter-vim

So you can send lines (<leader>E), visual selection (<leader>e) to a running jupyter-client (the replacement of ipython)

enter image description here

I prefer to separate editor and interpreter (each one in its shell). Imagine you send a bad input reading command ...

Editing the git commit message in GitHub

You need to git push -f assuming that nobody has pulled the other commit before. Beware, you're changing history.

How to load json into my angular.js ng-model?

Here's a simple example of how to load JSON data into an Angular model.

I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.

http://www.iNorthwind.com/Service1.svc/getAllCustomers

It returns some JSON data which looks like this:

{ 
    "GetAllCustomersResult" : 
        [
            {
              "CompanyName": "Alfreds Futterkiste",
              "CustomerID": "ALFKI"
            },
            {
              "CompanyName": "Ana Trujillo Emparedados y helados",
              "CustomerID": "ANATR"
            },
            {
              "CompanyName": "Antonio Moreno Taquería",
              "CustomerID": "ANTON"
            }
        ]
    }

..and I want to populate a drop down list with this data, to look like this...

Angular screenshot

I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.

How would I do it ?

My Angular controller would look like this:

function MikesAngularController($scope, $http) {

    $scope.listOfCustomers = null;

    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
         .success(function (data) {
             $scope.listOfCustomers = data.GetAllCustomersResult;
         })
         .error(function (data, status, headers, config) {
             //  Do some error handling here
         });
}

... which fills a "listOfCustomers" variable with this set of JSON data.

Then, in my HTML page, I'd use this:

<div ng-controller='MikesAngularController'>
    <span>Please select a customer:</span>
    <select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>

And that's it. We can now see a list of our JSON data on a web page, ready to be used.

The key to this is in the "ng-options" tag:

customer.CustomerID as customer.CompanyName for customer in listOfCustomers

It's a strange syntax to get your head around !

When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.

The full script for this example can be found here:

JSON data with Angular

Mike

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Just add autofocus in first input or textarea.

<input type="text" name="name" id="xax" autofocus="autofocus" />

#ifdef in C#

I would recommend you using the Conditional Attribute!

Update: 3.5 years later

You can use #if like this (example copied from MSDN):

// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass 
{
    static void Main() 
    {
#if (DEBUG && !VC_V7)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
        Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
        Console.WriteLine("DEBUG and VC_V7 are defined");
#else
        Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
    }
}

Only useful for excluding parts of methods.

If you use #if to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.

If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if with a method that returns a value you have to hide all pieces of code that call it too.

Here is an example:


    // calling Class1.ConditionalMethod() will be ignored at runtime 
    // unless the DEBUG constant is defined


    using System.Diagnostics;
    class Class1 
    {
       [Conditional("DEBUG")]
       public static void ConditionalMethod() {
          Console.WriteLine("Executed Class1.ConditionalMethod");
       }
    }

Summary:

I would use #ifdef in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though. You may want to use #if to avoid dependencies because with Conditional attribute your code is still compiled.

Javascript regular expression password validation having special characters

Use positive lookahead assertions:

var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

Without it, your current regex only matches that you have 6 to 16 valid characters, it doesn't validate that it has at least a number, and at least a special character. That's what the lookahead above is for.

  • (?=.*[0-9]) - Assert a string has at least one number;
  • (?=.*[!@#$%^&*]) - Assert a string has at least one special character.

Ignoring SSL certificate in Apache HttpClient 4.3

You can use following code snippet for get the HttpClient instance without ssl certification checking.

private HttpClient getSSLHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

        LogLoader.serverLog.trace("In getSSLHttpClient()");

        SSLContext context = SSLContext.getInstance("SSL");

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        context.init(null, new TrustManager[] { tm }, null);

        HttpClientBuilder builder = HttpClientBuilder.create();
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context);
        builder.setSSLSocketFactory(sslConnectionFactory);

        PlainConnectionSocketFactory plainConnectionSocketFactory = new PlainConnectionSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory).register("http", plainConnectionSocketFactory).build();

        PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(registry);
        ccm.setMaxTotal(BaseConstant.CONNECTION_POOL_SIZE);
        ccm.setDefaultMaxPerRoute(BaseConstant.CONNECTION_POOL_SIZE);
        builder.setConnectionManager((HttpClientConnectionManager) ccm);

        builder.disableRedirectHandling();

        LogLoader.serverLog.trace("Out getSSLHttpClient()");

        return builder.build();
    }

What is the most efficient way to deep clone an object in JavaScript?

I use the npm clone library. Apparently it also works in the browser.

https://www.npmjs.com/package/clone

let a = clone(b)

How to split a string in Java

There are only two methods you really need to consider.

Use String.split for a one-character delimiter or you don't care about performance

If performance is not an issue, or if the delimiter is a single character that is not a regular expression special character (i.e., not one of .$|()[{^?*+\) then you can use String.split.

String[] results = input.split(",");

The split method has an optimization to avoid using a regular expression if the delimeter is a single character and not in the above list. Otherwise, it has to compile a regular expression, and this is not ideal.

Use Pattern.split and precompile the pattern if using a complex delimiter and you care about performance.

If performance is an issue, and your delimiter is not one of the above, you should pre-compile a regular expression pattern which you can then reuse.

// Save this somewhere
Pattern pattern = Pattern.compile("[,;:]");

/// ... later
String[] results = pattern.split(input);

This last option still creates a new Matcher object. You can also cache this object and reset it for each input for maximum performance, but that is somewhat more complicated and not thread-safe.

MAC addresses in JavaScript

No you cannot get the MAC address in JavaScript, mainly because the MAC address uniquely identifies the running computer so it would be a security vulnerability.

Now if all you need is a unique identifier, I suggest you create one yourself using some cryptographic algorithm and store it in a cookie.

If you really need to know the MAC address of the computer AND you are developing for internal applications, then I suggest you use an external component to do that: ActiveX for IE, XPCOM for Firefox (installed as an extension).

Align two inline-blocks left and right on same line

New ways to align items right:

Grid:

.header {
        display:grid;
        grid-template-columns: 1fr auto;
    }

Demo

Bootstrap 4. Align right:

<div class="row">
      <div class="col">left</div>
      <div class="col">
          <div class="float-right">element needs to be right aligned</div>
      </div>
</div>

Demo

Sending string via socket (python)

import socket
from threading import *

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            print('Client sent:', self.sock.recv(1024).decode())
            self.sock.send(b'Oi you sent something to me')

serversocket.listen(5)
print ('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

This is a very VERY simple design for how you could solve it. First of all, you need to either accept the client (server side) before going into your while 1 loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.

How to format numbers by prepending 0 to single-digit numbers?

Here's my version. Can easily be adapted to other scenarios.

function setNumericFormat(value) {
    var length = value.toString().length;
    if (length < 4) {
        var prefix = "";
        for (var i = 1; i <= 4 - length; i++) {
            prefix += "0";
        }
        return prefix + value.toString();
    }
    return  value.toString();
}

list.clear() vs list = new ArrayList<Integer>();

Tried the below program , With both the approach. 1. With clearing the arraylist obj in for loop 2. creating new New Arraylist in for loop.

List al= new ArrayList();
        for(int i=0;i<100;i++)
        {
            //List al= new ArrayList();

            for(int j=0;j<10;j++)
            {
                al.add(Integer.parseInt("" +j+i));
                //System.out.println("Obj val " +al.get(j));
            }
            //System.out.println("Hashcode : " + al.hashCode());
            al.clear();

        }

and to my surprise. the memory allocation didnt change much.

With New Arraylist approach.

Before loop total free memory: 64,909 ::

After loop total free memory: 64,775 ::

with Clear approach,

Before loop total free memory: 64,909 :: After loop total free memory: 64,765 ::

So this says there is not much difference in using arraylist.clear from memory utilization perspective.

How to count number of files in each directory?

A super fast miracle command, which recursively traverses files to count the number of images in a directory and organize the output by image extension:

find . -type f | sed -e 's/.*\.//' | sort | uniq -c | sort -n | grep -Ei '(tiff|bmp|jpeg|jpg|png|gif)$'

Credits: https://unix.stackexchange.com/a/386135/354980

Compression/Decompression string with C#

I like @fubo's answer the best but I think this is much more elegant.

This method is more compatible because it doesn't manually store the length up front.

Also I've exposed extensions to support compression for string to string, byte[] to byte[], and Stream to Stream.

public static class ZipExtensions
{
    public static string CompressToBase64(this string data)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(data).Compress());
    }

    public static string DecompressFromBase64(this string data)
    {
        return Encoding.UTF8.GetString(Convert.FromBase64String(data).Decompress());
    }
    
    public static byte[] Compress(this byte[] data)
    {
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
        {
            sourceStream.CompressTo(destinationStream);
            return destinationStream.ToArray();
        }
    }

    public static byte[] Decompress(this byte[] data)
    {
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
        {
            sourceStream.DecompressTo(destinationStream);
            return destinationStream.ToArray();
        }
    }
    
    public static void CompressTo(this Stream stream, Stream outputStream)
    {
        using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
        {
            stream.CopyTo(gZipStream);
            gZipStream.Flush();
        }
    }

    public static void DecompressTo(this Stream stream, Stream outputStream)
    {
        using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))
        {
            gZipStream.CopyTo(outputStream);
        }
    }
}

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
_x000D_
_x000D_

How do I create a simple 'Hello World' module in Magento?

I will rather recommend Mage2Gen, this will help you generate the boilerplate and you can just focus on the core business logic. it just helps speed up the things.

Importing modules from parent folder

I had a problem where I had to import a Flask application, that had an import that also needed to import files in separate folders. This is partially using Remi's answer, but suppose we had a repository that looks like this:

.
+-- service
    +-- misc
        +-- categories.csv
    +-- test
        +-- app_test.py
    app.py
    pipeline.py

Then before importing the app object from the app.py file, we change the directory one level up, so when we import the app (which imports the pipeline.py), we can also read in miscellaneous files like a csv file.

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)

os.chdir('../')
from app import app

After having imported the Flask app, you can use os.chdir('./test') so that your working directory is not changed.

android button selector

Create custom_selector.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@drawable/unselected" android:state_pressed="true" />
   <item android:drawable="@drawable/selected" />
</selector>

Create selected.xml shape in drawable folder

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="90dp">
   <solid android:color="@color/selected"/>
   <padding />
   <stroke android:color="#000" android:width="1dp"/>
   <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>
</shape>

Create unselected.xml shape in drawable folder

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="90dp">
   <solid android:color="@color/unselected"/>
   <padding />
   <stroke android:color="#000" android:width="1dp"/>
   <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>
</shape>

Add following colors for selected/unselected state in color.xml of values folder

<color name="selected">#a8cf45</color>
<color name="unselected">#ff8cae3b</color>

you can check complete solution from here

Register DLL file on Windows Server 2008 R2

You need the full path to the regsvr32 so %windir$\system32\regsvr32 <*.dll>

Plot multiple lines in one graph

The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.

plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) )  )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
  } 
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

TypeError : Unhashable type

You are creating a set via set(...) call, and set needs hashable items. You can't have set of lists. Because list's arent hashable.

[[(a,b) for a in range(3)] for b in range(3)] is a list. It's not a hashable type. The __hash__ you saw in dir(...) isn't a method, it's just None.

A list comprehension returns a list, you don't need to explicitly use list there, just use:

>>> [[(a,b) for a in range(3)] for b in range(3)]
[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]

Try those:

>>> a = {1, 2, 3}
>>> b= [1, 2, 3]
>>> type(a)
<class 'set'>
>>> type(b)
<class 'list'>
>>> {1, 2, []}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> print([].__hash__)
None
>>> [[],[],[]] #list of lists
[[], [], []]
>>> {[], [], []} #set of lists
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

What are metaclasses in Python?

The tl;dr version

The type(obj) function gets you the type of an object.

The type() of a class is its metaclass.

To use a metaclass:

class Foo(object):
    __metaclass__ = MyMetaClass

type is its own metaclass. The class of a class is a metaclass-- the body of a class is the arguments passed to the metaclass that is used to construct the class.

Here you can read about how to use metaclasses to customize class construction.

How to center a table of the screen (vertically and horizontally)

This fixes the box dead center on the screen:

HTML

<table class="box" border="1px">
    <tr>
        <td>
            my content
        </td>
    </tr>
</table>

CSS

.box {
    width:300px;
    height:300px;
    background-color:#d9d9d9;
    position:fixed;
    margin-left:-150px; /* half of width */
    margin-top:-150px;  /* half of height */
    top:50%;
    left:50%;
}

View Results

http://jsfiddle.net/bukov/wJ7dY/168/

Receiver not registered exception error?

Be careful, when you register by

LocalBroadcastManager.getInstance(this).registerReceiver()

you can't unregister by

 unregisterReceiver()

you must use

LocalBroadcastManager.getInstance(this).unregisterReceiver()

or app will crash, log as follow:

09-30 14:00:55.458 19064-19064/com.jialan.guangdian.view E/AndroidRuntime: FATAL EXCEPTION: main Process: com.jialan.guangdian.view, PID: 19064 java.lang.RuntimeException: Unable to stop service com.google.android.exoplayer.demo.player.PlayService@141ba331: java.lang.IllegalArgumentException: Receiver not registered: com.google.android.exoplayer.demo.player.PlayService$PlayStatusReceiver@19538584 at android.app.ActivityThread.handleStopService(ActivityThread.java:2941) at android.app.ActivityThread.access$2200(ActivityThread.java:148) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5310) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.google.android.exoplayer.demo.player.PlayService$PlayStatusReceiver@19538584 at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:769) at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1794) at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:510) at com.google.android.exoplayer.demo.player.PlayService.onDestroy(PlayService.java:542) at android.app.ActivityThread.handleStopService(ActivityThread.java:2924) at android.app.ActivityThread.access$2200(ActivityThread.java:148)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5310)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) 

How to change Oracle default data pump directory to import dumpfile?

With the directory parameter:

impdp system/password@$ORACLE_SID schemas=USER_SCHEMA directory=MY_DIR \
  dumpfile=mydumpfile.dmp logfile=impdpmydumpfile.log

The default directory is DATA_PUMP_DIR, which is presumably set to /u01/app/oracle/admin/mydatabase/dpdump on your system.

To use a different directory you (or your DBA) will have to create a new directory object in the database, which points to the Oracle-visible operating system directory you put the file into, and assign privileges to the user doing the import.

How do you convert a byte array to a hexadecimal string, and vice versa?

You can use the BitConverter.ToString method:

byte[] bytes = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256}
Console.WriteLine( BitConverter.ToString(bytes));

Output:

00-01-02-04-08-10-20-40-80-FF

More information: BitConverter.ToString Method (Byte[])

How do you extract classes' source code from a dll file?

You cannot get the exact code, but you can get a decompiled version of it.

The most popular (and best) tool is Reflector, but there are also other .Net decompilers (such as Dis#). You can also decompile the IL using ILDASM, which comes bundled with the .Net Framework SDK Tools.

How to enable ASP classic in IIS7.5

Add Authenticated Users

Make the file accessible to the Authenticated Users group. Right click your virtual directory and give the group read/write access to Authenticated Users.

I faced issue on windows 10 machine.

What does "restore purchases" in In-App purchases mean?

You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.

for other type of products it will automatically restore it.

Please read following text which will clear your concept about this :

Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.

Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.

If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices

Best way to handle multiple constructors in Java

You need to specify what are the class invariants, i.e. properties which will always be true for an instance of the class (for example, the title of a book will never be null, or the size of a dog will always be > 0).

These invariants should be established during construction, and be preserved along the lifetime of the object, which means that methods shall not break the invariants. The constructors can set these invariants either by having compulsory arguments, or by setting default values:

class Book {
    private String title; // not nullable
    private String isbn;  // nullable

    // Here we provide a default value, but we could also skip the 
    // parameterless constructor entirely, to force users of the class to
    // provide a title
    public Book()
    {
        this("Untitled"); 
    }

    public Book(String title) throws IllegalArgumentException
    {
        if (title == null) 
            throw new IllegalArgumentException("Book title can't be null");
        this.title = title;
        // leave isbn without value
    }
    // Constructor with title and isbn
}

However, the choice of these invariants highly depends on the class you're writing, how you'll use it, etc., so there's no definitive answer to your question.

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Simple fix for me was

  1. Build > Clean project
  2. Restart Android Studio

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

If you're like me, and would rather not make this security hole system or user-wide, then you can add a config option to any git repos that need this by running this command in those repos. (note only works with git version >= 2.10, released 2016-09-04)

git config core.sshCommand 'ssh -oHostKeyAlgorithms=+ssh-dss'

This only works after the repo is setup however. If you're not comfortable adding a remote manually (and just want to clone) then you can run the clone like this:

GIT_SSH_COMMAND='ssh -oHostKeyAlgorithms=+ssh-dss' git clone ssh://user@host/path-to-repository

then run the first command to make it permanent.

If you don't have the latest, and still would like to keep the hole as local as possible I recommend putting

export GIT_SSH_COMMAND='ssh -oHostKeyAlgorithms=+ssh-dss'

in a file somewhere, say git_ssh_allow_dsa_keys.sh, and sourceing it when needed.

Node.js Hostname/IP doesn't match certificate's altnames

We don't have this problem if we are testing our client request with localhost destination address (host or hostname on node.js) and our server common name is CN = localhost in the server cert. But even if we change localhost for 127.0.0.1 or any other IP we'll get error Hostname/IP doesn't match certificate's altnames on node.js or SSL handshake failed on QT.

I had the same issue about my server certificate on my client request. To solve it on my client node.js app I needed to put a subjectAltName on my server_extension with the following value:

[ server_extension ]
       .
       .
       .

subjectAltName          = @alt_names_server

[alt_names_server]
IP.1 = x.x.x.x

and then I use -extension when I create and sign the certificate.

example:

In my case, I first export the issuer's config file because this file contents the server_extension:

export OPENSSL_CONF=intermed-ca.cnf

so I create and sign my server cert:

openssl ca \
    -in server.req.pem \
    -out server.cert.pem \
    -extensions server_extension \
    -startdate `date +%y%m%d000000Z -u -d -2day` \
    -enddate `date +%y%m%d000000Z -u -d +2years+1day`   

It works fine on clients based on node.js with https requests but it doesn't work with clients based on QT QSsl when we define sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyPeer), unless we use QSslSocket::VerifyNone it won't work. If we use VerifyNone it will make our app to don't check the peer certificate so it'll accept any cert. So, to solve it I need to change my server common name on its cert and replace its value for the IP Address where my server is running.

for example:

CN = 127.0.0.1

How to get a substring between two strings in PHP?

I have been using this for years and it works well. Could probably be made more efficient, but

grabstring("Test string","","",0) returns Test string
grabstring("Test string","Test ","",0) returns string
grabstring("Test string","s","",5) returns string

function grabstring($strSource,$strPre,$strPost,$StartAt) {
if(@strpos($strSource,$strPre)===FALSE && $strPre!=""){
    return("");
}
@$Startpoint=strpos($strSource,$strPre,$StartAt)+strlen($strPre);
if($strPost == "") {
    $EndPoint = strlen($strSource);
} else {
    if(strpos($strSource,$strPost,$Startpoint)===FALSE){
        $EndPoint= strlen($strSource);
    } else {
        $EndPoint = strpos($strSource,$strPost,$Startpoint);
    }
}
if($strPre == "") {
    $Startpoint = 0;
}
if($EndPoint - $Startpoint < 1) {
    return "";
} else {
        return substr($strSource, $Startpoint, $EndPoint - $Startpoint);
}

}

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

Run change detection explicitly after the change:

import { ChangeDetectorRef } from '@angular/core';

constructor(private cdRef:ChangeDetectorRef) {}

ngAfterViewChecked()
{
  console.log( "! changement de la date du composant !" );
  this.dateNow = new Date();
  this.cdRef.detectChanges();
}

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

TSQL select into Temp table from dynamic sql

How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)

DECLARE @sql AS nvarchar(MAX)
declare @Month Nvarchar(1000)

--DROP TABLE #temp
select distinct YYYYMM into #temp from #AccPurch AS ap
SELECT  @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM    #temp

SELECT   @Month= LEFT(@Month,len(@Month)-1)


SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
Select ap.AccPurch ,
       ap.YYYYMM ,
       ap.UserID ,
       ap.AccountNumber
FROM #AccPurch AS ap 
) p
Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'


EXEC sp_executesql @sql

Select * INTO #final From ##final_Donovan_12345

DROP TABLE  ##final_Donovan_12345

Select * From #final AS f

The value violated the integrity constraints for the column

You can replace the values "null" from the original file & field/column.

Get current application physical path within Application_Start

use below code

server.mappath() in asp.net

application.startuppath in c# windows application

Preloading CSS Images

When there is no way to modify CSS code and preload images with CSS rules for :before or :after pseudo elements another approach with JavaScript code traversing CSS rules of loaded stylesheets can be used. In order to make it working scripts should be included after stylesheets in HTML, for example, before closing body tag or just after stylesheets.

getUrls() {
    const urlRegExp = /url\(('|")?([^'"()]+)('|")\)?/;

    let urls = [];
    for (let i = 0; i < document.styleSheets.length; i++) {
        let cssRules = document.styleSheets[i].cssRules;
        for (let j = 0; j < cssRules.length; j++) {
            let cssRule = cssRules[j];
            if (!cssRule.selectorText) {
                continue;
            }

            for (let k = 0; k < cssRule.style.length; k++) {
                let property = cssRule.style[k],
                    urlMatch = cssRule.style[property].match(urlRegExp);
                if (urlMatch !== null) {
                    urls.push(urlMatch[2]);
                }
            }
        }
    }
    return urls;
}

preloadImages() {
    return new Promise(resolve => {
        let urls = getUrls(),
            loadedCount = 0;

        const onImageLoad = () => {
            loadedCount++;
            if (urls.length === loadedCount) {
                resolve();
            }
        };

        for (var i = 0; i < urls.length; i++) {
            let image = new Image();
            image.src = urls[i];
            image.onload = onImageLoad;
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    preloadImages().then(() => {
        // CSS images are loaded here
    });
});

Why do python lists have pop() but not push()

Ok, personal opinion here, but Append and Prepend imply precise positions in a set.

Push and Pop are really concepts that can be applied to either end of a set... Just as long as you're consistent... For some reason, to me, Push() seems like it should apply to the front of a set...

How to display all elements in an arraylist?

Set for each loop to get all values

for (String member : members){
    Log.i("Member name: ", member);
}

Plotting power spectrum in python

if rate is the sampling rate(Hz), then np.linspace(0, rate/2, n) is the frequency array of every point in fft. You can use rfft to calculate the fft in your data is real values:

import numpy as np
import pylab as pl
rate = 30.0
t = np.arange(0, 10, 1/rate)
x = np.sin(2*np.pi*4*t) + np.sin(2*np.pi*7*t) + np.random.randn(len(t))*0.2
p = 20*np.log10(np.abs(np.fft.rfft(x)))
f = np.linspace(0, rate/2, len(p))
plot(f, p)

enter image description here

signal x contains 4Hz & 7Hz sin wave, so there are two peaks at 4Hz & 7Hz.

Combine several images horizontally with Python

If all image’s heights are same,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x)) for x in imgs],
    axis=1
  )
)

maybe you can resize images before the concatenation like this,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x).resize((640,480)) for x in imgs],
    axis=1
  )
)

Checkout another branch when there are uncommitted changes on the current branch

In case you don't want this changes to be committed at all do git reset --hard.

Next you can checkout to wanted branch, but remember that uncommitted changes will be lost.

What is console.log?

Apart from the usages mentioned above, console.log can also print to the terminal in node.js. A server created with express (for eg.) can use console.log to write to the output logger file.

How to find the width of a div using vanilla JavaScript?

You can also search the DOM using ClassName. For example:

document.getElementsByClassName("myDiv")

This will return an array. If there is one particular property you are interested in. For example:

var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;

divWidth will now be equal to the the width of the first element in your div array.

How to toggle boolean state of react component?

Use checked to get the value. During onChange, checked will be true and it will be a type of boolean.

Hope this helps!

_x000D_
_x000D_
class A extends React.Component {_x000D_
  constructor() {_x000D_
    super()_x000D_
    this.handleCheckBox = this.handleCheckBox.bind(this)_x000D_
    this.state = {_x000D_
      checked: false_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  handleCheckBox(e) {_x000D_
    this.setState({_x000D_
      checked: e.target.checked_x000D_
    })_x000D_
  }_x000D_
  _x000D_
  render(){_x000D_
    return <input type="checkbox" onChange={this.handleCheckBox} checked={this.state.checked} />_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<A/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

iterate through a map in javascript

An answer to your Question from 2019:

It depends on what version of ECMAScript you use.

Pre ES6:

Use any of the answers below, e.g.:

for (var m in myMap){
    for (var i=0;i<myMap[m].length;i++){
    ... do something with myMap[m][i] ...
    }
} 

For ES6 (ES 2015):

You should use a Map object, which has the entries() function:

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const [key, value] of myMap.entries()) {
  console.log(key, value);
}

For ES8 (ES 2017):

Object.entries() was introduced:

const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
  console.log(key, value);
}

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

Hbase quickly count number of rows

Simple, Effective and Efficient way to count row in HBASE:

  1. Whenever you insert a row trigger this API which will increment that particular cell.

    Htable.incrementColumnValue(Bytes.toBytes("count"), Bytes.toBytes("details"), Bytes.toBytes("count"), 1);
    
  2. To check number of rows present in that table. Just use "Get" or "scan" API for that particular Row 'count'.

By using this Method you can get the row count in less than a millisecond.

How to set cornerRadius for only top-left and top-right corner of a UIView?

In Swift 4.2, Create it via @IBDesignable like this:

@IBDesignable

class DesignableViewCustomCorner: UIView {

    @IBInspectable var cornerRadious: CGFloat = 0 {
        didSet {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadious, height: cornerRadious))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            self.layer.mask = mask
        }
    }

}

How to convert date to timestamp?

function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

In some cases data was not encoded into JSON format, so you need to encode it first e.g

 json_encode($data);

Later you will use json Parse in your JS, like

JSON.parse(data);

Display the binary representation of a number in C?

This code should handle your needs up to 64 bits.



char* pBinFill(long int x,char *so, char fillChar); // version with fill
char* pBin(long int x, char *so);                    // version without fill
#define width 64

char* pBin(long int x,char *so)
{
 char s[width+1];
 int    i=width;
 s[i--]=0x00;   // terminate string
 do
 { // fill in array from right to left
  s[i--]=(x & 1) ? '1':'0';  // determine bit
  x>>=1;  // shift right 1 bit
 } while( x > 0);
 i++;   // point to last valid character
 sprintf(so,"%s",s+i); // stick it in the temp string string
 return so;
}

char* pBinFill(long int x,char *so, char fillChar)
{ // fill in array from right to left
 char s[width+1];
 int    i=width;
 s[i--]=0x00;   // terminate string
 do
 {
  s[i--]=(x & 1) ? '1':'0';
  x>>=1;  // shift right 1 bit
 } while( x > 0);
 while(i>=0) s[i--]=fillChar;    // fill with fillChar 
 sprintf(so,"%s",s);
 return so;
}

void test()
{
 char so[width+1]; // working buffer for pBin
 long int   val=1;
 do
 {
   printf("%ld =\t\t%#lx =\t\t0b%s\n",val,val,pBinFill(val,so,0));
   val*=11; // generate test data
 } while (val < 100000000);
}

Output:
00000001 = 0x000001 =   0b00000000000000000000000000000001
00000011 = 0x00000b =   0b00000000000000000000000000001011
00000121 = 0x000079 =   0b00000000000000000000000001111001
00001331 = 0x000533 =   0b00000000000000000000010100110011
00014641 = 0x003931 =   0b00000000000000000011100100110001
00161051 = 0x02751b =   0b00000000000000100111010100011011
01771561 = 0x1b0829 =   0b00000000000110110000100000101001
19487171 = 0x12959c3 =  0b00000001001010010101100111000011

How do you load custom UITableViewCells from Xib files?

Here are two methods which the original author states was recommended by an IB engineer.

See the actual post for more details. I prefer method #2 as it seems simpler.

Method #1:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BDCustomCell"];
    if (cell == nil) {
        // Create a temporary UIViewController to instantiate the custom cell.
        UIViewController *temporaryController = [[UIViewController alloc] initWithNibName:@"BDCustomCell" bundle:nil];
        // Grab a pointer to the custom cell.
        cell = (BDCustomCell *)temporaryController.view;
        [[cell retain] autorelease];
        // Release the temporary UIViewController.
        [temporaryController release];
    }

    return cell;
}

Method #2:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BDCustomCell"];
    if (cell == nil) {
        // Load the top-level objects from the custom cell XIB.
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"BDCustomCell" owner:self options:nil];
        // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
        cell = [topLevelObjects objectAtIndex:0];
    }

    return cell;
}

Update (2014): Method #2 is still valid but there is no documentation for it anymore. It used to be in the official docs but is now removed in favor of storyboards.

I posted a working example on Github:
https://github.com/bentford/NibTableCellExample

edit for Swift 4.2

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    self.tblContacts.register(UINib(nibName: CellNames.ContactsCell, bundle: nil), forCellReuseIdentifier: MyIdentifier)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: MyIdentifier, for: indexPath) as! ContactsCell

    return cell
}

Can I set up HTML/Email Templates with ASP.NET?

I think the easy answer is MvcMailer. It s NuGet package that lets you use your favorite view engine to generate emails. See the NuGet package here and the project documentation

Hope it helps!

What is the best (idiomatic) way to check the type of a Python variable?

That should work - so no, there is nothing wrong with your code. However, it could also be done with a dict:

{type(str()): do_something_with_a_string,
 type(dict()): do_something_with_a_dict}.get(type(x), errorhandler)()

A bit more concise and pythonic wouldn't you say?


Edit.. Heeding Avisser's advice, the code also works like this, and looks nicer:

{str: do_something_with_a_string,
 dict: do_something_with_a_dict}.get(type(x), errorhandler)()

Get record counts for all tables in MySQL database

This is what I do to get the actual count (no using the schema)

It's slower but more accurate.

It's a two step process at

  1. Get list of tables for your db. You can get it using

    mysql -uroot -p mydb -e "show tables"
    
  2. Create and assign the list of tables to the array variable in this bash script (separated by a single space just like in the code below)

    array=( table1 table2 table3 )
    
    for i in "${array[@]}"
    do
        echo $i
        mysql -uroot mydb -e "select count(*) from $i"
    done
    
  3. Run it:

    chmod +x script.sh; ./script.sh
    

How do I use a third-party DLL file in Visual Studio C++?

As everyone else says, LoadLibrary is the hard way to do it, and is hardly ever necessary.

The DLL should have come with a .lib file for linking, and one or more header files to #include into your sources. The header files will define the classes and function prototypes that you can use from the DLL. You will need this even if you use LoadLibrary.

To link with the library, you might have to add the .lib file to the project configuration under Linker/Input/Additional Dependencies.

How to lay out Views in RelativeLayout programmatically?

Android 22 minimal runnable example

enter image description here

Source:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final RelativeLayout relativeLayout = new RelativeLayout(this);

        final TextView tv1;
        tv1 = new TextView(this);
        tv1.setText("tv1");
        // Setting an ID is mandatory.
        tv1.setId(View.generateViewId());
        relativeLayout.addView(tv1);

        // tv2.
        final TextView tv2;
        tv2 = new TextView(this);
        tv2.setText("tv2");
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.FILL_PARENT);
        lp.addRule(RelativeLayout.BELOW, tv1.getId());
        relativeLayout.addView(tv2, lp);

        // tv3.
        final TextView tv3;
        tv3 = new TextView(this);
        tv3.setText("tv3");
        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        );
        lp2.addRule(RelativeLayout.BELOW, tv2.getId());
        relativeLayout.addView(tv3, lp2);

        this.setContentView(relativeLayout);
    }
}

Works with the default project generated by android create project .... GitHub repository with minimal build code.

Disable submit button when form invalid with AngularJS

We can create a simple directive and disable the button until all the mandatory fields are filled.

angular.module('sampleapp').directive('disableBtn',
function() {
 return {
  restrict : 'A',
  link : function(scope, element, attrs) {
   var $el = $(element);
   var submitBtn = $el.find('button[type="submit"]');
   var _name = attrs.name;
   scope.$watch(_name + '.$valid', function(val) {
    if (val) {
     submitBtn.removeAttr('disabled');
    } else {
     submitBtn.attr('disabled', 'disabled');
    }
   });
  }
 };
}
);

For More Info click here

Why .NET String is immutable?

  1. Instances of immutable types are inherently thread-safe, since no thread can modify it, the risk of a thread modifying it in a way that interferes with another is removed (the reference itself is a different matter).
  2. Similarly, the fact that aliasing can't produce changes (if x and y both refer to the same object a change to x entails a change to y) allows for considerable compiler optimisations.
  3. Memory-saving optimisations are also possible. Interning and atomising being the most obvious examples, though we can do other versions of the same principle. I once produced a memory saving of about half a GB by comparing immutable objects and replacing references to duplicates so that they all pointed to the same instance (time-consuming, but a minute's extra start-up to save a massive amount of memory was a performance win in the case in question). With mutable objects that can't be done.
  4. No side-effects can come from passing an immutable type as a method to a parameter unless it is out or ref (since that changes the reference, not the object). A programmer therefore knows that if string x = "abc" at the start of a method, and that doesn't change in the body of the method, then x == "abc" at the end of the method.
  5. Conceptually, the semantics are more like value types; in particular equality is based on state rather than identity. This means that "abc" == "ab" + "c". While this doesn't require immutability, the fact that a reference to such a string will always equal "abc" throughout its lifetime (which does require immutability) makes uses as keys where maintaining equality to previous values is vital, much easier to ensure correctness of (strings are indeed commonly used as keys).
  6. Conceptually, it can make more sense to be immutable. If we add a month onto Christmas, we haven't changed Christmas, we have produced a new date in late January. It makes sense therefore that Christmas.AddMonths(1) produces a new DateTime rather than changing a mutable one. (Another example, if I as a mutable object change my name, what has changed is which name I am using, "Jon" remains immutable and other Jons will be unaffected.
  7. Copying is fast and simple, to create a clone just return this. Since the copy can't be changed anyway, pretending something is its own copy is safe.
  8. [Edit, I'd forgotten this one]. Internal state can be safely shared between objects. For example, if you were implementing list which was backed by an array, a start index and a count, then the most expensive part of creating a sub-range would be copying the objects. However, if it was immutable then the sub-range object could reference the same array, with only the start index and count having to change, with a very considerable change to construction time.

In all, for objects which don't have undergoing change as part of their purpose, there can be many advantages in being immutable. The main disadvantage is in requiring extra constructions, though even here it's often overstated (remember, you have to do several appends before StringBuilder becomes more efficient than the equivalent series of concatenations, with their inherent construction).

It would be a disadvantage if mutability was part of the purpose of an object (who'd want to be modeled by an Employee object whose salary could never ever change) though sometimes even then it can be useful (in a many web and other stateless applications, code doing read operations is separate from that doing updates, and using different objects may be natural - I wouldn't make an object immutable and then force that pattern, but if I already had that pattern I might make my "read" objects immutable for the performance and correctness-guarantee gain).

Copy-on-write is a middle ground. Here the "real" class holds a reference to a "state" class. State classes are shared on copy operations, but if you change the state, a new copy of the state class is created. This is more often used with C++ than C#, which is why it's std:string enjoys some, but not all, of the advantages of immutable types, while remaining mutable.

Detect merged cells in VBA Excel with MergeArea

There are several helpful bits of code for this.

Place your cursor in a merged cell and ask these questions in the Immidiate Window:

Is the activecell a merged cell?

? Activecell.Mergecells
 True

How many cells are merged?

? Activecell.MergeArea.Cells.Count
 2

How many columns are merged?

? Activecell.MergeArea.Columns.Count
 2

How many rows are merged?

? Activecell.MergeArea.Rows.Count
  1

What's the merged range address?

? activecell.MergeArea.Address
  $F$2:$F$3

Run a command shell in jenkins

Error shows that script does not exists

The file does not exists. check your full path

C:\Windows\TEMP\hudson6299483223982766034.sh
The system cannot find the file specified

Moreover, to launch .sh scripts into windows, you need to have CYGWIN installed and well configured into your path

Confirm that script exists.

Into jenkins script, do the following to confirm that you do have the file

cd C:\Windows\TEMP\
ls -rtl
sh -xe hudson6299483223982766034.sh

How to execute multiple SQL statements from java

you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference

When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.

  • JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
  • The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
  • The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
  • Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.

EXAMPLE:

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");

      Statement stmt = con.createStatement
      (ResultSet.TYPE_SCROLL_SENSITIVE,
      ResultSet.CONCUR_UPDATABLE);
      String insertEmp1 = "insert into emp values
      (10,'jay','trainee')";
      String insertEmp2 = "insert into emp values
      (11,'jayes','trainee')";
      String insertEmp3 = "insert into emp values
      (12,'shail','trainee')";
      con.setAutoCommit(false);
      stmt.addBatch(insertEmp1);//inserting Query in stmt
      stmt.addBatch(insertEmp2);
      stmt.addBatch(insertEmp3);
      ResultSet rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows before batch execution= "
      + rs.getRow());
      stmt.executeBatch();
      con.commit();
      System.out.println("Batch executed");
      rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows after batch execution= "
      + rs.getRow());
   }
} 

refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm

VB.NET: Clear DataGridView

To remove the old record in datagridview when you are searching for new result,with button_click event write the following code,

me.DataGridview1.DataSource.clear()

this code will help to remove the old record in datagridview.

List files in local git repo?

git ls-tree --full-tree -r HEAD and git ls-files return all files at once. For a large project with hundreds or thousands of files, and if you are interested in a particular file/directory, you may find more convenient to explore specific directories. You can do it by obtaining the ID/SHA-1 of the directory that you want to explore and then use git cat-file -p [ID/SHA-1 of directory]. For example:

git cat-file -p 14032aabd85b43a058cfc7025dd4fa9dd325ea97
100644 blob b93a4953fff68df523aa7656497ee339d6026d64    glyphicons-halflings-regular.eot
100644 blob 94fb5490a2ed10b2c69a4a567a4fd2e4f706d841    glyphicons-halflings-regular.svg
100644 blob 1413fc609ab6f21774de0cb7e01360095584f65b    glyphicons-halflings-regular.ttf
100644 blob 9e612858f802245ddcbf59788a0db942224bab35    glyphicons-halflings-regular.woff
100644 blob 64539b54c3751a6d9adb44c8e3a45ba5a73b77f0    glyphicons-halflings-regular.woff2

In the example above, 14032aabd85b43a058cfc7025dd4fa9dd325ea97 is the ID/SHA-1 of the directory that I wanted to explore. In this case, the result was that four files within that directory were being tracked by my Git repo. If the directory had additional files, it would mean those extra files were not being tracked. You can add files using git add <file>... of course.

Assert an object is a specific type

You can use the assertThat method and the Matchers that comes with JUnit.

Take a look at this link that describes a little bit about the JUnit Matchers.

Example:

public class BaseClass {
}

public class SubClass extends BaseClass {
}

Test:

import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;

/**
 * @author maba, 2012-09-13
 */
public class InstanceOfTest {

    @Test
    public void testInstanceOf() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }
}

How to pass a PHP variable using the URL

I found this solution in "Super useful bits of PHP, Form and JavaScript code" at Skytopia.

Inside "page1.php" or "page1.html":

// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
<a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a> 

    //or as I needed it.
    <a href='page2c.php?myNumber={$row[0]}&myFruit={$row[1]}'>Send variables</a>

Inside "page2c.php":

<?php
    // Retrieve the URL variables (using PHP).
    $num = $_GET['myNumber'];
    $fruit = $_GET['myFruit'];
    echo "Number: ".$num."  Fruit: ".$fruit;
?>

How to parse an RSS feed using JavaScript?

I was so exasperated by many misleading articles and answers that I wrote my own RSS reader: https://gouessej.wordpress.com/2020/06/28/comment-creer-un-lecteur-rss-en-javascript-how-to-create-a-rss-reader-in-javascript/

You can use AJAX requests to fetch the RSS files but it will work if and only if you use a CORS proxy. I'll try to write my own CORS proxy to give you a more robust solution. In the meantime, it works, I deployed it on my server under Debian Linux.

My solution doesn't use JQuery, I use only plain Javascript standard APIs with no third party libraries and it's supposed to work even with Microsoft Internet Explorer 11.

How can I get my Android device country code without using GPS?

There isn't any need to call any API. You can get the country code from your device where it is located. Just use this function:

 fun getUserCountry(context: Context): String? {
    try {
        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val simCountry = tm.simCountryIso
        if (simCountry != null && simCountry.length == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US)
        } 
        else if (tm.phoneType != TelephonyManager.PHONE_TYPE_CDMA) { // Device is not 3G (would be unreliable)
            val networkCountry = tm.networkCountryIso
            if (networkCountry != null && networkCountry.length == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US)
            }
        }
    }
    catch (e: Exception) {
    }
    return null
}

Why is the gets function so dangerous that it should not be used?

fgets.

To read from the stdin:

char string[512];

fgets(string, sizeof(string), stdin); /* no buffer overflows here, you're safe! */

"relocation R_X86_64_32S against " linking Error

Add -fPIC at the end of CMAKE_CXX_FLAGS and CMAKE_C_FLAG

Example:

set( CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -Wall --std=c++11 -O3 -fPIC" )
set( CMAKE_C_FLAGS  "${CMAKE_C_FLAGS} -Wall -O3 -fPIC" )

This solved my issue.

How to compare types

If your instance is a Type:

Type typeFiled;
if (typeField == typeof(string))
{ 
    ... 
}

but if your instance is an object and not a Type use the as operator:

object value;
string text = value as string;
if (text != null)
{
    // value is a string and you can do your work here
}

this has the advantage to convert value only once into the specified type.

Converting dd/mm/yyyy formatted string to Datetime

use DateTime.ParseExact

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)

null will use the current culture, which is somewhat dangerous. Try to supply a specific culture

DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)

Appending HTML string to the DOM

The right way is using insertAdjacentHTML. In Firefox earlier than 8, you can fall back to using Range.createContextualFragment if your str contains no script tags.

If your str contains script tags, you need to remove script elements from the fragment returned by createContextualFragment before inserting the fragment. Otherwise, the scripts will run. (insertAdjacentHTML marks scripts unexecutable.)

Using str_replace so that it only acts on the first match?

For Loop Solution

<?php
echo replaceFirstMatchedChar("&", "?", "/property/details&id=202&test=123#tab-6");

function replaceFirstMatchedChar($searchChar, $replaceChar, $str)
{
    for ($i = 0; $i < strlen($str); $i++) {

        if ($str[$i] == $searchChar) {
            $str[$i] = $replaceChar;
            break;
        }
    }
    return $str;
}

How do I get the value of a textbox using jQuery?

By Using

$("#txtEmail").val()

you get the actual value of the element

Exit a while loop in VBS/VBA

While Loop is an obsolete structure, I would recommend you to replace "While loop" to "Do While..loop", and you will able to use Exit clause.

check = 0 

Do while not rs.EOF 
   if rs("reg_code") = rcode then 
      check = 1 
      Response.Write ("Found") 
      Exit do
   else 
      rs.MoveNext 
    end if 
Loop 

if check = 0 then 
   Response.Write "Not Found" 
end if}

Constantly print Subprocess output while process is running

In Python >= 3.5 using subprocess.run works for me:

import subprocess

cmd = 'echo foo; sleep 1; echo foo; sleep 2; echo foo'
subprocess.run(cmd, shell=True)

(getting the output during execution also works without shell=True) https://docs.python.org/3/library/subprocess.html#subprocess.run

How to parse a CSV in a Bash script?

CSV isn't quite that simple. Depending on the limits of the data you have, you might have to worry about quoted values (which may contain commas and newlines) and escaping quotes.

So if your data are restricted enough can get away with simple comma-splitting fine, shell script can do that easily. If, on the other hand, you need to parse CSV ‘properly’, bash would not be my first choice. Instead I'd look at a higher-level scripting language, for example Python with a csv.reader.

HTML5 Canvas background image

Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img> element placed under the canvas. To draw a background onto the canvas element you can do something like the following:

Live Demo

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = 903;
canvas.height = 657;


var background = new Image();
background.src = "http://www.samskirrow.com/background.png";

// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
    ctx.drawImage(background,0,0);   
}

// Draw whatever else over top of it on the canvas.

How can I make my website's background transparent without making the content (images & text) transparent too?

Make the background image transparent/semi-transparent. If it's a solid coloured background just create a 1px by 1px image in fireworks or whatever and adjust its opacity...

Undo git update-index --assume-unchanged <file>

I assume (heh) you meant --assume-unchanged, since I don't see any --assume-changed option. The inverse of --assume-unchanged is --no-assume-unchanged.

'python' is not recognized as an internal or external command

If you uninstalled then re-installed, and running 'python' in CLI, make sure to open a new CMD after your installation for 'python' to be recognized. 'py' will probably be recognized with an old CLI because its not tied to any version.

git - Your branch is ahead of 'origin/master' by 1 commit

You cannot push anything that hasn't been committed yet. The order of operations is:

  1. Make your change.
  2. git add - this stages your changes for committing
  3. git commit - this commits your staged changes locally
  4. git push - this pushes your committed changes to a remote

If you push without committing, nothing gets pushed. If you commit without adding, nothing gets committed. If you add without committing, nothing at all happens, git merely remembers that the changes you added should be considered for the following commit.

The message you're seeing (your branch is ahead by 1 commit) means that your local repository has one commit that hasn't been pushed yet.

In other words: add and commit are local operations, push, pull and fetch are operations that interact with a remote.

Since there seems to be an official source control workflow in place where you work, you should ask internally how this should be handled.

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

To center it, you can use the technique shown here: Absolute centering.

To make it as big as possible, give it max-width and max-height of 100%.

To maintain the aspect ratio (even when the width is specifically set like in the snippet below), use object-fit as explained here.

_x000D_
_x000D_
.className {
    max-width: 100%;
    max-height: 100%;
    bottom: 0;
    left: 0;
    margin: auto;
    overflow: auto;
    position: fixed;
    right: 0;
    top: 0;
    -o-object-fit: contain;
    object-fit: contain;
}
_x000D_
<img src="https://i.imgur.com/HmezgW6.png" class="className" />

<!-- Slider to control the image width, only to make demo clearer !-->
<input type="range" min="10" max="2000" value="276" step="10" oninput="document.querySelector('img').style.width = (this.value +'px')" style="width: 90%; position: absolute; z-index: 2;" >
_x000D_
_x000D_
_x000D_

How do I see the commit differences between branches in git?

Not the perfect answer but works better for people using Github:

enter image description here

Go to your repo: Insights -> Network

nginx: send all requests to a single html page

The correct way would be:

location / {
    rewrite (.*) base.html last;
}

Using last will make nginx find a new suitable location block according to the result of rewriting.

try_files is also a perfectly valid approach to this problem.

Shorthand if/else statement Javascript

Here is a way to do it that works, but may not be best practise for any language really:

var x,y;
x='something';
y=1;
undefined === y || (x = y);

alternatively

undefined !== y && (x = y);

Adding to a vector of pair

Use std::make_pair:

revenue.push_back(std::make_pair("string",map[i].second));

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

Below code work for me in web.xml file

<servlet>
    <servlet-name>WebService</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.example.demo.webservice</param-value>
        //Package
    </init-param>
    <init-param>
        <param-name>unit:WidgetPU</param-name>
        <param-value>persistence/widget</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>WebService</servlet-name>
    <url-pattern>/webservices/*</url-pattern>
</servlet-mapping>

How can I list all of the files in a directory with Perl?

readdir() does that.

Check http://perldoc.perl.org/functions/readdir.html

opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;

How do I find an array item with TypeScript? (a modern, easier way)

Playing with the tsconfig.json You can also targeting es5 like this :

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "module": "commonjs", 
        "target": "es5"
    }
    ...

push multiple elements to array

Now in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:

_x000D_
_x000D_
var arr = [1];_x000D_
var newItems = [2, 3];_x000D_
arr.push(...newItems);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

See Kangax's ES6 compatibility table to see what browsers are compatible

How to use python numpy.savetxt to write strings and float number to an ASCII file?

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I found the solution : it's the 9th byte of this key :

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections] "DefaultConnectionSettings"=hex:3c,00,00,00,1f,00,00,00,05,00,00,00,00,00,00, 00,00,00,00,00,00,00,00,00,01,00,00,00,1f,00,00,00,68,74,74,70,3a,2f,2f,31, 34,34,2e,31,33,31,2e,32,32,32,2e,31,36,37,2f,77,70,61,64,2e,64,61,74,90,0e, 1e,66,d3,88,c5,01,01,00,00,00,8d,a8,4e,9e,00,00,00,00,00,00,00,00

It's a bitfield:

  • 0x1: (Always 1)
  • 0x2: Proxy enabled
  • 0x4: "Use automatic configuration script" checked
  • 0x8: "Automatically detect settings" checked

Mask 0x8 to turn it off, i.e., subtract 8 if it's higher than 8.

Thanks to Jamie on google groups.

Update

Based on the VBScript by WhoIsRich combined with details in this answer, here's a PowerShell script to amend these & related settings:

function Set-ProxySettings {
    [CmdletBinding()]
    param ( #could improve with parameter sets 
        [Parameter(Mandatory = $false)]
        [bool]$AutomaticDetect = $true
        ,
        [Parameter(Mandatory = $false)]
        [bool]$UseProxyForLAN = $false
        ,
        [Parameter(Mandatory = $false)]
        [AllowNull()][AllowEmptyString()]
        [string]$ProxyAddress = $null
        ,
        [Parameter(Mandatory = $false)]
        [int]$ProxyPort = 8080 #closest we have to a default port for proxies
        ,
        [AllowNull()][AllowEmptyString()]
        [bool]$UseAutomaticConfigurationScript = $false
    )
    begin {
        [string]$ProxyRegRoot = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
        [string]$DefaultConnectionSettingsPath = (Join-Path $ProxyRegRoot 'Connections')
        [byte]$MaskProxyEnabled = 2
        [byte]$MaskUseAutomaticConfigurationScript = 4
        [byte]$MaskAutomaticDetect = 8
        [int]$ProxyConnectionSettingIndex = 8
    }
    process {
    #this setting is affected by multiple options, so fetch once here 
    [byte[]]$DefaultConnectionSettings = Get-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' | Select-Object -ExpandProperty 'DefaultConnectionSettings'

    #region auto detect
    if($AutomaticDetect) { 
        Set-ItemProperty -Path $ProxyRegRoot -Name AutoDetect -Value 1
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskAutomaticDetect
    } else {
        Set-ItemProperty -Path $ProxyRegRoot -Name AutoDetect -Value 0
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskAutomaticDetect)
    }
    #endregion

    #region defined proxy
    if($UseProxyForLAN) {
        if(-not ([string]::IsNullOrWhiteSpace($ProxyAddress))) {
            Set-ItemProperty -Path $ProxyRegRoot -Name ProxyServer -Value ("{0}:{1}" -f $ProxyAddress,$ProxyPort)
        }
        Set-ItemProperty -Path $ProxyRegRoot -Name ProxyEnable -Value 1
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskProxyEnabled
    } else {
        Set-ItemProperty -Path $ProxyRegRoot -Name ProxyEnable -Value 0        
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskProxyEnabled)
    }
    #endregion

    #region config script
    if($UseAutomaticConfigurationScript){
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskUseAutomaticConfigurationScript
    }else{
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskUseAutomaticConfigurationScript) 
    }
    #endregion

    #persist the updates made above
    Set-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' -Value $DefaultConnectionSettings
    }
}

WPF MVVM ComboBox SelectedItem or SelectedValue not working

I had the same problem. The thing is. The selected item doesnt know which object it should use from the collection. So you have to say to the selected item to use the item from the collection.

public MyObject SelectedObject
 {
      get
      {
          Objects.find(x => x.id == _selectedObject.id)
          return _selectedObject;
      }
      set
      {
           _selectedObject = value;
      }
 }

I hope this helps.

What is the difference between parseInt() and Number()?

One minor difference is what they convert of undefined or null,

Number() Or Number(null) // returns 0

while

parseInt() Or parseInt(null) // returns NaN

How to clear jQuery validation error messages?

If you want to reset numberOfInvalids() as well then add following line in resetForm function in jquery.validate.js file line number: 415.

this.invalid = {};

Insert line break in wrapped cell via code

Yes. The VBA equivalent of AltEnter is to use a linebreak character:

ActiveCell.Value = "I am a " & Chr(10) & "test"

Note that this automatically sets WrapText to True.

Proof:

Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub

Are lists thread-safe?

I recently had this case where I needed to append to a list continuously in one thread, loop through the items and check if the item was ready, it was an AsyncResult in my case and remove it from the list only if it was ready. I could not find any examples that demonstrated my problem clearly Here is an example demonstrating adding to list in one thread continuously and removing from the same list in another thread continuously The flawed version runs easily on smaller numbers but keep the numbers big enough and run a few times and you will see the error

The FLAWED version

import threading
import time

# Change this number as you please, bigger numbers will get the error quickly
count = 1000
l = []

def add():
    for i in range(count):
        l.append(i)
        time.sleep(0.0001)

def remove():
    for i in range(count):
        l.remove(i)
        time.sleep(0.0001)


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()

print(l)

Output when ERROR

Exception in thread Thread-63:
Traceback (most recent call last):
  File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "<ipython-input-30-ecfbac1c776f>", line 13, in remove
    l.remove(i)
ValueError: list.remove(x): x not in list

Version that uses locks

import threading
import time
count = 1000
l = []
lock = threading.RLock()
def add():
    with lock:
        for i in range(count):
            l.append(i)
            time.sleep(0.0001)

def remove():
    with lock:
        for i in range(count):
            l.remove(i)
            time.sleep(0.0001)


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()

print(l)

Output

[] # Empty list

Conclusion

As mentioned in the earlier answers while the act of appending or popping elements from the list itself is thread safe, what is not thread safe is when you append in one thread and pop in another

I want to declare an empty array in java and then I want do update it but the code is not working

You can't set a number in an arbitrary place in the array without telling the array how big it needs to be. For your example: int[] array = new int[4];

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Below is the exact code you need to make your sheet look exactly as it is in the attached PDF:

try
        {
            Excel.Application application;
            Excel.Workbook workBook;
            Excel.Worksheet workSheet;
            object misValue = System.Reflection.Missing.Value;

            application = new Excel.ApplicationClass();
            workBook = application.Workbooks.Add(misValue);
            workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(1);

            int i = 1;
            workSheet.Cells[i, 2] = "MSS Close Sheet"; 
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;               
            i++;
            workSheet.Cells[i, 2] = "MSS - " + dpsNoTextBox.Text;
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            i++;
            workSheet.Cells[i, 2] = customerNameTextBox.Text;
            i++;                
            workSheet.Cells[i, 2] = "Opening Date : ";
            workSheet.Cells[i, 3] = openingDateTextBox.Value.ToShortDateString();
            i++;
            workSheet.Cells[i, 2] = "Closing Date : ";
            workSheet.Cells[i, 3] = closingDateTextBox.Value.ToShortDateString();
            i++;
            i++;
            i++;

            workSheet.Cells[i, 1] = "SL. No";
            workSheet.Cells[i, 2] = "Month";
            workSheet.Cells[i, 3] = "Amount Deposited";
            workSheet.Cells[i, 4] = "Fine";
            workSheet.Cells[i, 5] = "Cumulative Total";
            workSheet.Cells[i, 6] = "Profit + Cumulative Total";
            workSheet.Cells[i, 7] = "Profit @ " + profitRateComboBox.Text;
            WorkSheet.Cells[i, 1].EntireRow.Font.Bold = true;
            i++;



            /////////////////////////////////////////////////////////
            foreach (RecurringDeposit rd in RecurringDepositList)
            {
                workSheet.Cells[i, 1] = rd.SN.ToString();
                workSheet.Cells[i, 2] = rd.MonthYear;
                workSheet.Cells[i, 3] = rd.InstallmentSize.ToString();
                workSheet.Cells[i, 4] = "";
                workSheet.Cells[i, 5] = rd.CumulativeTotal.ToString();
                workSheet.Cells[i, 6] = rd.ProfitCumulative.ToString();
                workSheet.Cells[i, 7] = rd.Profit.ToString();
                i++;
            }
            //////////////////////////////////////////////////////


            ////////////////////////////////////////////////////////
            workSheet.Cells[i, 2] = "Total (" + RecurringDepositList.Count + " months installment)";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = totalAmountDepositedTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "a) Total Amount Deposited";
            workSheet.Cells[i, 3] = totalAmountDepositedTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "b) Fine";
            workSheet.Cells[i, 3] = "";
            i++;

            workSheet.Cells[i, 2] = "c) Total Pft Paid";
            workSheet.Cells[i, 3] = totalProfitPaidTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Sub Total";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (totalAmountDepositedTextBox.Value + totalProfitPaidTextBox.Value).ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Deduction";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            i++;

            workSheet.Cells[i, 2] = "a) Excise Duty";
            workSheet.Cells[i, 3] = "0";
            i++;

            workSheet.Cells[i, 2] = "b) Income Tax on Pft. @ " + incomeTaxPercentageTextBox.Text;
            workSheet.Cells[i, 3] = "0";
            i++;

            workSheet.Cells[i, 2] = "c) Account Closing Charge ";
            workSheet.Cells[i, 3] = closingChargeCommaNumberTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "d) Outstanding on BAIM(FO) ";
            workSheet.Cells[i, 3] = baimFOLowerTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Total Deduction ";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (incomeTaxDeductionTextBox.Value + closingChargeCommaNumberTextBox.Value + baimFOTextBox.Value).ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Client Paid ";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = customerPayableNumberTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "e) Current Balance ";
            workSheet.Cells[i, 3] = currentBalanceCommaNumberTextBox.Value.ToString("0.00");
            workSheet.Cells[i, 5] = "Exp. Pft paid on MSS A/C(PL67054)";
            workSheet.Cells[i, 6] = plTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "e) Total Paid ";
            workSheet.Cells[i, 3] = customerPayableNumberTextBox.Value.ToString("0.00");
            workSheet.Cells[i, 5] = "IT on Pft (BDT16216)";
            workSheet.Cells[i, 6] = incomeTaxDeductionTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Difference";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (currentBalanceCommaNumberTextBox.Value - customerPayableNumberTextBox.Value).ToString("0.00");
            workSheet.Cells[i, 5] = "Account Closing Charge";
            workSheet.Cells[i, 6] = closingChargeCommaNumberTextBox.Value;
            i++;

            ///////////////////////////////////////////////////////////////

            workBook.SaveAs("D:\\" + dpsNoTextBox.Text.Trim() + "-" + customerNameTextBox.Text.Trim() + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            workBook.Close(true, misValue, misValue);
            application.Quit();

            releaseObject(workSheet);
            releaseObject(workBook);
            releaseObject(application);

iOS Detection of Screenshot?

Swift 4 Examples

Example #1 using closure

NotificationCenter.default.addObserver(forName: .UIApplicationUserDidTakeScreenshot, 
                                       object: nil, 
                                       queue: OperationQueue.main) { notification in
    print("\(notification) that a screenshot was taken!")
}

Example #2 with selector

NotificationCenter.default.addObserver(self, 
                                       selector: #selector(screenshotTaken), 
                                       name: .UIApplicationUserDidTakeScreenshot, 
                                       object: nil)

@objc func screenshotTaken() {
    print("Screenshot taken!")
}

How do I set the background color of Excel cells using VBA?

or alternatively you could not bother coding for it and use the 'conditional formatting' function in Excel which will set the background colour and font colour based on cell value.

There are only two variables here so set the default to yellow and then overwrite when the value is greater than or less than your threshold values.

iPhone App Icons - Exact Radius?

After trying some of the answers in this post, I consulted with Louie Mantia (former Apple, Square, and Iconfactory designer) and all the answers so far on this post are wrong (or at least incomplete). Apple starts with the 57px icon and a radius of 10 then scales up or down from there. Thus you can calculate the radius for any icon size using 10/57 x new size (for example 10/57 x 114 gives 20, which is the proper radius for a 114px icon). Here is a list of the most commonly used icons, proper naming conventions, pixel dimensions, and corner radii.

  1. Icon1024.png - 1024px - 179.649
  2. Icon512.png - 512px - 89.825
  3. Icon.png - 57px - 10
  4. [email protected] - 114px - 20
  5. Icon-72.png - 72px - 12.632
  6. [email protected] - 144px - 25.263
  7. Icon-Small.png - 29px - 5.088
  8. [email protected] - 58px - 10.175

Also, as mentioned in other answers, you don't actually want to crop any of the images you use in the binary or submit to Apple. Those should all be square and not have any transparency. Apple will automatically mask each icon in the appropriate context.

Knowing the above is important, however, for icon usage within app UI where you have to apply the mask in code, or pre-rendered in photoshop. It's also helpful when creating artwork for websites and other promotional material.

Additional reading:

Neven Mrgan on additional icon sizes and other design considerations: ios app icon sizes

Bjango's Marc Edwards on the different options for creating roundrects in Photoshop and why it matters: roundrect

Apple's official docs on icon size and design considerations: Icons and Images

Update:

I did some tests in Photoshop CS6 and it seems as though 3 digits after the decimal point is enough precision to end up with the exact same vector (at least as displayed by Photoshop at 3200% zoom). The Round Rect Tool sometimes rounds the input to the nearest whole number, but you can see a significant difference between 90 and 89.825. And several times the Round Rectangle Tool didn't round up and actually showed multiple digits after the decimal point. Not sure what's going on there, but it's definitely using and storing the more precise number that was entered.

Anyhow, I've updated the list above to include just 3 digits after the decimal point (before there were 13!). In most situations it would probably be hard to tell the difference between a transparent 512px icon masked at a 90px radius and one masked at 89.825, but the antialiasing of the rounded corner would definitely end up slightly different and would likely be visible in certain circumstances especially if a second, more precise mask is applied by Apple, in code, or otherwise.

jQuery.ajax returns 400 Bad Request

I think you just need to add 2 more options (contentType and dataType):

$('#my_get_related_keywords').click(function() {

    $.ajax({
            type: "POST",
            url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
            data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
            contentType: "application/json; charset=utf-8", // this
            dataType: "json", // and this
            success: function (msg) {
               //do something
            },
            error: function (errormessage) {
                //do something else
            }
        });
}