Programs & Examples On #Bamboo

Bamboo is a continuous integration and deployment server from Atlassian, the makers of JIRA, Confluence and Crowd.

use jQuery's find() on JSON object

The pure javascript solution is better, but a jQuery way would be to use the jQuery grep and/or map methods. Probably not much better than using $.each

jQuery.grep(TestObj, function(obj) {
    return obj.id === "A";
});

or

jQuery.map(TestObj, function(obj) {
    if(obj.id === "A")
         return obj; // or return obj.name, whatever.
});

Returns an array of the matching objects, or of the looked-up values in the case of map. Might be able to do what you want simply using those.

But in this example you'd have to do some recursion, because the data isn't a flat array, and we're accepting arbitrary structures, keys, and values, just like the pure javascript solutions do.

function getObjects(obj, key, val) {
    var retv = [];

    if(jQuery.isPlainObject(obj))
    {
        if(obj[key] === val) // may want to add obj.hasOwnProperty(key) here.
            retv.push(obj);

        var objects = jQuery.grep(obj, function(elem) {
            return (jQuery.isArray(elem) || jQuery.isPlainObject(elem));
        });

        retv.concat(jQuery.map(objects, function(elem){
            return getObjects(elem, key, val);
        }));
    }

    return retv;
}

Essentially the same as Box9's answer, but using the jQuery utility functions where useful.

········

Tab key == 4 spaces and auto-indent after curly braces in Vim

As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your .vimrc):

filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab

In your [.vimrc:][1] file:
set smartindent
set tabstop=4
set shiftwidth=4
set expandtab

The help files take a bit of time to get used to, but the more you read, the better Vim gets:

:help smartindent

Even better, you can embed these settings in your source for portability:

:help auto-setting

To see your current settings:

:set all

As graywh points out in the comments, smartindent has been replaced by cindent which "Works more cleverly", although still mainly for languages with C-like syntax:

:help C-indenting

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

Answering to myself. From the RequireJS website:

//THIS WILL FAIL
define(['require'], function (require) {
    var namedModule = require('name');
});

This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.

My solution:

// Modules configuration (modules that will be used as Jade helpers)
define(function () {
    return {
        'moment':   'path/to/moment',
        'filesize': 'path/to/filesize',
        '_':        'path/to/lodash',
        '_s':       'path/to/underscore.string'
    };
});

The loader:

define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
    var deps;

    // Dynamic require
    require(_.values(Config), function () {
        deps = _.object(_.keys(Config), arguments);

        // Use deps...
    });
});

jQuery UI dialog positioning

I don't think the speech bubble is quite right. I tweaked it a bit so that it would work and the item opens right under the link.

function PositionDialog(link) {
    $('#myDialog').dialog('open');
    var myDialogX = $(link).position().left;
    var myDialogY = $(link).position().top + $(link).outerHeight();
    $('#myDialog').dialog('option', 'position', [myDialogX, myDialogY]);
}

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

I got the same error with something like:

Set rs = dbs.OpenRecordset _
( _
  "SELECT Field1, Field2, FieldN " _
  & "FROM Query1 " _
  & "WHERE Query2.Field1 = """ & Value1 & """;" _
, dbOpenSnapshot _
)

I fixed the error by replacing "Query1" with "Query2"

How can I make a program wait for a variable change in javascript?

I would recommend a wrapper that will handle value being changed. For example you can have JavaScript function, like this:

?function Variable(initVal, onChange)
{
    this.val = initVal;          //Value to be stored in this object
    this.onChange = onChange;    //OnChange handler

    //This method returns stored value
    this.GetValue = function()  
    {
        return this.val;
    }

    //This method changes the value and calls the given handler       
    this.SetValue = function(value)
    {
        this.val = value;
        this.onChange();
    }


}

And then you can make an object out of it that will hold value that you want to monitor, and also a function that will be called when the value gets changed. For example, if you want to be alerted when the value changes, and initial value is 10, you would write code like this:

var myVar = new Variable(10, function(){alert("Value changed!");});

Handler function(){alert("Value changed!");} will be called (if you look at the code) when SetValue() is called.

You can get value like so:

alert(myVar.GetValue());

You can set value like so:

myVar.SetValue(12);

And immediately after, an alert will be shown on the screen. See how it works: http://jsfiddle.net/cDJsB/

How to move screen without moving cursor in Vim?

Additionally:

  • Ctrl-y Moves screen up one line
  • Ctrl-e Moves screen down one line
  • Ctrl-u Moves cursor & screen up ½ page
  • Ctrl-d Moves cursor & screen down ½ page
  • Ctrl-b Moves screen up one page, cursor to last line
  • Ctrl-f Moves screen down one page, cursor to first line

Ctrl-y and Ctrl-e only change the cursor position if it would be moved off screen.

Courtesy of http://www.lagmonster.org/docs/vi2.html

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

You could also disable the cascade delete convention in global scope of your application by doing this:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()

How can I retrieve a table from stored procedure to a datatable?

Explaining if any one want to send some parameters while calling stored procedure as below,

using (SqlConnection con = new SqlConnection(connetionString))
            {
                using (var command = new SqlCommand(storedProcName, con))
                {
                    foreach (var item in sqlParams)
                    {
                        item.Direction = ParameterDirection.Input;
                        item.DbType = DbType.String;
                        command.Parameters.Add(item);
                    }
                    command.CommandType = CommandType.StoredProcedure;
                    using (var adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dt);
                    }
                }
            }

MySQL combine two columns and add into a new column

Are you sure you want to do this? In essence, you're duplicating the data that is in the three original columns. From that point on, you'll need to make sure that the data in the combined field matches the data in the first three columns. This is more overhead for your application, and other processes that update the system will need to understand the relationship.

If you need the data, why not select in when you need it? The SQL for selecting what would be in that field would be:

SELECT CONCAT(zipcode, ' - ', city, ', ', state) FROM Table;

This way, if the data in the fields changes, you don't have to update your combined field.

Find indices of elements equal to zero in a NumPy array

I would do it the following way:

>>> x = np.array([[1,0,0], [0,2,0], [1,1,0]])
>>> x
array([[1, 0, 0],
       [0, 2, 0],
       [1, 1, 0]])
>>> np.nonzero(x)
(array([0, 1, 2, 2]), array([0, 1, 0, 1]))

# if you want it in coordinates
>>> x[np.nonzero(x)]
array([1, 2, 1, 1])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
       [1, 1],
       [2, 0],
       [2, 1])

ES6 class variable alternatives

If its only the cluttering what gives the problem in the constructor why not implement a initialize method that intializes the variables. This is a normal thing to do when the constructor gets to full with unnecessary stuff. Even in typed program languages like C# its normal convention to add an Initialize method to handle that.

Java: How to access methods from another class

You either need to create an object of type Beta in the Alpha class or its method

Like you do here in the Main Beta cBeta = new Beta();

If you want to use the variable you create in your Main then you have to parse it to cAlpha as a parameter by making the Alpha constructor look like

public class Alpha 
{

    Beta localInstance;

    public Alpha(Beta _beta)
    {
        localInstance = _beta;
    }


     public void DoSomethingAlpha() 
     {
          localInstance.DoSomethingAlpha();     
     }
}

How to select all elements with a particular ID in jQuery?

I would use Different IDs but assign each DIV the same class.

<div id="c-1" class="countdown"></div>
<div id="c-2" class="countdown"></div>

This also has the added benefit of being able to reconstruct the IDs based off of the return of jQuery('.countdown').length


Ok what about adding multiple classes to each countdown timer. IE:

<div class="countdown c-1"></div>
<div class="countdown c-2"></div>
<div class="countdown c-1"></div>

That way you get the best of both worlds. It even allows repeat 'IDS'

Get the (last part of) current directory name in C#

You could try:

var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
var dirName = new DirectoryInfo(path).Name;

Convert DateTime to long and also the other way around

There are several possibilities (note that the those long values aren't the same as the Unix epoch.

For your example (to reverse ToFileTime()) just use DateTime.FromFileTime(t).

Return index of greatest value in an array

This is probably the best way, since it’s reliable and works on old browsers:

function indexOfMax(arr) {
    if (arr.length === 0) {
        return -1;
    }

    var max = arr[0];
    var maxIndex = 0;

    for (var i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            maxIndex = i;
            max = arr[i];
        }
    }

    return maxIndex;
}

There’s also this one-liner:

let i = arr.indexOf(Math.max(...arr));

It performs twice as many comparisons as necessary and will throw a RangeError on large arrays, though. I’d stick to the function.

Difference between .dll and .exe?

An exe is an executible program whereas A DLL is a file that can be loaded and executed by programs dynamically.

Delete last commit in bitbucket

In the first place, if you are working with other people on the same code repository, you should not delete a commit since when you force the update on the repository it will leave the local repositories of your coworkers in an illegal state (e.g. if they made commits after the one you deleted, those commits will be invalid since they were based on a now non-existent commit).

Said that, what you can do is revert the commit. This procedure is done differently (different commands) depending on the CVS you're using:

On git:

git revert <commit>

On mercurial:

hg backout <REV>

EDIT: The revert operation creates a new commit that does the opposite than the reverted commit (e.g. if the original commit added a line, the revert commit deletes that line), effectively removing the changes of the undesired commit without rewriting the repository history.

jQuery : select all element with custom attribute

As described by the link I've given in comment, this

$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "<br>");});

works (playable example).

How to print values separated by spaces instead of new lines in Python 2.7

This does almost everything you want:

f = open('data.txt', 'rb')

while True:
    char = f.read(1)
    if not char: break
    print "{:02x}".format(ord(char)),

With data.txt created like this:

f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()

I get the following output:

61 62 0d 0a 63 64

tl;dr -- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.

===

1. Your variable names are horrendous.

That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:

fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()

xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0

while yxxxxx < xxyxxx:
    xyxxxx = hex(ord(xxxyxx[yxxxxx]))
    xyxxxx = xyxxxx[-2:]
    yxxxxx = yxxxxx + 1
    xxxxxy = chr(13) + chr(10)
    xxxxyx = str(xxxxxy)
    xyxxxxx = str(xyxxxx)
    xyxxxxx.replace(xxxxyx, ' ')
    print xyxxxxx

That program runs fine, but it is impossible to understand.

2. The hex() function produces strings of different lengths.

For instance,

print hex(61)
print hex(15)

--output:--
0x3d
0xf

And taking the slice [-2:] for each of those strings gives you:

3d
xf

See how you got the 'x' in the second one? The slice:

[-2:] 

says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:

[2:]  

3. Your code will never replace any newlines.

Suppose your file has these two consecutive characters:

"\r\n"

Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd", and you slice off the first two characters giving you:

"d"

Next, this line in your code:

bndtx.replace(entx, ' ')

tries to find every occurrence of the string "\r\n" in the string "d" and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d" is one character long.

The replacement won't work for "\r\n" and "0d" either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"? The ascii code for the character "0" is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:

 x = '0d' + '0a'
 x.replace("\r\n", " ")
 print x

 --output:--
 '0d0a'

Nor will this:

x = 'd' + 'a'
x.replace("\r\n", " ")
print x

--output:--
da

The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:

char = "a"
code = ord(char)
hex_str = hex(code)

print char.replace(hex_str, " ")

...you can't expect "a" to be replaced by a space. If you examine the output here:

char = "a"
print repr(char)

code = ord(char)
print repr(code)

hex_str = hex(code)
print repr(hex_str)

print repr(
    char.replace(hex_str, " ")
)

--output:--
'a'
97
'0x61'
'a'

You can see that 'a' is a string with one character in it, and '0x61' is a string with 4 characters in it: '0', 'x', '6', and '1', and you can never find a four character string inside a one character string.

4) Removing newlines can corrupt the data.

For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.

However, if you are writing a program to read only text files, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.

I hope all that's not too confusing.

Why does DEBUG=False setting make my django Static Files Access fail?

If you are using the static serve view in development, you have to have DEBUG = True :

Warning

This will only work if DEBUG is True.

That's because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.

Docs: serving static files in developent

EDIT: You could add some urls just to test your 404 and 500 templates, just use the generic view direct_to_template in your urls.

from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    ('^404testing/$', direct_to_template, {'template': '404.html'})
)

What is Hive: Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

I know I am 3 years late on this thread, however still providing my 2 cents for similar cases in future.

I recently faced the same issue/error in my cluster. The JOB would always get to some 80%+ reduction and fail with the same error, with nothing to go on in the execution logs either. Upon multiple iterations and research I found that among the plethora of files getting loaded some were non-compliant with the structure provided for the base table(table being used to insert data into partitioned table).

Point to be noted here is whenever I executed a select query for a particular value in the partitioning column or created a static partition it worked fine as in that case error records were being skipped.

TL;DR: Check the incoming data/files for inconsistency in the structuring as HIVE follows Schema-On-Read philosophy.

PostgreSQL function for last inserted ID

See the below example

CREATE TABLE users (
    -- make the "id" column a primary key; this also creates
    -- a UNIQUE constraint and a b+-tree index on the column
    id    SERIAL PRIMARY KEY,
    name  TEXT,
    age   INT4
);

INSERT INTO users (name, age) VALUES ('Mozart', 20);

Then for getting last inserted id use this for table "user" seq column name "id"

SELECT currval(pg_get_serial_sequence('users', 'id'));

How can I order a List<string>?

List<string> myCollection = new List<string>()
{
    "Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};

myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
    Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}

output: Abdi 3 Alex 2 Bob 4

List of Java processes

To know the list of java running on the linux machine. ps -e | grep java

Validation to check if password and confirm password are same is not working

function validate()
{
  var a=documents.forms["yourformname"]["yourpasswordfieldname"].value;
  var b=documents.forms["yourformname"]["yourconfirmpasswordfieldname"].value;
  if(!(a==b))
  {
    alert("both passwords are not matching");
    return false;
  }
  return true;
}

Create pandas Dataframe by appending one row at a time

Figured out a simple and nice way:

>>> df
     A  B  C
one  1  2  3
>>> df.loc["two"] = [4,5,6]
>>> df
     A  B  C
one  1  2  3
two  4  5  6

Note the caveat with performance as noted in the comments

Reference - What does this error mean in PHP?

Fatal error: Call to undefined function XXX

Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.

Example 1 - Conditional Function Declaration

$someCondition = false;
if ($someCondition === true) {
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case, fn() will never be declared because $someCondition is not true.

Example 2 - Function in Function Declaration

function createFn() 
{
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case, fn will only be declared once createFn() gets called. Note that subsequent calls to createFn() will trigger an error about Redeclaration of an Existing function.

You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.

In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g. apt in Debian or Ubuntu, yum in Red Hat or CentOS), or a control panel in a shared hosting environment.

If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.

In case of missing includes, make sure to include the file declaring the function before calling the function.

In case of typos, fix the typo.

Related Questions:

Testing javascript with Mocha - how can I use console.log to debug a test?

I had an issue with node.exe programs like test output with mocha.

In my case, I solved it by removing some default "node.exe" alias.

I'm using Git Bash for Windows(2.29.2) and some default aliases are set from /etc/profile.d/aliases.sh,

  # show me alias related to 'node'
  $ alias|grep node
  alias node='winpty node.exe'`

To remove the alias, update aliases.sh or simply do

unalias node

I don't know why winpty has this side effect on console.info buffered output but with a direct node.exe use, I've no more stdout issue.

How to check the maximum number of allowed connections to an Oracle database?

select count(*),sum(decode(status, 'ACTIVE',1,0)) from v$session where type= 'USER'

SQL Bulk Insert with FIRSTROW parameter skips the following line

Given how mangled some data can look after BCP importing into SQL Server from non-SQL data sources, I'd suggest doing all the BCP import into some scratch tables first.

For example

truncate table Address_Import_tbl

BULK INSERT dbo.Address_Import_tbl FROM 'E:\external\SomeDataSource\Address.csv' WITH ( FIELDTERMINATOR = '|', ROWTERMINATOR = '\n', MAXERRORS = 10 )

Make sure all the columns in Address_Import_tbl are nvarchar(), to make it as agnostic as possible, and avoid type conversion errors.

Then apply whatever fixes you need to Address_Import_tbl. Like deleting the unwanted header.

Then run a INSERT SELECT query, to copy from Address_Import_tbl to Address_tbl, along with any datatype conversions you need. For example, to cast imported dates to SQL DATETIME.

Cannot add a project to a Tomcat server in Eclipse

Steps I used to resolve it:

  1. Double click on Tomcat Server in the Servers tab.
  2. In a dropdown next to Runtime Environment:, select Apache Tomcat your version
  3. Click on save.

Now, you should be able to add to server on right click "Add and Remove".

Note: Additionally, when on clear/run, you get an error for multiple instances, open server.xml and ensure that it contains a single instance of each application and not multiple.

How to initialize all the elements of an array to any specific value in java

Evidently you can use Arrays.fill(), The way you have it done also works though.

File upload along with other object in Jersey restful web service

You can access the Image File and data from a form using MULTIPART FORM DATA By using the below code.

@POST
@Path("/UpdateProfile")
@Consumes(value={MediaType.APPLICATION_JSON,MediaType.MULTIPART_FORM_DATA})
@Produces(value={MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response updateProfile(
    @FormDataParam("file") InputStream fileInputStream,
    @FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
    @FormDataParam("ProfileInfo") String ProfileInfo,
    @FormDataParam("registrationId") String registrationId) {

    String filePath= "/filepath/"+contentDispositionHeader.getFileName();

    OutputStream outputStream = null;
    try {
        int read = 0;
        byte[] bytes = new byte[1024];
        outputStream = new FileOutputStream(new File(filePath));

        while ((read = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }

        outputStream.flush();
        outputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) { 
            try {
                outputStream.close();
            } catch(Exception ex) {}
        }
    }
}

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

In your $CATALINA_BASE/conf/context.xml add block below before </Context>

<Resources cachingAllowed="true" cacheMaxSize="100000" />

For more information: http://tomcat.apache.org/tomcat-8.0-doc/config/resources.html

Removing padding gutter from grid columns in Bootstrap 4

Need an edge-to-edge design? Drop the parent .container or .container-fluid.

Still if you need to remove padding from .row and immediate child columns you have to add the class .no-gutters with the code from @Brian above to your own CSS file, actually it's Not 'right out of the box', check here for official details on the final Bootstrap 4 release: https://getbootstrap.com/docs/4.0/layout/grid/#no-gutters

Is there a constraint that restricts my generic method to numeric types?

This limitation affected me when I tried to overload operators for generic types; since there was no "INumeric" constraint, and for a bevy of other reasons the good people on stackoverflow are happy to provide, operations cannot be defined on generic types.

I wanted something like

public struct Foo<T>
{
    public T Value{ get; private set; }

    public static Foo<T> operator +(Foo<T> LHS, Foo<T> RHS)
    {
        return new Foo<T> { Value = LHS.Value + RHS.Value; };
    }
}

I have worked around this issue using .net4 dynamic runtime typing.

public struct Foo<T>
{
    public T Value { get; private set; }

    public static Foo<T> operator +(Foo<T> LHS, Foo<T> RHS)
    {
        return new Foo<T> { Value = LHS.Value + (dynamic)RHS.Value };
    }
}

The two things about using dynamic are

  1. Performance. All value types get boxed.
  2. Runtime errors. You "beat" the compiler, but lose type safety. If the generic type doesn't have the operator defined, an exception will be thrown during execution.

How to handle-escape both single and double quotes in an SQL-Update statement

In C# and VB the SqlCommand object implements the Parameter.AddWithValue method which handles this situation

String escape into XML

public static string XmlEscape(string unescaped)
{
    XmlDocument doc = new XmlDocument();
    XmlNode node = doc.CreateElement("root");
    node.InnerText = unescaped;
    return node.InnerXml;
}

public static string XmlUnescape(string escaped)
{
    XmlDocument doc = new XmlDocument();
    XmlNode node = doc.CreateElement("root");
    node.InnerXml = escaped;
    return node.InnerText;
}

How can I get the current stack trace in Java?

Thread.currentThread().getStackTrace();

is available since JDK1.5.

For an older version, you can redirect exception.printStackTrace() to a StringWriter() :

StringWriter sw = new StringWriter();
new Throwable("").printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();

How do I pass the this context to a function?

You can use the bind function to set the context of this within a function.

function myFunc() {
  console.log(this.str)
}
const myContext = {str: "my context"}
const boundFunc = myFunc.bind(myContext);
boundFunc(); // "my context"

Assigning out/ref parameters in Moq

This can be a solution .

[Test]
public void TestForOutParameterInMoq()
{
  //Arrange
  _mockParameterManager= new Mock<IParameterManager>();

  Mock<IParameter > mockParameter= new Mock<IParameter >();
  //Parameter affectation should be useless but is not. It's really used by Moq 
  IParameter parameter= mockParameter.Object;

  //Mock method used in UpperParameterManager
  _mockParameterManager.Setup(x => x.OutMethod(out parameter));

  //Act with the real instance
  _UpperParameterManager.UpperOutMethod(out parameter);

  //Assert that method used on the out parameter of inner out method are really called
  mockParameter.Verify(x => x.FunctionCalledInOutMethodAfterInnerOutMethod(),Times.Once());

}

Sql select rows containing part of string

You can use the LIKE operator to compare the content of a T-SQL string, e.g.

SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'.

The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".

Matplotlib different size subplots

Another way is to use the subplots function and pass the width ratio with gridspec_kw:

import numpy as np
import matplotlib.pyplot as plt 

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)

f.tight_layout()
f.savefig('grid_figure.pdf')

What does bundle exec rake mean?

This comes up a lot when your gemfile.lock has different versions of the gems installed on your machine. You may get a warning after running rake (or rspec or others) such as:

You have already activated rake 10.3.1, but your Gemfile requires rake 10.1.0. Prepending "bundle exec" to your command may solve this.

Prepending bundle exec tells the bundler to execute this command regardless of the version differential. There isn't always an issue, however, you might run into problems.

Fortunately, there is a gem that solves this: rubygems-bundler.

$ gem install rubygems-bundler

$ $ gem regenerate_binstubs

Then try your rake, rspec, or whatever again.

Disable PHP in directory (including all sub-directories) with .htaccess

If you use php-fpm, the php_admin_value will NOT work and gives an Internal Server Error.

Instead use this in your .htaccess. It disables the parser in that folder and all subfolders:

<FilesMatch ".+\.*$">
    SetHandler !
</FilesMatch>

Python "string_escape" vs "unicode_escape"

According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.

They are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.

Gradle task - pass arguments to Java application

Sorry for answering so late.

I figured an answer alike to @xlm 's:

task run (type: JavaExec, dependsOn: classes){
    if(project.hasProperty('myargs')){
        args(myargs.split(','))
    }
    description = "Secure algorythm testing"
    main = "main.Test"
    classpath = sourceSets.main.runtimeClasspath
}

And invoke like:

gradle run -Pmyargs=-d,s

JUNIT testing void methods

You can learn something called "mocking". You can use this, for example, to check if: - a function was called - a function was called x times - a function was called at least x times - a function was called with a specific set of parameters. In your case, for example, you can use mocking to check that method3 was called once with whatever you pass as arg1 and arg2.

Have a look at these: https://code.google.com/p/mockito/ https://code.google.com/p/powermock/

Convert date time string to epoch in Bash

For Linux Run this command

date -d '06/12/2012 07:21:22' +"%s"

For mac OSX run this command

date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"

How to get store information in Magento?

Just for information sake, in regards to my need... The answer I was looking for here was:

Mage::app()->getStore()->getGroup()->getName()

That is referenced on the admin page, where one can manage multiple stores... admin/system_store, I wanted to retrieve the store group title...

Are there any style options for the HTML5 Date picker?

You can use the following CSS to style the input element.

_x000D_
_x000D_
input[type="date"] {_x000D_
  background-color: red;_x000D_
  outline: none;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-clear-button {_x000D_
  font-size: 18px;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-inner-spin-button {_x000D_
  height: 28px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
  font-size: 15px;_x000D_
}
_x000D_
<input type="date" value="From" name="from" placeholder="From" required="" />
_x000D_
_x000D_
_x000D_

What is the meaning of @_ in Perl?

Never try to edit to @_ variable!!!! They must be not touched.. Or you get some unsuspected effect. For example...

my $size=1234;
sub sub1{
  $_[0]=500;
}
sub1 $size;

Before call sub1 $size contain 1234. But after 500(!!) So you Don't edit this value!!! You may pass two or more values and change them in subroutine and all of them will be changed! I've never seen this effect described. Programs I've seen also leave @_ array readonly. And only that you may safely pass variable don't changed internal subroutine You must always do that:

sub sub2{
  my @m=@_;
  ....
}

assign @_ to local subroutine procedure variables and next worked with them. Also in some deep recursive algorithms that returun array you may use this approach to reduce memory used for local vars. Only if return @_ array the same.

How do I configure Apache 2 to run Perl CGI scripts?

There are two ways to handle CGI scripts, SetHandler and AddHandler.

SetHandler cgi-script

applies to all files in a given context, no matter how they are named, even index.html or style.css.

AddHandler cgi-script .pl

is similar, but applies to files ending in .pl, in a given context. You may choose another extension or several, if you like.

Additionally, the CGI module must be loaded and Options +ExecCGI configured. To activate the module, issue

a2enmod cgi

and restart or reload Apache. Finally, the Perl CGI script must be executable. So the execute bits must be set

chmod a+x script.pl

and it should start with

#! /usr/bin/perl

as its first line.


When you use SetHandler or AddHandler (and Options +ExecCGI) outside of any directive, it is applied globally to all files. But you may restrict the context to a subset by enclosing these directives inside, e.g. Directory

<Directory /path/to/some/cgi-dir>
    SetHandler cgi-script
    Options +ExecCGI
</Directory>

Now SetHandler applies only to the files inside /path/to/some/cgi-dir instead of all files of the web site. Same is with AddHandler inside a Directory or Location directive, of course. It then applies to the files inside /path/to/some/cgi-dir, ending in .pl.

Where can I download english dictionary database in a text format?

The Gutenberg Project hosts Webster's Unabridged English Dictionary plus many other public domain literary works. Actually it looks like they've got several versions of the dictionary hosted with copyright from different years. The one I linked has a 2009 copyright. You may want to poke around the site and investigate the different versions of Webster's dictionary.

Rounding a double to turn it into an int (java)

import java.math.*;
public class TestRound11 {
  public static void main(String args[]){
    double d = 3.1537;
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
    // output is 3.15
    System.out.println(d + " : " + round(d, 2));
    // output is 3.154
    System.out.println(d + " : " + round(d, 3));
  }

  public static double round(double d, int decimalPlace){
    // see the Javadoc about why we use a String in the constructor
    // http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
    BigDecimal bd = new BigDecimal(Double.toString(d));
    bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
    return bd.doubleValue();
  }
}

How to split a python string on new line characters

? Splitting line in Python:

Have you tried using str.splitlines() method?:

From the docs:

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']

Which delimiters are considered?

This method uses the universal newlines approach to splitting lines.

The main difference between Python 2.X and Python 3.X is that the former uses the universal newlines approach to splitting lines, so "\r", "\n", and "\r\n" are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:

  • \v or \x0b: Line Tabulation (added in Python 3.2).
  • \f or \x0c: Form Feed (added in Python 3.2).
  • \x1c: File Separator.
  • \x1d: Group Separator.
  • \x1e: Record Separator.
  • \x85: Next Line (C1 Control Code).
  • \u2028: Line Separator.
  • \u2029: Paragraph Separator.

splitlines VS split:

Unlike str.split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> ''.splitlines()
[]

>>> 'Line 1\n'.splitlines()
['Line 1']

While str.split('\n') returns:

>>> ''.split('\n')
['']

>>> 'Line 1\n'.split('\n')
['Line 1', '']

?? Removing additional whitespace:

If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines(), you could use str.splitlines() together with str.strip():

>>> [str.strip() for str in 'Line 1  \n  \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']

? Removing empty strings (''):

Lastly, if you want to filter out the empty strings from the resulting list, you could use filter():

>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']

>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']

Additional comment regarding the original question:

As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

What underlies this JavaScript idiom: var self = this?

As others have explained, var self = this; allows code in a closure to refer back to the parent scope.

However, it's now 2018 and ES6 is widely supported by all major web browsers. The var self = this; idiom isn't quite as essential as it once was.

It's now possible to avoid var self = this; through the use of arrow functions.

In instances where we would have used var self = this:

function test() {
    var self = this;
    this.hello = "world";
    document.getElementById("test_btn").addEventListener("click", function() {
        console.log(self.hello); // logs "world"
    });
};

We can now use an arrow function without var self = this:

function test() {
    this.hello = "world";
    document.getElementById("test_btn").addEventListener("click", () => {
        console.log(this.hello); // logs "world"
    });
};

Arrow functions do not have their own this and simply assume the enclosing scope.

Javascript, Change google map marker color

var map_marker = $(".map-marker").children("img").attr("src") var pinImage = new google.maps.MarkerImage(map_marker);

     var marker = new google.maps.Marker({
      position: uluru,
      map: map,
      icon: pinImage
    });
  }

Good examples of python-memcache (memcached) being used in Python?

I would advise you to use pylibmc instead.

It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it here.

And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming.

How to determine MIME type of file in android?

I faced similar problem. So far I know result may different for different names, so finally came to this solution.

public String getMimeType(String filePath) {
    String type = null;
    String extension = null;
    int i = filePath.lastIndexOf('.');
    if (i > 0)
        extension = filePath.substring(i+1);
    if (extension != null)
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    return type;
}  

How to set multiple commands in one yaml file with Kubernetes?

IMHO the best option is to use YAML's native block scalars. Specifically in this case, the folded style block.

By invoking sh -c you can pass arguments to your container as commands, but if you want to elegantly separate them with newlines, you'd want to use the folded style block, so that YAML will know to convert newlines to whitespaces, effectively concatenating the commands.

A full working example:

apiVersion: v1
kind: Pod
metadata:
  name: myapp
  labels:
    app: myapp
spec:
  containers:
  - name: busy
    image: busybox:1.28
    command: ["/bin/sh", "-c"]
    args:
    - >
      command_1 &&
      command_2 &&
      ... 
      command_n

Questions every good PHP Developer should be able to answer

Explain why the following code displays 2.5 instead of 3:

$a = 012;
echo $a / 4;

Answer: When a number is preceded by a 0 in PHP, the number is treated as an octal number (base-8). Therefore the octal number 012 is equal to the decimal number 10.

Android refresh current activity

I think that the best choice for you is using SwipeRefreshLayout View in your layout. Then set RefreshListener like.

mySwipeRefreshLayout.setOnRefreshListener(
            new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    Log.i("Fav ", "onRefresh called from SwipeRefreshLayout");

                    // This method performs the actual data-refresh operation.
                    // The method calls setRefreshing(false) when it's finished.
                    request();  // call what you want to update in this method
                    mySwipeRefreshLayout.setRefreshing(false);
                }
            }
    );

For more details click this link

Convert date to another timezone in JavaScript

Got it !

Wanted to force the date shown = server date, no mattter the local settings (UTC).

My server is GMT-6 --> new Date().getTimezoneOffset() = 360.

myTZO = 360;
myNewDate=new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
alert(myNewDate);

converting CSV/XLS to JSON?

Take a try on the tiny free tool:

http://keyangxiang.com/csvtojson/

It utilises node.js csvtojson module

How to print the contents of RDD?

If you're running this on a cluster then println won't print back to your context. You need to bring the RDD data to your session. To do this you can force it to local array and then print it out:

linesWithSessionId.toArray().foreach(line => println(line))

Unable to launch the IIS Express Web server

In my situation, the IIS Express applicationhost.config file had a typo in the managedRuntimeVersion attribute of several elements. This was happening for both Visual Studio 2012 and Visual Studio 2013. I only received the first part of the message, stating:

Unable to launch the IIS Express Web server.

It logged an error in the event log with the message:

The worker process failed to pre-load .Net Runtime version v4.030319.

The correct runtime version is v4.0.30319 (note the second period.)

The steps I took to correct:

  1. Navigate to C:\Users\\Documents\IISExpress\config
  2. Edit applicationhost.config
  3. Find the config section
  4. Correct any references to "v4.030319" to read "v4.0.30319"

Visual Studio successfully started IIS Express the next time I debugged a web application.

Batch program to to check if process exists

TASKLIST doesn't set an exit code that you could check in a batch file. One workaround to checking the exit code could be parsing its standard output (which you are presently redirecting to NUL). Apparently, if the process is found, TASKLIST will display its details, which include the image name too. Therefore, you could just use FIND or FINDSTR to check if the TASKLIST's output contains the name you have specified in the request. Both FIND and FINDSTR set a non-null exit code if the search was unsuccessful. So, this would work:

@echo off
tasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nul
if not errorlevel 1 (taskkill /f /im "notepad.exe") else (
  specific commands to perform if the process was not found
)
exit

There's also an alternative that doesn't involve TASKLIST at all. Unlike TASKLIST, TASKKILL does set an exit code. In particular, if it couldn't terminate a process because it simply didn't exist, it would set the exit code of 128. You could check for that code to perform your specific actions that you might need to perform in case the specified process didn't exist:

@echo off
taskkill /f /im "notepad.exe" > nul
if errorlevel 128 (
  specific commands to perform if the process
  was not terminated because it was not found
)
exit

adding classpath in linux

It's always advised to never destructively destroy an existing classpath unless you have a good reason.

The following line preserves the existing classpath and adds onto it.

export CLASSPATH="$CLASSPATH:foo.jar:../bar.jar"

How to find third or n?? maximum salary from salary table?

Third or nth maximum salary from salary table without using subquery

select salary from salary
   ORDER   BY salary DESC
   OFFSET  N-1 ROWS
   FETCH NEXT 1 ROWS ONLY

For 3rd highest salary put 2 in place of N-1

Speed up rsync with Simultaneous/Concurrent File Transfers?

Updated answer (Jan 2020)

xargs is now the recommended tool to achieve parallel execution. It's pre-installed almost everywhere. For running multiple rsync tasks the command would be:

ls /srv/mail | xargs -n1 -P4 -I% rsync -Pa % myserver.com:/srv/mail/

This will list all folders in /srv/mail, pipe them to xargs, which will read them one-by-one and and run 4 rsync processes at a time. The % char replaces the input argument for each command call.

Original answer using parallel:

ls /srv/mail | parallel -v -j8 rsync -raz --progress {} myserver.com:/srv/mail/{}

How can we stop a running java process through Windows cmd?

I like this one.

wmic process where "name like '%java%'" delete

You can actually kill a process on a remote machine the same way.

wmic /node:computername /user:adminuser /password:password process where "name like '%java%'" delete

wmic is awesome!

Add data dynamically to an Array

Let's say you have defined an empty array:

$myArr = array();

If you want to simply add an element, e.g. 'New Element to Array', write

$myArr[] = 'New Element to Array';

if you are calling the data from the database, below code will work fine

$sql = "SELECT $element FROM $table";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)//if it finds any row
{
   while($result = mysql_fetch_object($query))
   {
      //adding data to the array
      $myArr[] = $result->$element;
   }
}

ERROR in ./node_modules/css-loader?

you have to update your node.js and angular/cli.If you update these two things then your project has angular.json file instead of angular-cli.json file.Then add css file into angular.json file.If you add css file into angular-cli.json file instead of angular.json file,then errors are occured.

How do you implement a good profanity filter?

Don't.

Because:

  • Clbuttic
  • Profanity is not OMG EVIL
  • Profanity cannot be effectively defined
  • Most people quite probably don't appreciate being "protected" from profanity

Edit: While I agree with the commenter who said "censorship is wrong", that is not the nature of this answer.

Using an array as needles in strpos

I'm writing a new answer which hopefully helps anyone looking for similar to what I am.

This works in the case of "I have multiple needles and I'm trying to use them to find a singled-out string". and this is the question I came across to find that.

    $i = 0;
    $found = array();
    while ($i < count($needle)) {
        $x = 0;
        while ($x < count($haystack)) {
            if (strpos($haystack[$x], $needle[$i]) !== false) {
                array_push($found, $haystack[$x]);
            }
            $x++;
        }
        $i++;
    }

    $found = array_count_values($found);

The array $found will contain a list of all the matching needles, the item of the array with the highest count value will be the string(s) you're looking for, you can get this with:

print_r(array_search(max($found), $found));

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

Get all column names of a DataTable into string array using (LINQ/Predicate)

Use

var arrayNames = (from DataColumn x in dt.Columns
                  select x.ColumnName).ToArray();

Disable pasting text into HTML form

Just got this, we can achieve it using onpaste:"return false", thanks to: http://sumtips.com/2011/11/prevent-copy-cut-paste-text-field.html

We have various other options available as listed below.

<input type="text" onselectstart="return false" onpaste="return false;" onCopy="return false" onCut="return false" onDrag="return false" onDrop="return false" autocomplete=off/><br>

nodejs vs node on ubuntu 12.04

Apparently the solution differs between Ubuntu versions. Following worked for me on Ubuntu 13.10:

sudo apt-get install nodejs-legacy

HTH

Edit: Rule of thumb:

If you have installed nodejs but are missing the /usr/bin/node binary, then also install nodejs-legacy. This just creates the missing softlink.

According to my tests, Ubuntu 17.10 and above already have the compatibility-softlink /usr/bin/node in place after nodejs is installed, so nodejs-legacy is missing from these releases as it is no more needed.

How to quickly and conveniently disable all console.log statements in my code?

One liner just set devMode true/false;

console.log = devMode ? console.log : () => { };

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

I use this:

@var.respond_to?(:keys)

It works for Hash and ActiveSupport::HashWithIndifferentAccess.

How to get file creation date/time in Bash/Debian?

You can find creation time - aka birth time - using stat and also match using find.
We have these files showing last modified time:

$ ls -l --time-style=long-iso | sort -k6
total 692
-rwxrwx---+ 1 XXXX XXXX 249159 2013-05-31 14:47 Getting Started.pdf
-rwxrwx---+ 1 XXXX XXXX 275799 2013-12-30 21:12 TheScienceofGettingRich.pdf
-rwxrwx---+ 1 XXXX XXXX  25600 2015-05-07 18:52 Thumbs.db
-rwxrwx---+ 1 XXXX XXXX 148051 2015-05-07 18:55 AsAManThinketh.pdf

To find files created within a certain time frame using find as below.
Clearly, the filesystem knows about the birth time of a file:

$ find -newerBt '2014-06-13' ! -newerBt '2014-06-13 12:16:10' -ls 
20547673299906851  148 -rwxrwx---   1 XXXX XXXX   148051 May  7 18:55 ./AsAManThinketh.pdf
1407374883582246  244 -rwxrwx---   1 XXXX XXXX   249159 May 31  2013 ./Getting\ Started.pdf


We can confirm this using stat:

$ stat -c "%w %n" * | sort
2014-06-13 12:16:03.873778400 +0100 AsAManThinketh.pdf
2014-06-13 12:16:04.006872500 +0100 Getting Started.pdf
2014-06-13 12:16:29.607075500 +0100 TheScienceofGettingRich.pdf
2015-05-07 18:32:26.938446200 +0100 Thumbs.db


stat man pages explains %w:

%w     time of file birth, human-readable; - if unknown

How to send a POST request from node.js Express?

As described here for a post request :

var http = require('http');

var options = {
  host: 'www.host.com',
  path: '/',
  port: '80',
  method: 'POST'
};

callback = function(response) {
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();

How do I put text on ProgressBar?

You will have to override the OnPaint method, call the base implementation and the paint your own text.

You will need to create your own CustomProgressBar and then override OnPaint to draw what ever text you want.

Custom Progress Bar Class

namespace ProgressBarSample
{

public enum ProgressBarDisplayText
{
    Percentage,
    CustomText
}

class CustomProgressBar: ProgressBar
{
    //Property to set to decide whether to print a % or Text
    public ProgressBarDisplayText DisplayStyle { get; set; }

    //Property to hold the custom text
    public String CustomText { get; set; }

    public CustomProgressBar()
    {
        // Modify the ControlStyles flags
        //http://msdn.microsoft.com/en-us/library/system.windows.forms.controlstyles.aspx
        SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Rectangle rect = ClientRectangle;
        Graphics g = e.Graphics;

        ProgressBarRenderer.DrawHorizontalBar(g, rect);
        rect.Inflate(-3, -3);
        if (Value > 0)
        {
            // As we doing this ourselves we need to draw the chunks on the progress bar
            Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)Value / Maximum) * rect.Width), rect.Height);
            ProgressBarRenderer.DrawHorizontalChunks(g, clip);
        }

        // Set the Display text (Either a % amount or our custom text
        string text = DisplayStyle == ProgressBarDisplayText.Percentage ? Value.ToString() + '%' : CustomText;


        using (Font f = new Font(FontFamily.GenericSerif, 10))
        {

            SizeF len = g.MeasureString(text, f);
            // Calculate the location of the text (the middle of progress bar)
            // Point location = new Point(Convert.ToInt32((rect.Width / 2) - (len.Width / 2)), Convert.ToInt32((rect.Height / 2) - (len.Height / 2)));
            Point location = new Point(Convert.ToInt32((Width / 2) - len.Width / 2), Convert.ToInt32((Height / 2) - len.Height / 2)); 
            // The commented-out code will centre the text into the highlighted area only. This will centre the text regardless of the highlighted area.
            // Draw the custom text
            g.DrawString(text, f, Brushes.Red, location);
        }
    }
}
}

Sample WinForms Application

using System;
using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;

namespace ProgressBarSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // Set our custom Style (% or text)
            customProgressBar1.DisplayStyle = ProgressBarDisplayText.CustomText;
            customProgressBar1.CustomText = "Initialising";
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            customProgressBar1.Value = 0;
            btnStart.Enabled = true;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            btnReset.Enabled = false;
            btnStart.Enabled = false;

            for (int i = 0; i < 101; i++)
            {

                customProgressBar1.Value = i;
                // Demo purposes only
                System.Threading.Thread.Sleep(100);

                // Set the custom text at different intervals for demo purposes
                if (i > 30 && i < 50)
                {
                    customProgressBar1.CustomText = "Registering Account";
                }

                if (i > 80)
                {
                    customProgressBar1.CustomText = "Processing almost complete!";
                }

                if (i >= 99)
                {
                    customProgressBar1.CustomText = "Complete";
                }
            }

            btnReset.Enabled = true;


        }


    }
}

Append same text to every cell in a column in Excel

Type it in one cell, copy that cell, select all the cells you want to fill, and paste.

Alternatively, type it in one cell, select the black square in the bottom-right of that cell, and drag down.

set option "selected" attribute from dynamic created option

You could search all the option values until it finds the correct one.

var defaultVal = "Country";
$("#select").find("option").each(function () {

    if ($(this).val() == defaultVal) {

        $(this).prop("selected", "selected");
    }
});

How do I install SciPy on 64 bit Windows?

I haven't tried it, but you may want to download this version of Portable Python. It comes with Scipy-0.7.0b1 running on Python 2.5.4.

HTML Table cellspacing or padding just top / bottom

Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top, padding-bottom, padding-left, and padding-right; or padding: [top] [right] [bottom] [left];).

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

If you are running multiple extensions that perform ad or script blocking you will need to

individually update each one to your whitelist

Taking from this source, here are some of the extensions that may cause the case and how to deal with them.

Adblock Plus

  • Click the Adblock Plus icon.
  • Click “Enabled on this site” to disable ad blocking for the current site.
  • In Firefox Click “disable on wired.com” to disable ad blocking.
  • Reload the page you were viewing.
  • If problem still persist, cek if the character string "-300x600" is in the file name, that particular text pattern matches an expression list pattern in the AdBlock Plus.

Firefox Tracking Protection

  • In Firefox “Tracking Protection” may activate our adblock notice. It can be temporarily disabled for a browsing session by clicking the “shield” icon in the url bar if visible and following the instructions.

  • For further details on Tracking Protection please review Mozilla’s support.

Adblock

  • Click the Ad Block icon.
  • Click “Don’t run on pages on this domain”.
  • Reload the page you were viewing.

Ghostery

  • Click the Ghostery icon.
  • In Ghostery versions < 6.0 Click “Whitelist site”.
  • In Ghostery version 7.0 click “trust site”
  • In Versions < 6.0 You will see the message “Site is whitelisted”. Click “reload the page to see your changes.”
  • Reload the page you were viewing.

uBlock / uBlock Origin

  • Click the uBlock / uBlock Origin icon.

  • Click the “power” button in the menu that appears to whitelist the current web site.

  • Click the reload icon to reload the page you were viewing.

Disconnect

  • Click the Disconnect icon.
  • Click “Whitelist site”.

Kaspersky Ant-Banner
Please review How to configure Anti-Banner in Kaspersky Total Security for information on how to whitelist with Kaspersky Total Security.

TypeError: document.getElementbyId is not a function

JavaScript is case-sensitive. The b in getElementbyId should be capitalized.

var content = document.getElementById("edit").innerHTML;

Finding rows containing a value (or values) in any column

How about

apply(df, 1, function(r) any(r %in% c("M017", "M018")))

The ith element will be TRUE if the ith row contains one of the values, and FALSE otherwise. Or, if you want just the row numbers, enclose the above statement in which(...).

Install dependencies globally and locally using package.json

Due to the disadvantages described below, I would recommend following the accepted answer:

Use npm install --save-dev [package_name] then execute scripts with:

$ npm run lint
$ npm run build
$ npm test

My original but not recommended answer follows.


Instead of using a global install, you could add the package to your devDependencies (--save-dev) and then run the binary from anywhere inside your project:

"$(npm bin)/<executable_name>" <arguments>...

In your case:

"$(npm bin)"/node.io --help

This engineer provided an npm-exec alias as a shortcut. This engineer uses a shellscript called env.sh. But I prefer to use $(npm bin) directly, to avoid any extra file or setup.

Although it makes each call a little larger, it should just work, preventing:

  • potential dependency conflicts with global packages (@nalply)
  • the need for sudo
  • the need to set up an npm prefix (although I recommend using one anyway)

Disadvantages:

  • $(npm bin) won't work on Windows.
  • Tools deeper in your dev tree will not appear in the npm bin folder. (Install npm-run or npm-which to find them.)

It seems a better solution is to place common tasks (such as building and minifying) in the "scripts" section of your package.json, as Jason demonstrates above.

How to get the first five character of a String

In C# 8.0 you can get the first five characters of a string like so

string str = data[0..5];

Here is some more information about Indices And Ranges

Java ElasticSearch None of the configured nodes are available

Faced similar issue, and here is the solution

Example :

  1. In elasticsearch.yml add the below properties

    cluster.name: production
    node.name: node1
    network.bind_host: 10.0.1.22
    network.host: 0.0.0.0
    transport.tcp.port: 9300
    
  2. Add the following in Java Elastic API for Bulk Push (just a code snippet). For IP Address add public IP address of elastic search machine

    Client client;
    BulkRequestBuilder requestBuilder;
    try {
        client = TransportClient.builder().settings(Settings.builder().put("cluster.name", "production").put("node.name","node1")).build().addTransportAddress(
        new InetSocketTransportAddress(InetAddress.getByName(""), 9300));
        requestBuilder = (client).prepareBulk();
    } 
    catch (Exception e) {
    }
    
  3. Open the Firewall ports for 9200,9300

ISO C90 forbids mixed declarations and code in C

Make sure the variable is on the top part of the block, and in case you compile it with -ansi-pedantic, make sure it looks like this:

function() {
    int i;
    i = 0;

    someCode();
}

How to post JSON to a server using C#?

Some different and clean way to achieve this is by using HttpClient like this:

public async Task<HttpResponseMessage> PostResult(string url, ResultObject resultObject)
{
    using (var client = new HttpClient())
    {
        HttpResponseMessage response = new HttpResponseMessage();
        try
        {
            response = await client.PostAsJsonAsync(url, resultObject);
        }
        catch (Exception ex)
        {
            throw ex
        }
        return response;
     }
}

C++ passing an array pointer as a function argument

int *a[], when used as a function parameter (but not in normal declarations), is a pointer to a pointer, not a pointer to an array (in normal declarations, it is an array of pointers). A pointer to an array looks like this:

int (*aptr)[N]

Where N is a particular positive integer (not a variable).

If you make your function a template, you can do it and you don't even need to pass the size of the array (because it is automatically deduced):

template<size_t SZ>
void generateArray(int (*aptr)[SZ])
{
    for (size_t i=0; i<SZ; ++i)
        (*aptr)[i] = rand() % 9;
}

int main()
{    
    int a[5];    
    generateArray(&a);
}

You could also take a reference:

template<size_t SZ>
void generateArray(int (&arr)[SZ])
{
    for (size_t i=0; i<SZ; ++i)
        arr[i] = rand() % 9;
}

int main()
{    
    int a[5];    
    generateArray(a);
}

Map over object preserving keys

With Underscore

Underscore provides a function _.mapObject to map the values and preserve the keys.

_.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

// => { one: 3, two: 6, three: 9 }

DEMO


With Lodash

Lodash provides a function _.mapValues to map the values and preserve the keys.

_.mapValues({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

// => { one: 3, two: 6, three: 9 }

DEMO

Get List of connected USB Devices

To see the devices I was interested in, I had replace Win32_USBHub by Win32_PnPEntity in Adel Hazzah's code, based on this post. This works for me:

namespace ConsoleApplication1
{
  using System;
  using System.Collections.Generic;
  using System.Management; // need to add System.Management to your project references.

  class Program
  {
    static void Main(string[] args)
    {
      var usbDevices = GetUSBDevices();

      foreach (var usbDevice in usbDevices)
      {
        Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
            usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
      }

      Console.Read();
    }

    static List<USBDeviceInfo> GetUSBDevices()
    {
      List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

      ManagementObjectCollection collection;
      using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
        collection = searcher.Get();      

      foreach (var device in collection)
      {
        devices.Add(new USBDeviceInfo(
        (string)device.GetPropertyValue("DeviceID"),
        (string)device.GetPropertyValue("PNPDeviceID"),
        (string)device.GetPropertyValue("Description")
        ));
      }

      collection.Dispose();
      return devices;
    }
  }

  class USBDeviceInfo
  {
    public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
    {
      this.DeviceID = deviceID;
      this.PnpDeviceID = pnpDeviceID;
      this.Description = description;
    }
    public string DeviceID { get; private set; }
    public string PnpDeviceID { get; private set; }
    public string Description { get; private set; }
  }
}

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.

If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.

For more info on these techniques, please click here to refer the article

Remove innerHTML from div

you should be able to just overwrite it without removing previous data

Changing MongoDB data store directory

In debian/ubuntu, you'll need to edit the /etc/init.d/mongodb script. Really, this file should be pulling the settings from /etc/mongodb.conf but it doesn't seem to pull the default directory (probably a bug)

This is a bit of a hack, but adding these to the script made it start correctly:

add:

DBDIR=/database/mongodb

change:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --config $CONF run"}

to:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --dbpath $DBDIR --config $CONF run"}

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

How do I determine scrollHeight?

scrollHeight is a regular javascript property so you don't need jQuery.

var test = document.getElementById("foo").scrollHeight;

How do I access refs of a child component in the parent component

  1. Inside the child component add a ref to the node you need
  2. Inside the parent component add a ref to the child component.
/*
* Child component
*/
class Child extends React.Component {
  render() {
    return (
      <div id="child">
        <h1 ref={(node) => { this.heading = node; }}>
          Child
        </h1>
      </div>
    );
  }
}

/*
 * Parent component
 */
class Parent extends React.Component {
  componentDidMount() {
    // Access child component refs via parent component instance like this
    console.log(this.child.heading.getDOMNode());
  }

  render() {
    return (
      <div>
        <Child
          ref={(node) => { this.child = node; }}
        />
      </div>
    );
  }
}

Demo: https://codepen.io/itsfadnis/pen/aLWVVx?editors=0011

How do I get rid of the b-prefix in a string in python?

Assuming you don't want to immediately decode it again like others are suggesting here, you can parse it to a string and then just strip the leading 'b and trailing '.

>>> x = "Hi there " 
>>> x = "Hi there ".encode("utf-8") 
>>> x
b"Hi there \xef\xbf\xbd"
>>> str(x)[2:-1]
"Hi there \\xef\\xbf\\xbd"   

How to get a list of MySQL views?

SHOW FULL TABLES IN database_name WHERE TABLE_TYPE LIKE 'VIEW';

MySQL query to find all views in a database

How to reject in async/await syntax?

A better way to write the async function would be by returning a pending Promise from the start and then handling both rejections and resolutions within the callback of the promise, rather than just spitting out a rejected promise on error. Example:

async foo(id: string): Promise<A> {
    return new Promise(function(resolve, reject) {
        // execute some code here
        if (success) { // let's say this is a boolean value from line above
            return resolve(success);
        } else {
            return reject(error); // this can be anything, preferably an Error object to catch the stacktrace from this function
        }
    });
}

Then you just chain methods on the returned promise:

async function bar () {
    try {
        var result = await foo("someID")
        // use the result here
    } catch (error) {
        // handle error here
    }
}

bar()

Source - this tutorial:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

How to increase maximum execution time in php

ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
ini_set('max_execution_time', '0'); // for infinite time of execution 

Place this at the top of your PHP script and let your script loose!

Taken from Increase PHP Script Execution Time Limit Using ini_set()

Get Table and Index storage size in sql server

with pages as (
    SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
            SUM (case 
                    when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
                    else lob_used_page_count + row_overflow_used_page_count
                 end) as pages
    FROM sys.dm_db_partition_stats
    group by object_id
), extra as (
    SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
    FROM sys.dm_db_partition_stats p, sys.internal_tables it
    WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
    group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
        pages * 8 as data_kb,
        (CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
        (CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id

Takes into account internal tables, such as those used for XML storage.

Edit: If you divide the data_kb and index_kb values by 1024.0, you will get the numbers you see in the GUI.

How to find the extension of a file in C#?

EndsWith()

Found an alternate solution over at DotNetPerls that I liked better because it doesn't require you to specify a path. Here's an example where I populated an array with the help of a custom method

        // This custom method takes a path 
        // and adds all files and folder names to the 'files' array
        string[] files = Utilities.FileList("C:\", "");
        // Then for each array item...
        foreach (string f in files)
        {
            // Here is the important line I used to ommit .DLL files:
            if (!f.EndsWith(".dll", StringComparison.Ordinal))
                // then populated a listBox with the array contents
                myListBox.Items.Add(f);
        }

Amazon S3 direct file upload from client browser - private key disclosure

If you don't have any server side code, you security depends on the security of the access to your JavaScript code on the client side (ie everybody who has the code could upload something).

So I would recommend, to simply create a special S3 bucket which is public writeable (but not readable), so you don't need any signed components on the client side.

The bucket name (a GUID eg) will be your only defense against malicious uploads (but a potential attacker could not use your bucket to transfer data, because it is write only to him)

Compare two objects' properties to find differences?

Compare NET Objects can help you!

CompareLogic logic = new CompareLogic();
var compare = logic.Compare(obj1, obj2);
comparacao.Differences.ForEach(diff => Debug.Write(diff.PropertyName));
// Or formatted summary
Debug.Write(comparacao.DifferencesString);

adb uninstall failed

It can be something as simple as typing the package name in the wrong case...

I had the same problem - turned out I was entering the package name in all lower case when the actual package name included upper case characters.

adb uninstall -k <packageName - eg. com.test.app>

( If you're explicitly uninstalling you probably don't want the -k which keeps the app data and cache directories around. )

Storing Python dictionaries

My use case was to save multiple JSON objects to a file and marty's answer helped me somewhat. But to serve my use case, the answer was not complete as it would overwrite the old data every time a new entry was saved.

To save multiple entries in a file, one must check for the old content (i.e., read before write). A typical file holding JSON data will either have a list or an object as root. So I considered that my JSON file always has a list of objects and every time I add data to it, I simply load the list first, append my new data in it, and dump it back to a writable-only instance of file (w):

def saveJson(url,sc): # This function writes the two values to the file
    newdata = {'url':url,'sc':sc}
    json_path = "db/file.json"

    old_list= []
    with open(json_path) as myfile:  # Read the contents first
        old_list = json.load(myfile)
    old_list.append(newdata)

    with open(json_path,"w") as myfile:  # Overwrite the whole content
        json.dump(old_list, myfile, sort_keys=True, indent=4)

    return "success"

The new JSON file will look something like this:

[
    {
        "sc": "a11",
        "url": "www.google.com"
    },
    {
        "sc": "a12",
        "url": "www.google.com"
    },
    {
        "sc": "a13",
        "url": "www.google.com"
    }
]

NOTE: It is essential to have a file named file.json with [] as initial data for this approach to work

PS: not related to original question, but this approach could also be further improved by first checking if our entry already exists (based on one or multiple keys) and only then append and save the data.

How many values can be represented with n bits?

What you're missing: Zero is a value

Iterate over the lines of a string

You can iterate over "a file", which produces lines, including the trailing newline character. To make a "virtual file" out of a string, you can use StringIO:

import io  # for Py2.7 that would be import cStringIO as io

for line in io.StringIO(foo):
    print(repr(line))

How can I specify a branch/tag when adding a Git submodule?

Note: Git 1.8.2 added the possibility to track branches. See some of the answers below.


It's a little confusing to get used to this, but submodules are not on a branch. They are, like you say, just a pointer to a particular commit of the submodule's repository.

This means, when someone else checks out your repository, or pulls your code, and does git submodule update, the submodule is checked out to that particular commit.

This is great for a submodule that does not change often, because then everyone on the project can have the submodule at the same commit.

If you want to move the submodule to a particular tag:

cd submodule_directory
git checkout v1.0
cd ..
git add submodule_directory
git commit -m "moved submodule to v1.0"
git push

Then, another developer who wants to have submodule_directory changed to that tag, does this

git pull
git submodule update --init

git pull changes which commit their submodule directory points to. git submodule update actually merges in the new code.

Read file data without saving it in Flask

In case we want to dump the in memory file to disk. This code can be used

  if isinstanceof(obj,SpooledTemporaryFile):
    obj.rollover()

How to stretch the background image to fill a div

For this you can use CSS3 background-size property. Write like this:

#div2{
    background-image:url(http://s7.static.hootsuite.com/3-0-48/images/themes/classic/streams/message-gradient.png);
    -moz-background-size:100% 100%;
    -webkit-background-size:100% 100%;
    background-size:100% 100%;
    height:180px;
    width:200px;
    border: 1px solid red;
}

Check this: http://jsfiddle.net/qdzaw/1/

How to remove all CSS classes using jQuery/JavaScript?

You can just try

$(document).ready(function() {
   $('body').find('#item').removeClass();
});

If you have to access to that element without class name, for example you have to add a new class name, you can do that:

$(document).ready(function() {
   $('body').find('#item').removeClass().addClass('class-name');
});

I use that function in my projet to remove and add class in a html builder. Good luck.

PHP: How to remove all non printable characters in a string?

you can use character classes

/[[:cntrl:]]+/

Android Google Maps API V2 Zoom to Current Location

try this code :

private GoogleMap mMap;


LocationManager locationManager;


private static final String TAG = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(map);
    mapFragment.getMapAsync(this);

    arrayPoints = new ArrayList<LatLng>();
}

@Override
public void onMapReady(GoogleMap googleMap) {


    mMap = googleMap;


    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);


    LatLng myPosition;


    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    googleMap.setMyLocationEnabled(true);
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);


    if (location != null) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        myPosition = new LatLng(latitude, longitude);


        LatLng coordinate = new LatLng(latitude, longitude);
        CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 19);
        mMap.animateCamera(yourLocation);
    }
}

}

Dont forget to add permissions on AndroidManifest.xml.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

How to filter rows containing a string pattern from a Pandas dataframe

In [3]: df[df['ids'].str.contains("ball")]
Out[3]:
     ids  vals
0  aball     1
1  bball     2
3  fball     4

Import Script from a Parent Directory

From the docs:

from .. import scriptA

You can do this in packages, but not in scripts you run directly. From the link above:

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports.

If you create a script that imports A.B.B, you won't receive the ValueError.

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

Xampp-mysql - "Table doesn't exist in engine" #1932

If you have copied & Pasted files from an old backup folder to new then its simple. Just copy the old ibdata1 into your new one. You can find it from \xampp\mysql\data

Most efficient way to find smallest of 3 numbers Java?

Math.min uses a simple comparison to do its thing. The only advantage to not using Math.min is to save the extra function calls, but that is a negligible saving.

If you have more than just three numbers, having a minimum method for any number of doubles might be valuable and would look something like:

public static double min(double ... numbers) {
    double min = numbers[0];
    for (int i=1 ; i<numbers.length ; i++) {
        min = (min <= numbers[i]) ? min : numbers[i];
    }
    return min;
}

For three numbers this is the functional equivalent of Math.min(a, Math.min(b, c)); but you save one method invocation.

How to save a base64 image to user's disk using JavaScript?

In JavaScript you cannot have the direct access to the filesystem. However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":

"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");

Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:

Probably, you will find them useful in a way...


Here is a refactored version of what I understand you need:

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', () => {_x000D_
  const img = document.getElementById('embedImage');_x000D_
  img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
    'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
    '9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
  img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
  _x000D_
  const button = document.getElementById('saveImage');_x000D_
  button.addEventListener('click', () => {_x000D_
    window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <img id="embedImage" alt="Red dot" />_x000D_
  <button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Webpack how to build production code and how to use it

In addition to Gilson PJ answer:

 new webpack.optimize.CommonsChunkPlugin('common.js'),
 new webpack.optimize.DedupePlugin(),
 new webpack.optimize.UglifyJsPlugin(),
 new webpack.optimize.AggressiveMergingPlugin()

with

"scripts": {
    "build": "NODE_ENV=production webpack -p --config ./webpack.production.config.js"
},

cause that the it tries to uglify your code twice. See https://webpack.github.io/docs/cli.html#production-shortcut-p for more information.

You can fix this by removing the UglifyJsPlugin from plugins-array or add the OccurrenceOrderPlugin and remove the "-p"-flag. so one possible solution would be

 new webpack.optimize.CommonsChunkPlugin('common.js'),
 new webpack.optimize.DedupePlugin(),
 new webpack.optimize.UglifyJsPlugin(),
 new webpack.optimize.OccurrenceOrderPlugin(),
 new webpack.optimize.AggressiveMergingPlugin()

and

"scripts": {
    "build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},

How does one output bold text in Bash?

In theory like so:

# BOLD
$ echo -e "\033[1mThis is a BOLD line\033[0m"
This is a BOLD line

# Using tput
tput bold 
echo "This" #BOLD
tput sgr0 #Reset text attributes to normal without clear.
echo "This" #NORMAL

# UNDERLINE
$ echo -e "\033[4mThis is a underlined line.\033[0m"
This is a underlined line. 

But in practice it may be interpreted as "high intensity" color instead.

(source: http://unstableme.blogspot.com/2008/01/ansi-escape-sequences-for-writing-text.html)

Force add despite the .gitignore file

See man git-add:

   -f, --force
       Allow adding otherwise ignored files.

So run this

git add --force my/ignore/file.foo

Oracle date function for the previous month

Data for last month-

select count(distinct switch_id)
  from [email protected]
 where dealer_name =  'XXXX'
   and to_char(CREATION_DATE,'MMYYYY') = to_char(add_months(trunc(sysdate),-1),'MMYYYY');

How could others, on a local network, access my NodeJS app while it's running on my machine?

One tip that nobody has mentioned yet is to remember to host the app on the LAN-accessible address 0.0.0.0 instead of the default localhost. Firewalls on Mac and Linux are less strict about this address compared to the default localhost address (172.0.0.1).

For example,

gatsby develop --host 0.0.0.0

yarn start --host 0.0.0.0

npm start --host 0.0.0.0

You can then access the address to connect to by entering ifconfig or ipconfig in the terminal. Then try one of the IP addresses on the left that does not end in .255 or .0

How to convert integer to decimal in SQL Server query?

declare @xx int 
set     @xx = 3 
select @xx      
select @xx * 2  -- yields another integer  
select @xx/1    -- same
select @xx/1.0  --yields 6 decimal places 
select @xx/1.00 --       6 
select @xx * 1.0  --     1 decimal place - victory
select @xx * 1.00 --     2         places - hooray 

Also _ inserting an int into a temp_table with like decimal(10,3) _ works ok.

Better way to call javascript function in a tag

Neither is good.

Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like

$('#the-element').click(function () { /* perform action here */ });

in a separate <script> block.

The advantage of this is that it

  1. Separates markup and behaviour in the same way that CSS separates markup and style
  2. Centralises configuration (this is somewhat a corollary of 1).
  3. Is trivially extensible to include more than one argument using jQuery’s powerful selector syntax

Furthermore, it degrades gracefully (but so would using the onclick event) since you can provide the link tags with a href in case the user doesn’t have JavaScript enabled.

Of course, these arguments still count if you’re not using jQuery or another JavaScript library (but why do that?).

Why use the INCLUDE clause when creating an index?

Basic index columns are sorted, but included columns are not sorted. This saves resources in maintaining the index, while still making it possible to provide the data in the included columns to cover a query. So, if you want to cover queries, you can put the search criteria to locate rows into the sorted columns of the index, but then "include" additional, unsorted columns with non-search data. It definitely helps with reducing the amount of sorting and fragmentation in index maintenance.

The import android.support cannot be resolved

Another way to solve the issue:

If you are using the support library, you need to add the appcompat lib to the project. This link shows how to add the support lib to your project.

Assuming you have added the support lib earlier but you are getting the mentioned issue, you can follow the steps below to fix that.

  1. Right click on the project and navigate to Build Path > Configure Build Path.

  2. On the left side of the window, select Android. You will see something like this:

enter image description here

  1. You can notice that no library is referenced at the moment. Now click on the Add button shown at the bottom-right side. You will see a pop up window as shown below.

enter image description here

  1. Select the appcompat lib and press OK. (Note: The lib will be shown if you have added them as mentioned earlier). Now you will see the following window:

enter image description here

  1. Press OK. That's it. The lib is now added to your project (notice the red mark) and the errors relating inclusion of support lib must be gone.

New to MongoDB Can not run command mongo

Also check if you have installed the Mongo as a windows service and if its running. That's also important. There might port conflict because of that.

Spring Boot Adding Http Request Interceptors

WebMvcConfigurerAdapter will be deprecated with Spring 5. From its Javadoc:

@deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made possible by a Java 8 baseline) and can be implemented directly without the need for this adapter

As stated above, what you should do is implementing WebMvcConfigurer and overriding addInterceptors method.

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyCustomInterceptor());
    }
}

How can I check if a JSON is empty in NodeJS?

Object.keys(myObj).length === 0;

As there is need to just check if Object is empty it will be better to directly call a native method Object.keys(myObj).length which returns the array of keys by internally iterating with for..in loop.As Object.hasOwnProperty returns a boolean result based on the property present in an object which itself iterates with for..in loop and will have time complexity O(N2).

On the other hand calling a UDF which itself has above two implementations or other will work fine for small object but will block the code which will have severe impact on overall perormance if Object size is large unless nothing else is waiting in the event loop.

cast or convert a float to nvarchar?

If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.

So instead of:

select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009

You would use:

select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890

In these examples the innermost cast(1234567890 as float) is used in place of selecting a value from the appropriate column.

I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?

select cast(0100884555 as float)
100884555

Whoops! We just stored an incorrect phone number...

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

How to install XNA game studio on Visual Studio 2012?

I found another issue, for some reason if the extensions are cached in the local AppData folder, the XNA extensions never get loaded.

You need to remove the files extensionSdks.en-US.cache and extensions.en-US.cache from the %LocalAppData%\Microsoft\VisualStudio\11.0\Extensions folder. These files are rebuilt the next time you launch

If you need access to the Visual Studio startup log to debug what's happening, run devenv.exe /log command from the C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE directory (assuming you are on a 64 bit machine). The log file generated is located here:

%AppData%\Microsoft\VisualStudio\11.0\ActivityLog.xml

How to use default Android drawables

Better to use android.R.drawable because it is public and documented.

Backup a single table with its data from a database in sql server 2008

You can create table script along with its data using following steps:

  1. Right click on the database.
  2. Select Tasks > Generate scripts ...
  3. Click next.
  4. Click next.
  5. In Table/View Options, set Script Data to True; then click next.
  6. Select the Tables checkbox and click next.
  7. Select your table name and click next.
  8. Click next until the wizard is done.

For more information, see Eric Johnson's blog.

How do I set a column value to NULL in SQL Server Management Studio?

Use This:

Update Table Set Column = CAST(NULL As Column Type) where Condition

Like This:

Update News Set Title = CAST(NULL As nvarchar(100)) Where ID = 50

Tracking Google Analytics Page Views with AngularJS

In your index.html, copy and paste the ga snippet but remove the line ga('send', 'pageview');

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-XXXXXXXX-X');
</script>

I like to give it it's own factory file my-google-analytics.js with self injection:

angular.module('myApp')
  .factory('myGoogleAnalytics', [
    '$rootScope', '$window', '$location', 
    function ($rootScope, $window, $location) {

      var myGoogleAnalytics = {};

      /**
       * Set the page to the current location path
       * and then send a pageview to log path change.
       */
      myGoogleAnalytics.sendPageview = function() {
        if ($window.ga) {
          $window.ga('set', 'page', $location.path());
          $window.ga('send', 'pageview');
        }
      }

      // subscribe to events
      $rootScope.$on('$viewContentLoaded', myGoogleAnalytics.sendPageview);

      return myGoogleAnalytics;
    }
  ])
  .run([
    'myGoogleAnalytics', 
    function(myGoogleAnalytics) {
        // inject self
    }
  ]);

How to change package name of an Android Application

  1. In your Android studio , at project panel , there is gear icon "Click on it".
  2. Uncheck the Compact Empty Middle Packages
  3. Now the package directory has been broken up i.e individual directories.
  4. Select the directory you want to rename.
  5. Right click on that particular directory.
  6. Select refactor and then rename option.
  7. The dialog box has been open up,rename it.
  8. After putting new name, click on Refactor.
  9. Then click on Do Refactor at bottom.
  10. Then android studio will update all changes.
  11. Now open build.gradle file and update the applicationId & sync it.
  12. Now go to manifest file and rename the package.
  13. Rebuild your Project.
  14. You are done :)

How can I get the data type of a variable in C#?

There is an important and subtle issue that none of them addresses directly. There are two ways of considering type in C#: static type and run-time type.

Static type is the type of a variable in your source code. It is therefore a compile-time concept. This is the type that you see in a tooltip when you hover over a variable or property in your development environment.

You can obtain static type by writing helper generic method to let type inference take care of it for you:

   Type GetStaticType<T>(T x) { return typeof(T); }

Run-time type is the type of an object in memory. It is therefore a run-time concept. This is the type returned by the GetType() method.

An object's run-time type is frequently different from the static type of the variable, property, or method that holds or returns it. For example, you can have code like this:

object o = "Some string";

The static type of the variable is object, but at run time, the type of the variable's referent is string. Therefore, the next line will print "System.String" to the console:

Console.WriteLine(o.GetType()); // prints System.String

But, if you hover over the variable o in your development environment, you'll see the type System.Object (or the equivalent object keyword). You also see the same using our helper function from above:

Console.WriteLine(GetStaticType(o)); // prints System.Object

For value-type variables, such as int, double, System.Guid, you know that the run-time type will always be the same as the static type, because value types cannot serve as the base class for another type; the value type is guaranteed to be the most-derived type in its inheritance chain. This is also true for sealed reference types: if the static type is a sealed reference type, the run-time value must either be an instance of that type or null.

Conversely, if the static type of the variable is an abstract type, then it is guaranteed that the static type and the runtime type will be different.

To illustrate that in code:

// int is a value type
int i = 0;
// Prints True for any value of i
Console.WriteLine(i.GetType() == typeof(int));

// string is a sealed reference type
string s = "Foo";
// Prints True for any value of s
Console.WriteLine(s == null || s.GetType() == typeof(string));

// object is an unsealed reference type
object o = new FileInfo("C:\\f.txt");
// Prints False, but could be true for some values of o
Console.WriteLine(o == null || o.GetType() == typeof(object));

// FileSystemInfo is an abstract type
FileSystemInfo fsi = new DirectoryInfo("C:\\");
// Prints False for all non-null values of fsi
Console.WriteLine(fsi == null || fsi.GetType() == typeof(FileSystemInfo));

Tablix: Repeat header rows on each page not working - Report Builder 3.0

Another way to accomplish this if you still have that issue is by doing the following :

  • Clear all the Table header text leave it empty.
  • On the Reports “Header” section add textboxes inside a rectangle , each textbox will represent a column header for the table.
  • As this rectangle is on the Reports Header section it will display on all report pages.

Thanks, Sufian.

Disabling radio buttons with jQuery

I just built a sandbox environment with your code and it worked for me. Here is what I used:

<html>
  <head>
    <title>test</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  </head>
  <body>
    <form id="chatTickets" method="post" action="/admin/index.cfm/">
      <input id="ticketID1" type="radio" checked="checked" value="myvalue1" name="ticketID"/>
      <input id="ticketID2" type="radio" checked="checked" value="myvalue2" name="ticketID"/>
    </form>
    <a href="#" title="Load ActiveChat" id="loadActive">Load Active</a>

    <script>
      jQuery("#loadActive").click(function() {
        //I have other code in here that runs before this function call
        writeData();
      });
      function writeData() {
        jQuery("input[name='ticketID']").each(function(i) {
            jQuery(this).attr('disabled', 'disabled');
        });
      }
    </script>
  </body>
</html>

I tested in FF3.5, moving to IE8 now. And it works fine in IE8 too. What browser are you using?

More than 1 row in <Input type="textarea" />

Although <input> ignores the rows attribute, you can take advantage of the fact that <textarea> doesn't have to be inside <form> tags, but can still be a part of a form by referencing the form's id:

<form method="get" id="testformid">
    <input type="submit" />
</form> 
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>

Of course, <textarea> now appears below "submit" button, but maybe you'll find a way to reposition it.

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

Although the accepted response is a good answer, it overlooks failure scenarios. curl will return 000 if there is an error in the request or there is a connection failure.

url='http://localhost:8080/'
status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == 500 ]] || [[ $status == 000 ]] && echo restarting ${url} # do start/restart logic

Note: this goes a little beyond the requested 500 status check to also confirm that curl can even connect to the server (i.e. returns 000).

Create a function from it:

failureCode() {
    local url=${1:-http://localhost:8080}
    local code=${2:-500}
    local status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
    [[ $status == ${code} ]] || [[ $status == 000 ]]
}

Test getting a 500:

failureCode http://httpbin.org/status/500 && echo need to restart

Test getting error/connection failure (i.e. 000):

failureCode http://localhost:77777 && echo need to start

Test not getting a 500:

failureCode http://httpbin.org/status/400 || echo not a failure

Get size of folder or file

private static long getFolderSize(Path folder) {
        try {
            return Files.walk(folder)
                      .filter(p -> p.toFile().isFile())
                      .mapToLong(p -> p.toFile().length())
                      .sum();
        } catch (IOException e) {
            e.printStackTrace();
            return 0L;
        }

Best method to download image from url in Android

Try this code to download an image from a URL on Android:

DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(imageName);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);

How to make use of ng-if , ng-else in angularJS

The syntax for ng if else in angular is :

<div class="case" *ngIf="data.id === '5'; else elsepart; ">
    <input type="checkbox" id="{{data.id}}" value="{{data.displayName}}" 
    data-ng-model="customizationCntrl.check[data.id1]" data-ng-checked="
    {{data.status}}=='1'" onclick="return false;">{{data.displayName}}<br>
</div>
<ng-template #elsepart>
    <div class="case">
        <input type="checkbox" id="{{data.id}}" value={{data.displayName}}"  
        data-ng-model="customizationCntrl.check[data.id]" data-ng-checked="
        {{data.status}}=='1'">{{data.displayName}}<br>
    </div> 
</ng-template>

Getting Serial Port Information

I tried so many solutions on here that didn't work for me, only displaying some of the ports. But the following displayed All of them and their information.

        using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'"))
        {
            var portnames = SerialPort.GetPortNames();
            var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());

            var portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();

            foreach(string s in portList)
            {
                Console.WriteLine(s);
            }
        }
    }

Get the current year in JavaScript

Take this example, you can place it wherever you want to show it without referring to script in the footer or somewhere else like other answers

<script>new Date().getFullYear()>document.write(new Date().getFullYear());</script>

Copyright note on the footer as an example

Copyright 2010 - <script>new Date().getFullYear()>document.write(new Date().getFullYear());</script>

How to pass model attributes from one Spring MVC controller to another controller?

Maybe you could do it like this:

Don't use the model in first controller. Store data in some other shared object which could be then retrieved by second controller.

Look at this and this post. It's about the similar issue.

P.S.

You could probabbly use session scoped bean for that shared data...

C# LINQ find duplicates in List

Linq query:

var query = from s2 in (from s in someList group s by new { s.Column1, s.Column2 } into sg select sg) where s2.Count() > 1 select s2;

How do we count rows using older versions of Hibernate (~2009)?

It's very easy, just run the following JPQL query:

int count = (
(Number)
    entityManager
    .createQuery(
        "select count(b) " +
        "from Book b")
    .getSingleResult()
).intValue();

The reason we are casting to Number is that some databases will return Long while others will return BigInteger, so for portability sake you are better off casting to a Number and getting an int or a long, depending on how many rows you are expecting to be counted.

Colouring plot by factor in R

The command palette tells you the colours and their order when col = somefactor. It can also be used to set the colours as well.

palette()
[1] "black"   "red"     "green3"  "blue"    "cyan"    "magenta" "yellow"  "gray"   

In order to see that in your graph you could use a legend.

legend('topright', legend = levels(iris$Species), col = 1:3, cex = 0.8, pch = 1)

You'll notice that I only specified the new colours with 3 numbers. This will work like using a factor. I could have used the factor originally used to colour the points as well. This would make everything logically flow together... but I just wanted to show you can use a variety of things.

You could also be specific about the colours. Try ?rainbow for starters and go from there. You can specify your own or have R do it for you. As long as you use the same method for each you're OK.

Make scrollbars only visible when a Div is hovered over?

.div::-webkit-scrollbar-thumb {
    background: transparent;
}

.div:hover::-webkit-scrollbar-thumb {
    background: red;
}

Upload files from Java client to a HTTP server

click link get example file upload clint java with apache HttpComponents

http://hc.apache.org/httpcomponents-client-ga/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java

and library downalod link

https://hc.apache.org/downloads.cgi

use 4.5.3.zip it's working fine in my code

and my working code..

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ClientMultipartFormPost {

     public static void main(String[] args) throws Exception {

          CloseableHttpClient httpclient = HttpClients.createDefault();
          try {
             HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");

             FileBody bin = new FileBody(new File("E:\\meter.jpg"));
             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

             HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("bin", bin)
                .addPart("comment", comment)
                .build();


             httppost.setEntity(reqEntity);

             System.out.println("executing request " + httppost.getRequestLine());
             CloseableHttpResponse response = httpclient.execute(httppost);
           try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                     System.out.println("Response content length: " +    resEntity.getContentLength());
                }
              EntityUtils.consume(resEntity);
             } finally {
                 response.close();
            }
       } finally {
          httpclient.close();
      }
   }

}

How do I align views at the bottom of the screen?

You can keep your initial linear layout by nesting the relative layout within the linear layout:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:text="welcome" 
        android:id="@+id/TextView" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content">
    </TextView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button android:text="submit" 
            android:id="@+id/Button" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true">
        </Button>
        <EditText android:id="@+id/EditText" 
            android:layout_width="match_parent" 
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/Button"
            android:layout_alignParentBottom="true">
        </EditText>
    </RelativeLayout>
</LinearLayout>

Multiple Inheritance in C#

If you can live with the restriction that the methods of IFirst and ISecond must only interact with the contract of IFirst and ISecond (like in your example)... you can do what you ask with extension methods. In practice, this is rarely the case.

public interface IFirst {}
public interface ISecond {}

public class FirstAndSecond : IFirst, ISecond
{
}

public static MultipleInheritenceExtensions
{
  public static void First(this IFirst theFirst)
  {
    Console.WriteLine("First");
  }

  public static void Second(this ISecond theSecond)
  {
    Console.WriteLine("Second");
  }
}

///

public void Test()
{
  FirstAndSecond fas = new FirstAndSecond();
  fas.First();
  fas.Second();
}

So the basic idea is that you define the required implementation in the interfaces... this required stuff should support the flexible implementation in the extension methods. Anytime you need to "add methods to the interface" instead you add an extension method.

How to secure MongoDB with username and password

This is what I did on Ubuntu 18.04:

$ sudo apt install mongodb
$ mongo
> show dbs
> use admin
> db.createUser({  user: "root",  pwd: "rootpw",  roles: [ "root" ]  })  // root user can do anything
> use lefa
> db.lefa.save( {name:"test"} )
> db.lefa.find()
> show dbs
> db.createUser({  user: "lefa",  pwd: "lefapw",  roles: [ { role: "dbOwner", db: "lefa" } ]  }) // admin of a db
> exit
$ sudo vim /etc/mongodb.conf
auth = true
$ sudo systemctl restart mongodb
$ mongo -u "root" -p "rootpw" --authenticationDatabase  "admin"
> use admin
> exit
$ mongo -u "lefa" -p "lefapw" --authenticationDatabase  "lefa"
> use lefa
> exit

VBA - how to conditionally skip a for loop iteration

VBA does not have a Continue or any other equivalent keyword to immediately jump to the next loop iteration. I would suggest a judicious use of Goto as a workaround, especially if this is just a contrived example and your real code is more complicated:

For i = LBound(Schedule, 1) To UBound(Schedule, 1)
    If (Schedule(i, 1) < ReferenceDate) Then
        PrevCouponIndex = i
        Goto NextIteration
    End If
    DF = Application.Run("SomeFunction"....)
    PV = PV + (DF * Coupon / CouponFrequency)
    '....'
    'a whole bunch of other code you are not showing us'
    '....'
    NextIteration:
Next

If that is really all of your code, though, @Brian is absolutely correct. Just put an Else clause in your If statement and be done with it.

How can I convert a string to a float in mysql?

mysql> SELECT CAST(4 AS DECIMAL(4,3));
+-------------------------+
| CAST(4 AS DECIMAL(4,3)) |
+-------------------------+
|                   4.000 |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('4.5s' AS DECIMAL(4,3));
+------------------------------+
| CAST('4.5s' AS DECIMAL(4,3)) |
+------------------------------+
|                        4.500 |
+------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3));
+-------------------------------+
| CAST('a4.5s' AS DECIMAL(4,3)) |
+-------------------------------+
|                         0.000 |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)

Select Row number in postgres

SELECT tab.*,
    row_number() OVER () as rnum
  FROM tab;

Here's the relevant section in the docs.

P.S. This, in fact, fully matches the answer in the referenced question.

How do I get ruby to print a full backtrace instead of a truncated one?

Almost everybody answered this. My version of printing any rails exception into logs would be:

begin
    some_statement
rescue => e
    puts "Exception Occurred #{e}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
    Rails.logger.error "Exception Occurred #{e}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
end

Creating an object: with or without `new`

Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.

Hide separator line on one UITableViewCell

In your UITableViewCell subclass, override layoutSubviews and hide the _UITableViewCellSeparatorView. Works under iOS 10.

override func layoutSubviews() {
    super.layoutSubviews()

    subviews.forEach { (view) in
        if view.dynamicType.description() == "_UITableViewCellSeparatorView" {
            view.hidden = true
        }
    }
}

TypeError: expected string or buffer

readlines() will return a list of all the lines in the file, so lines is a list. You probably want something like this:

for line in f.readlines(): # Iterates through every line and looks for a match
#or
#for line in f:
    match = re.findall('[A-Z]+', line)
    print match

Or, if the file isn't too large you can grab it as as single string:

lines = f.read() # Warning: reads the FULL FILE into memory. This can be bad.
match = re.findall('[A-Z]+', lines)
print match

ERROR Android emulator gets killed

  • Go to: Tools > Android > AVD Manager and Press the "edit" (pencil) icon next to your AVD , Change "Graphics" to "Software".
  • work on my Windows 10 machine and ubuntu 18.04

Combine multiple Collections into a single logical Collection?

Here is my solution for that:

EDIT - changed code a little bit

public static <E> Iterable<E> concat(final Iterable<? extends E> list1, Iterable<? extends E> list2)
{
    return new Iterable<E>()
    {
        public Iterator<E> iterator()
        {
            return new Iterator<E>()
            {
                protected Iterator<? extends E> listIterator = list1.iterator();
                protected Boolean checkedHasNext;
                protected E nextValue;
                private boolean startTheSecond;

                public void theNext()
                {
                    if (listIterator.hasNext())
                    {
                        checkedHasNext = true;
                        nextValue = listIterator.next();
                    }
                    else if (startTheSecond)
                        checkedHasNext = false;
                    else
                    {
                        startTheSecond = true;
                        listIterator = list2.iterator();
                        theNext();
                    }
                }

                public boolean hasNext()
                {
                    if (checkedHasNext == null)
                        theNext();
                    return checkedHasNext;
                }

                public E next()
                {
                    if (!hasNext())
                        throw new NoSuchElementException();
                    checkedHasNext = null;
                    return nextValue;

                }

                public void remove()
                {
                    listIterator.remove();
                }
            };
        }
    };
}

Convert numpy array to tuple

I was not satisfied, so I finally used this:

>>> a=numpy.array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])

>>> tuple(a.reshape(1, -1)[0])
(1, 2, 3, 4, 5, 6)

I don't know if it's quicker, but it looks more effective ;)

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

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

Switching the order of block elements with CSS

I known this is old, but I found a easier solution and it works on ie10, firefox and chrome:

<div id="wrapper">
  <div id="one">One</div>
  <div id="two">Two</div>
  <div id="three">Three</div>
</div> 

This is the css:

#wrapper {display:table;}
#one {display:table-footer-group;}
#three {display:table-header-group;}

And the result:

"Three"
"Two"
"One"

I found it here.

Text on image mouseover?

This is using the :hover pseudoelement in CSS3.

HTML:

<div id="wrapper">
    <img src="http://placehold.it/300x200" class="hover" />
    <p class="text">text</p>
</div>?

CSS:

#wrapper .text {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}

#wrapper:hover .text {
visibility:visible;
}

?Demo HERE.


This instead is a way of achieving the same result by using jquery:

HTML:

<div id="wrapper">
    <img src="http://placehold.it/300x200" class="hover" />
    <p class="text">text</p>
</div>?

CSS:

#wrapper p {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}

jquery code:

$('.hover').mouseover(function() {
  $('.text').css("visibility","visible");
});

$('.hover').mouseout(function() {
  $('.text').css("visibility","hidden");
});

You can put the jquery code where you want, in the body of the HTML page, then you need to include the jquery library in the head like this:

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>

You can see the demo HERE.

When you want to use it on your website, just change the <img src /> value and you can add multiple images and captions, just copy the format i used: insert image with class="hover" and p with class="text"

How to get the last N rows of a pandas DataFrame?

Don't forget DataFrame.tail! e.g. df1.tail(10)

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

If you have security\requestFiltering nodes in your web.config as follows:

<security>
  <requestFiltering>
    <verbs allowUnlisted="false">
      <add verb="GET" allowed="true" />
      <add verb="POST" allowed="true" />
      <add verb="PUT" allowed="true" />
      <add verb="DELETE" allowed="true" />
      <add verb="DEBUG" allowed="true" />          
    </verbs>
  </requestFiltering>

make sure you add this as well

<add verb="OPTIONS" allowed="true" />

How to hide Bootstrap previous modal when you opening new one?

The best that I've been able to do is

$(this).closest('.modal').modal('toggle');

This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

You can however do this:

$(".modal:visible").modal('toggle');

This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

Accessing the web page's HTTP Headers in JavaScript

Using XmlHttpRequest you can pull up the current page and then examine the http headers of the response.

Best case is to just do a HEAD request and then examine the headers.

For some examples of doing this have a look at http://www.jibbering.com/2002/4/httprequest.html

Just my 2 cents.

What is the difference between using constructor vs getInitialState in React / React Native?

The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass.

See the official React doc on the subject of ES6 classes.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}

is equivalent to

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

SameSite warning Chrome 77

This console warning is not an error or an actual problem — Chrome is just spreading the word about this new standard to increase developer adoption.

It has nothing to do with your code. It is something their web servers will have to support.

Release date for a fix is February 4, 2020 per: https://www.chromium.org/updates/same-site

February, 2020: Enforcement rollout for Chrome 80 Stable: The SameSite-by-default and SameSite=None-requires-Secure behaviors will begin rolling out to Chrome 80 Stable for an initial limited population starting the week of February 17, 2020, excluding the US President’s Day holiday on Monday. We will be closely monitoring and evaluating ecosystem impact from this initial limited phase through gradually increasing rollouts.

For the full Chrome release schedule, see here.

I solved same problem by adding in response header

response.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");

SameSite prevents the browser from sending the cookie along with cross-site requests. The main goal is mitigating the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks. Possible values for the flag are Lax or Strict.

SameSite cookies explained here

Please refer this before applying any option.

Hope this helps you.

Define an alias in fish shell

To properly load functions from ~/.config/fish/functions

You may set only ONE function inside file and name file the same as function name + add .fish extension.

This way changing file contents reload functions in opened terminals (note some delay may occur ~1-5s)

That way if you edit either by commandline

function name; function_content; end

then

funcsave name

you have user defined functions in console and custom made in the same order.

System.Timers.Timer vs System.Threading.Timer

System.Threading.Timer is a plain timer. It calls you back on a thread pool thread (from the worker pool).

System.Timers.Timer is a System.ComponentModel.Component that wraps a System.Threading.Timer, and provides some additional features used for dispatching on a particular thread.

System.Windows.Forms.Timer instead wraps a native message-only-HWND and uses Window Timers to raise events in that HWNDs message loop.

If your app has no UI, and you want the most light-weight and general-purpose .Net timer possible, (because you are happy figuring out your own threading/dispatching) then System.Threading.Timer is as good as it gets in the framework.

I'm not fully clear what the supposed 'not thread safe' issues with System.Threading.Timer are. Perhaps it is just same as asked in this question: Thread-safety of System.Timers.Timer vs System.Threading.Timer, or perhaps everyone just means that:

  1. it's easy to write race conditions when you're using timers. E.g. see this question: Timer (System.Threading) thread safety

  2. re-entrancy of timer notifications, where your timer event can trigger and call you back a second time before you finish processing the first event. E.g. see this question: Thread-safe execution using System.Threading.Timer and Monitor

Remove the last line from a file in Bash

Linux

$ is the last line, d for delete:

sed '$d' ~/path/to/your/file/name

MacOS

Equivalent of the sed -i

sed -i '' -e '$ d' ~/path/to/your/file/name

JUnit: how to avoid "no runnable methods" in test utils classes

Annotate your util classes with @Ignore. This will cause JUnit not to try and run them as tests.

How to position a CSS triangle using ::after?

You can set triangle with position see this code for reference

.top-left-corner {
    width: 0px;
    height: 0px;
    border-top: 0px solid transparent;
    border-bottom: 55px solid transparent;
    border-left: 55px solid #289006;
    position: absolute;
    left: 0px;
    top: 0px;
}

How to set default font family for entire Android app

I know this question is quite old, but I have found a nice solution. Basically, you pass a container layout to this function, and it will apply the font to all supported views, and recursively cicle in child layouts:

public static void setFont(ViewGroup layout)
{
    final int childcount = layout.getChildCount();
    for (int i = 0; i < childcount; i++)
    {
        // Get the view
        View v = layout.getChildAt(i);

        // Apply the font to a possible TextView
        try {
            ((TextView) v).setTypeface(MY_CUSTOM_FONT);
            continue;
        }
        catch (Exception e) { }

        // Apply the font to a possible EditText
        try {
            ((TextView) v).setTypeface(MY_CUSTOM_FONT);
            continue;
        }
        catch (Exception e) { }

        // Recursively cicle into a possible child layout
        try {
            ViewGroup vg = (ViewGroup) v;
            Utility.setFont(vg);
            continue;
        }
        catch (Exception e) { }
    }
}

Editor does not contain a main type in Eclipse

I suspect the problem is that Sample.java should be in a package inside the src folder.

I guess that eclipse will not automatically look outside of there.