Programs & Examples On #Layout engine

Handling very large numbers in Python

You could do this for the fun of it, but other than that it's not a good idea. It would not speed up anything I can think of.

  • Getting the cards in a hand will be an integer factoring operation which is much more expensive than just accessing an array.

  • Adding cards would be multiplication, and removing cards division, both of large multi-word numbers, which are more expensive operations than adding or removing elements from lists.

  • The actual numeric value of a hand will tell you nothing. You will need to factor the primes and follow the Poker rules to compare two hands. h1 < h2 for such hands means nothing.

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Your code is correct. Kindly mark small correction.

#rightcolumn {
     width: 750px;
     background-color: #777;
     display: block;
     **float: left;(wrong)**
     **float: right; (corrected)**
     border: 1px solid white;
}

Passing parameters in Javascript onClick event

onclick vs addEventListener. A matter of preference perhaps (where IE>9).

// Using closures
function onClickLink(e, index) {   
    alert(index);
    return false;
}

var div = document.getElementById('div');

for (var i = 0; i < 10; i++) {
    var link = document.createElement('a');

    link.setAttribute('href', '#');
    link.innerHTML = i + '';
    link.addEventListener('click', (function(e) {
        var index = i;
        return function(e) {
            return onClickLink(e, index);
        }
    })(), false);
    div.appendChild(link);
    div.appendChild(document.createElement('BR'));
}

How abut just using a plain data-* attribute, not as cool as a closure, but..

function onClickLink(e) {       
    alert(e.target.getAttribute('data-index'));
    return false;
}

var div = document.getElementById('div');

for (var i = 0; i < 10; i++) {
    var link = document.createElement('a');

    link.setAttribute('href', '#');
    link.setAttribute('data-index', i);
    link.innerHTML = i + ' Hello';        
    link.addEventListener('click', onClickLink, false);
    div.appendChild(link);
    div.appendChild(document.createElement('BR'));
}

java IO Exception: Stream Closed

You're calling writer.close(); after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.

public void writeToFile(){
    String file_text= pedStatusText + "     " + gatesStatus + "     " + DrawBridgeStatusText;
    try {
        writer.write(file_text);
        writer.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And add a method cleanUp to close the stream.

public void cleanUp() {
     writer.close();
}

This means that you have the responsibility to make sure that you're calling cleanUp when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.

EDIT: You can create a new stream each time you want to write to the file, by moving writer into the writeToFile() method..

 public void writeToFile() {
    FileWriter writer = new FileWriter("status.txt", true);
    // ... Write to the file.

    writer.close();
 }

Spring Boot + JPA : Column name annotation ignored

For hibernate5 I solved this issue by puting next lines in my application.properties file:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

I am creating Dialog in onCreate and using it with show and hide. For me the root cause was not dismissing onBackPressed, which was finishing the Home activity.

@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Home.this.finish();
                                return;
                            }
                        }).create().show();

I was finishing the Home Activity onBackPressed without closing / dismissing my dialogs.

When I dismissed my dialogs the crash disappeared.

new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                networkErrorDialog.dismiss() ;
                                homeLocationErrorDialog.dismiss() ;
                                currentLocationErrorDialog.dismiss() ;
                                Home.this.finish();
                                return;
                            }
                        }).create().show();

Windows equivalent of linux cksum command

To avoid annoying non-checksum lines : CertUtil -v -hashfile "your_file" SHA1 | FIND /V "CertUtil" This will display only line(s) NOT contaning CertUtil

Interesting 'takes exactly 1 argument (2 given)' Python error

The call

e.extractAll("th")

for a regular method extractAll() is indeed equivalent to

Extractor.extractAll(e, "th")

These two calls are treated the same in all regards, including the error messages you get.

If you don't need to pass the instance to a method, you can use a staticmethod:

@staticmethod
def extractAll(tag):
    ...

which can be called as e.extractAll("th"). But I wonder why this is a method on a class at all if you don't need to access any instance.

XAMPP Apache won't start

I had the same error, the error logs where empty, I ended up installing Apache as a service via XAMPP.

Now when I try and start Apache I at least get some informative errors in Windows Event Viewer.

Turned out to be a missing directory for a vhost, easy fix, however I was only able to view this error when attempting to start Apache as a service.

How can I exclude directories from grep -R?

A simple working command:

root/dspace# grep -r --exclude-dir={log,assetstore} "creativecommons.org"

Above I grep for text "creativecommons.org" in current directory "dspace" and exclude dirs {log,assetstore}.

Done.

make iframe height dynamic based on content inside- JQUERY/Javascript

jQuery('.home_vidio_img1 img').click(function(){
    video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
    jQuery(this).replaceWith(video);
});

jQuery('.home_vidio_img2 img').click(function(){
    video = <iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>;
    jQuery('.home_vidio_img1 img').replaceWith(video);
    jQuery('.home_vidio_img1 iframe').replaceWith(video);
});

jQuery('.home_vidio_img3 img').click(function(){
    video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
    jQuery('.home_vidio_img1 img').replaceWith(video);
    jQuery('.home_vidio_img1 iframe').replaceWith(video);
});

jQuery('.home_vidio_img4 img').click(function(){
    video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
    jQuery('.home_vidio_img1 img').replaceWith(video);
    jQuery('.home_vidio_img1 iframe').replaceWith(video);
});

Fuzzy matching using T-SQL

do it this way

         create table person(
         personid int identity(1,1) primary key,
         firstname varchar(20),
         lastname varchar(20),
         addressindex int,
         sound varchar(10)
         )

and later on create a trigger

         create trigger trigoninsert for dbo.person
         on insert 
         as
         declare @personid int;
         select @personid=personid from inserted;
         update person
         set sound=soundex(firstname) where personid=@personid;

now what i can do is i can create a procedure which looks something like this

         create procedure getfuzzi(@personid int)
          as
         declare @sound varchar(10);
         set @sound=(select sound from person where personid=@personid;
         select personid,firstname,lastname,addressindex from person
         where sound=@sound

this will return you all the names that are nearly in match with the names provided by for a particular personid

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

How to write an ArrayList of Strings into a text file?

I would suggest using FileUtils from Apache Commons IO library.It will create the parent folders of the output file,if they don't exist.while Files.write(out,arrayList,Charset.defaultCharset()); will not do this,throwing exception if the parent directories don't exist.

FileUtils.writeLines(new File("output.txt"), encoding, list);

How to inject window into a service?

There is an opportunity for direct access to the object of window through the document

document.defaultView == window

How to join on multiple columns in Pyspark?

You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))

df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()

## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## |  2|  b|3.0|  2|  b|0.0|
## +---+---+---+---+---+---+

How to merge remote master to local branch

git rebase didn't seem to work for me. After git rebase, when I try to push changes to my local branch, I kept getting an error ("hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. 'git pull ...') before pushing again.") even after git pull. What finally worked for me was git merge.

git checkout <local_branch>
git merge <master> 

If you are a beginner like me, here is a good article on git merge vs git rebase. https://www.atlassian.com/git/tutorials/merging-vs-rebasing

How can I pass a list as a command-line argument with argparse?

You can parse the list as a string and use of the eval builtin function to read it as a list. In this case, you will have to put single quotes into double quote (or the way around) in order to ensure successful string parse.

# declare the list arg as a string
parser.add_argument('-l', '--list', type=str)

# parse
args = parser.parse()

# turn the 'list' string argument into a list object
args.list = eval(args.list)
print(list)
print(type(list))

Testing:

python list_arg.py --list "[1, 2, 3]"

[1, 2, 3]
<class 'list'>

How to create an XML document using XmlDocument?

What about:

#region Using Statements
using System;
using System.Xml;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XmlDocument doc = new XmlDocument( );

        //(1) the xml declaration is recommended, but not mandatory
        XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore( xmlDeclaration, root );

        //(2) string.Empty makes cleaner code
        XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
        doc.AppendChild( element1 );

        XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
        element1.AppendChild( element2 );

        XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text1 = doc.CreateTextNode( "text" );
        element3.AppendChild( text1 );
        element2.AppendChild( element3 );

        XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text2 = doc.CreateTextNode( "other text" );
        element4.AppendChild( text2 );
        element2.AppendChild( element4 );

        doc.Save( "D:\\document.xml" );
    }
}

(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?


The result is:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

But I recommend you to use LINQ to XML which is simpler and more readable like here:

#region Using Statements
using System;
using System.Xml.Linq;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XDocument doc = new XDocument( new XElement( "body", 
                                           new XElement( "level1", 
                                               new XElement( "level2", "text" ), 
                                               new XElement( "level2", "other text" ) ) ) );
        doc.Save( "D:\\document.xml" );
    }
}

Best way to check if a URL is valid

function is_url($uri){
    if(preg_match( '/^(http|https):\\/\\/[a-z0-9_]+([\\-\\.]{1}[a-z_0-9]+)*\\.[_a-z]{2,5}'.'((:[0-9]{1,5})?\\/.*)?$/i' ,$uri)){
      return $uri;
    }
    else{
        return false;
    }
}

Real-world examples of recursion

Recursion is often used in implementations of the Backtracking algorithm. For a "real-world" application of this, how about a Sudoku solver?

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

Changing background color of ListView items on Android

Simple code to change all in layout of item (custom listview extends baseadapter):

lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            RelativeLayout layout=(RelativeLayout) arg1.findViewById(R.id.rel_cell_left);
            layout.setBackgroundColor(Color.YELLOW);



        }
    });

How to add an element to Array and shift indexes?

I smell homework, so probably an ArrayList won't be allowed (?)

Instead of looking for a way to "shift indexes", maybe just build a new array:

int[] b = new int[a.length +1];

Then

  1. copy indexes form array a counting from zero up to insert position
  2. ...
  3. ...

//edit: copy values of course, not indexes

inverting image in Python with OpenCV

You can use "tilde" operator to do it:

import cv2
image = cv2.imread("img.png")
image = ~image
cv2.imwrite("img_inv.png",image)

This is because the "tilde" operator (also known as unary operator) works doing a complement dependent on the type of object

for example for integers, its formula is:

x + (~x) = -1

but in this case, opencv use an "uint8 numpy array object" for its images so its range is from 0 to 255

so if we apply this operator to an "uint8 numpy array object" like this:

import numpy as np
x1 = np.array([25,255,10], np.uint8) #for example
x2 = ~x1
print (x2)

we will have as a result:

[230 0 245]

because its formula is:

x2 = 255 - x1

and that is exactly what we want to do to solve the problem.

Method with a bool return

     public bool roomSelected()
    {
        int a = 0;
        foreach (RadioButton rb in GroupBox1.Controls)
        {
            if (rb.Checked == true)
            {
                a = 1;
            }
        }
        if (a == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

this how I solved my problem

Is there a printf converter to print in binary format?

Here's is a very simple one:

int print_char_to_binary(char ch)
{
    int i;
    for (i=7; i>=0; i--)
        printf("%hd ", ((ch & (1<<i))>>i));
    printf("\n");
    return 0;
}

Removing NA observations with dplyr::filter()

If someone is here in 2020, after making all the pipes, if u pipe %>% na.exclude will take away all the NAs in the pipe!

How to debug on a real device (using Eclipse/ADT)

in devices which has Android 4.3 and above you should follow these steps:

How to enable Developer Options:

Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.

In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.

The remote end hung up unexpectedly while git cloning

###Quick solution:

With this kind of error, I usually start by raising the postBuffer size by:

git config --global http.postBuffer 524288000

(some comments below report having to double the value):

git config --global http.postBuffer 1048576000

(For npm publish, Martin Braun reports in the comments setting it to no more than 50 000 000 instead of the default 1 000 000)

###More information:

From the git config man page, http.postBuffer is about:

Maximum size in bytes of the buffer used by smart HTTP transports when POSTing data to the remote system.
For requests larger than this buffer size, HTTP/1.1 and Transfer-Encoding: chunked is used to avoid creating a massive pack file locally. Default is 1 MiB, which is sufficient for most requests.

Even for the clone, that can have an effect, and in this instance, the OP Joe reports:

[clone] works fine now


Note: if something went wrong on the server side, and if the server uses Git 2.5+ (Q2 2015), the error message might be more explicit.
See "Git cloning: remote end hung up unexpectedly, tried changing postBuffer but still failing".


Kulai (in the comments) points out to this Atlassian Troubleshooting Git page, which adds:

Error code 56 indicates a curl receive the error of CURLE_RECV_ERROR which means there was some issue that prevented the data from being received during the cloning process.
Typically this is caused by a network setting, firewall, VPN client, or anti-virus that is terminating the connection before all data has been transferred.

It also mentions the following environment variable, order to help with the debugging process.

# Linux
export GIT_TRACE_PACKET=1
export GIT_TRACE=1
export GIT_CURL_VERBOSE=1

#Windows
set GIT_TRACE_PACKET=1
set GIT_TRACE=1
set GIT_CURL_VERBOSE=1

With Git 2.25.1 (Feb. 2020), you know more about this http.postBuffer "solution".

See commit 7a2dc95, commit 1b13e90 (22 Jan 2020) by brian m. carlson (bk2204).
(Merged by Junio C Hamano -- gitster -- in commit 53a8329, 30 Jan 2020)
(Git Mailing list discussion)

docs: mention when increasing http.postBuffer is valuable

Signed-off-by: brian m. carlson

Users in a wide variety of situations find themselves with HTTP push problems.

Oftentimes these issues are due to antivirus software, filtering proxies, or other man-in-the-middle situations; other times, they are due to simple unreliability of the network.

However, a common solution to HTTP push problems found online is to increase http.postBuffer.

This works for none of the aforementioned situations and is only useful in a small, highly restricted number of cases: essentially, when the connection does not properly support HTTP/1.1.

Document when raising this value is appropriate and what it actually does, and discourage people from using it as a general solution for push problems, since it is not effective there.

So the documentation for git config http.postBuffer now includes:

http.postBuffer

Maximum size in bytes of the buffer used by smart HTTP transports when POSTing data to the remote system.
For requests larger than this buffer size, HTTP/1.1 and Transfer-Encoding: chunked is used to avoid creating a massive pack file locally.
Default is 1 MiB, which issufficient for most requests.

Note that raising this limit is only effective for disabling chunked transfer encoding and therefore should be used only where the remote server or a proxy only supports HTTP/1.0 or is noncompliant with the HTTP standard.
Raising this is not, in general, an effective solution for most push problems, but can increase memory consumption significantly since the entire buffer is allocated even for small pushes.

SSIS Text was truncated with status value 4

If this is coming from SQL Server Import Wizard, try editing the definition of the column on the Data Source, it is 50 characters by default, but it can be longer.

Data Soruce -> Advanced -> Look at the column that goes in error -> change OutputColumnWidth to 200 and try again.

using jQuery .animate to animate a div from right to left?

so the .animate method works only if you have given a position attribute to an element, if not it didn't move?

for example i've seen that if i declare the div but i declare nothing in the css, it does not assume his default position and it does not move it into the page, even if i declare property margin: x w y z;

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

Context

  • python 3.x
  • unpacking with **
  • use with string formatting

Use with string formatting

In addition to the answers in this thread, here is another detail that was not mentioned elsewhere. This expands on the answer by Brad Solomon

Unpacking with ** is also useful when using python str.format.

This is somewhat similar to what you can do with python f-strings f-string but with the added overhead of declaring a dict to hold the variables (f-string does not require a dict).

Quick Example

  ## init vars
  ddvars = dict()
  ddcalc = dict()
  pass
  ddvars['fname']     = 'Huomer'
  ddvars['lname']     = 'Huimpson'
  ddvars['motto']     = 'I love donuts!'
  ddvars['age']       = 33
  pass
  ddcalc['ydiff']     = 5
  ddcalc['ycalc']     = ddvars['age'] + ddcalc['ydiff']
  pass
  vdemo = []

  ## ********************
  ## single unpack supported in py 2.7
  vdemo.append('''
  Hello {fname} {lname}!

  Today you are {age} years old!

  We love your motto "{motto}" and we agree with you!
  '''.format(**ddvars)) 
  pass

  ## ********************
  ## multiple unpack supported in py 3.x
  vdemo.append('''
  Hello {fname} {lname}!

  In {ydiff} years you will be {ycalc} years old!
  '''.format(**ddvars,**ddcalc)) 
  pass

  ## ********************
  print(vdemo[-1])

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

If you are having some issue when including dependency for 6.1.0.jre7 from @nirmals answer in https://stackoverflow.com/a/41149866/1570834, in your pom with commons-codec/ azure-keyvault I prefer going with this:

    <dependency>
       <groupId>com.microsoft.sqlserver</groupId>
       <artifactId>mssql-jdbc</artifactId>
       <version>6.2.2.jre7</version>                
    </dependency>

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

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

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

typedef struct vs struct definitions

The common idiom is using both:

typedef struct S { 
    int x; 
} S;

They are different definitions. To make the discussion clearer I will split the sentence:

struct S { 
    int x; 
};

typedef struct S S;

In the first line you are defining the identifier S within the struct name space (not in the C++ sense). You can use it and define variables or function arguments of the newly defined type by defining the type of the argument as struct S:

void f( struct S argument ); // struct is required here

The second line adds a type alias S in the global name space and thus allows you to just write:

void f( S argument ); // struct keyword no longer needed

Note that since both identifier name spaces are different, defining S both in the structs and global spaces is not an error, as it is not redefining the same identifier, but rather creating a different identifier in a different place.

To make the difference clearer:

typedef struct S { 
    int x; 
} T;

void S() { } // correct

//void T() {} // error: symbol T already defined as an alias to 'struct S'

You can define a function with the same name of the struct as the identifiers are kept in different spaces, but you cannot define a function with the same name as a typedef as those identifiers collide.

In C++, it is slightly different as the rules to locate a symbol have changed subtly. C++ still keeps the two different identifier spaces, but unlike in C, when you only define the symbol within the class identifier space, you are not required to provide the struct/class keyword:

 // C++
struct S { 
    int x; 
}; // S defined as a class

void f( S a ); // correct: struct is optional

What changes are the search rules, not where the identifiers are defined. The compiler will search the global identifier table and after S has not been found it will search for S within the class identifiers.

The code presented before behaves in the same way:

typedef struct S { 
    int x; 
} T;

void S() {} // correct [*]

//void T() {} // error: symbol T already defined as an alias to 'struct S'

After the definition of the S function in the second line, the struct S cannot be resolved automatically by the compiler, and to create an object or define an argument of that type you must fall back to including the struct keyword:

// previous code here...
int main() {
    S(); 
    struct S s;
}

Datagridview: How to set a cell in editing mode?

I know this is an old question, but none of the answers worked for me, because I wanted to reliably (always be able to) set the cell into edit mode when possibly executing other events like Toolbar Button clicks, menu selections, etc. that may affect the default focus after those events return. I ended up needing a timer and invoke. The following code is in a new component derived from DataGridView. This code allows me to simply make a call to myXDataGridView.CurrentRow_SelectCellFocus(myDataPropertyName); anytime I want to arbitrarily set a databound cell to edit mode (assuming the cell is Not in ReadOnly mode).

// If the DGV does not have Focus prior to a toolbar button Click, 
// then the toolbar button will have focus after its Click event handler returns.
// To reliably set focus to the DGV, we need to time it to happen After event handler procedure returns.

private string m_SelectCellFocus_DataPropertyName = "";
private System.Timers.Timer timer_CellFocus = null;

public void CurrentRow_SelectCellFocus(string sDataPropertyName)
{
  // This procedure is called by a Toolbar Button's Click Event to select and set focus to a Cell in the DGV's Current Row.
  m_SelectCellFocus_DataPropertyName = sDataPropertyName;
  timer_CellFocus = new System.Timers.Timer(10);
  timer_CellFocus.Elapsed += TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Start();
}


void TimerElapsed_CurrentRowSelectCellFocus(object sender, System.Timers.ElapsedEventArgs e)
{
  timer_CellFocus.Stop();
  timer_CellFocus.Elapsed -= TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Dispose();
  // We have to Invoke the method to avoid raising a threading error
  this.Invoke((MethodInvoker)delegate
  {
    Select_Cell(m_SelectCellFocus_DataPropertyName);
  });
}


private void Select_Cell(string sDataPropertyName)
{
  /// When the Edit Mode is Enabled, set the initial cell to the Description
  foreach (DataGridViewCell dgvc in this.SelectedCells) 
  {
    // Clear previously selected cells
    dgvc.Selected = false; 
  }
  foreach (DataGridViewCell dgvc in this.CurrentRow.Cells)
  {
    // Select the Cell by its DataPropertyName
    if (dgvc.OwningColumn.DataPropertyName == sDataPropertyName)
    {
      this.CurrentCell = dgvc;
      dgvc.Selected = true;
      this.Focus();
      return;
    }
  }
}

OSError - Errno 13 Permission denied

This may also happen if you have a slash before the folder name:

path = '/folder1/folder2'

OSError: [Errno 13] Permission denied: '/folder1'

comes up with an error but this one works fine:

path = 'folder1/folder2'

How to access cookies in AngularJS?

AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.

We need to add angular-cookies.min.js file to use cookie feature.

Here is some method of AngularJS Cookie.

  • get(key); // This method returns the value of given cookie key.

  • getObject(key); //This method returns the deserialized value of given cookie key.

  • getAll(); //This method returns a key value object with all the cookies.

  • put(key, value, [options]); //This method sets a value for given cookie key.

  • remove(key, [options]); //This method remove given cookie.

Example

Html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>

JavaScript

var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);

I have Taken reference from http://www.tutsway.com/simple-example-of-cookie-in-angular-js.php.

For Loop on Lua

Your problem is simple:

names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
  print (names)
end

This code first declares a global variable called names. Then, you start a for loop. The for loop declares a local variable that just happens to be called names too; the fact that a variable had previously been defined with names is entirely irrelevant. Any use of names inside the for loop will refer to the local one, not the global one.

The for loop says that the inner part of the loop will be called with names = 1, then names = 2, and finally names = 3. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.

What you actually wanted was something like this:

names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
  print (names[nameCount])
end

The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).

Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.

However, this has a flaw. What happens if you remove one of the elements from the list?

names = {'John', 'Joe'}
for nameCount = 1, 3 do
  print (names[nameCount])
end

Now, we get John Joe nil, because attempting to access values from a table that don't exist results in nil. To prevent this, we need to count from 1 to the length of the table:

names = {'John', 'Joe'}
for nameCount = 1, #names do
  print (names[nameCount])
end

The # is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names gets, this will always work.

However, there is a more convenient way to iterate through an array of items:

names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
  print (name)
end

ipairs is a Lua standard function that iterates over a list. This style of for loop, the iterator for loop, uses this kind of iterator function. The i value is the index of the entry in the array. The name value is the value at that index. So it basically does a lot of grunt work for you.

outline on only one border

Try with Shadow( Like border ) + Border

border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

set option "selected" attribute from dynamic created option

You're overthinking it:

var country = document.getElementById("country");
country.options[country.options.selectedIndex].selected = true;

How to control font sizes in pgf/tikz graphics in latex?

I found the better control would be using scalefnt package:

\usepackage{scalefnt}
...
{\scalefont{0.5}
\begin{tikzpicture}
...
\end{tikzpicture}
}

Swift - iOS - Dates and times in different format

let usDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-US"))
            //usDateFormat now contains an optional string "MM/dd/yyyy"

let gbDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-GB"))
            //gbDateFormat now contains an optional string "dd/MM/yyyy"

let geDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "de-DE"))
            //geDateFormat now contains an optional string "dd.MM.yyyy"

You can use it in following way to get the current format from device:

let currentDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale.current)

SQLite UPSERT / UPDATE OR INSERT

You can also just add an ON CONFLICT REPLACE clause to your user_name unique constraint and then just INSERT away, leaving it to SQLite to figure out what to do in case of a conflict. See:https://sqlite.org/lang_conflict.html.

Also note the sentence regarding delete triggers: When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.

How do I get sed to read from standard input?

To make sed catch from stdin , instead of from a file, you should use -e.

Like this:

curl -k -u admin:admin https://$HOSTNAME:9070/api/tm/3.8/status/$HOSTNAME/statistics/traffic_ips/trafc_ip/ | sed -e 's/["{}]//g' |sed -e 's/[]]//g' |sed -e 's/[\[]//g' |awk  'BEGIN{FS=":"} {print $4}'

How to change the color of a button?

You can change the value in the XML like this:

<Button
    android:background="#FFFFFF"
     ../>

Here, you can add any other color, from the resources or hex.

Similarly, you can also change these values form the code like this:

demoButton.setBackgroundColor(Color.WHITE);

Another easy way is to make a drawable, customize the corners and shape according to your preference and set the background color and stroke of the drawable. For eg.

button_background.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="2dp" android:color="#ff207d94" />
    <corners android:radius="5dp" />
    <solid android:color="#FFFFFF" />
</shape>

And then set this shape as the background of your button.

<Button
    android:background="@drawable/button_background.xml"
     ../>

Hope this helps, good luck!

Python Pandas Counting the Occurrences of a Specific value

Try this:

(df[education]=='9th').sum()

How can I change the default Django date template format?

Within your template, you can use Django's date filter. E.g.:

<p>Birthday: {{ birthday|date:"M d, Y" }}</p>

Gives:

Birthday: Jan 29, 1983

More formatting examples in the date filter docs.

Disable/enable an input with jQuery?

If you just want to invert the current state (like a toggle button behaviour):

$("input").prop('disabled', ! $("input").prop('disabled') );

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

How can I rename a project folder from within Visual Studio?

A proven solution for Visual Studio extension for Data Tools for Business Intelligence (SSDT-BI 2013):

  1. Move the Project folder to its new location (don't rename anything yet)
  2. In Solution Explorer, rename the Project / Solution.
  3. Close (and save) the newly-renamed project.
  4. Rename the project's folder and .sln file.
  5. Use a text editor and open the newly-renamed project solution file (.sln) (I used Notepad++)
  6. In line number 6 you'll see: "Project {fdjfksdjk4387!...} = "OLDPROJECT", "OLDFOLDER\OLDPROJECT.rptproj". Rename everything with the new names used in step 4. (i.e. ... = "NEWPROJECT", "NEWFOLDER\NEWPROJECT.rptproj"... )
  7. That's it!

It was tested 100% and worked flawlessly in my case.

NOTE: I can't confirm if it works under different project templates and other Visual Studio versions. As always, do backup everything beforehand.

How to get duration, as int milli's and float seconds from <chrono>?

In AAA style using the explicitly typed initializer idiom:

#include <chrono>
#include <iostream>

int main(){
  auto start = std::chrono::high_resolution_clock::now();
  // Code to time here...
  auto end = std::chrono::high_resolution_clock::now();

  auto dur = end - start;
  auto i_millis = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
  auto f_secs = std::chrono::duration_cast<std::chrono::duration<float>>(dur);
  std::cout << i_millis.count() << '\n';
  std::cout << f_secs.count() << '\n';
}

<script> tag vs <script type = 'text/javascript'> tag

Douglas Crockford says:

type="text/javascript"

This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

In HTML 4.01 and XHTML 1(.1), the type attribute for <script> elements is required.

How do I reformat HTML code using Sublime Text 2?

The only package I've been able to find is Tag.

You can install it using the package control. https://sublime.wbond.net

After installing package control. Go to package control (Preferences -> Package Control) then type install, hit enter. Then type tag and hit enter.

After installing Tag, highlight the text and press the shortcut Ctrl+Alt+F.

Remove accents/diacritics in a string in JavaScript

I have forked billy's code http://jsfiddle.net/billybraga/UHmnf/ (from his post) into this: http://jsfiddle.net/infralabs/dJX58/

I corrected transcription of ? and ß characters and also added coversion of these ones: Þþ, Ðð, ??, ??, Œœ.

The modified snippet is below:

var defaultDiacriticsRemovalMap = [{
    'base': "A",
        'letters': /(&#65;|&#9398;|&#65313;|&#192;|&#193;|&#194;|&#7846;|&#7844;|&#7850;|&#7848;|&#195;|&#256;|&#258;|&#7856;|&#7854;|&#7860;|&#7858;|&#550;|&#480;|&#196;|&#478;|&#7842;|&#197;|&#506;|&#461;|&#512;|&#514;|&#7840;|&#7852;|&#7862;|&#7680;|&#260;|&#570;|&#11375;|[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F])/g
}, {
    'base': "AA",
        'letters': /(&#42802;|[\uA732])/g
}, {
    'base': "AE",
        'letters': /(&#198;|&#508;|&#482;|[\u00C6\u01FC\u01E2])/g
}, {
    'base': "AO",
        'letters': /(&#42804;|[\uA734])/g
}, {
    'base': "AU",
        'letters': /(&#42806;|[\uA736])/g
}, {
    'base': "AV",
        'letters': /(&#42808;|&#42810;|[\uA738\uA73A])/g
}, {
    'base': "AY",
        'letters': /(&#42812;|[\uA73C])/g
}, {
    'base': "B",
        'letters': /(&#66;|&#9399;|&#65314;|&#7682;|&#7684;|&#7686;|&#579;|&#386;|&#385;|[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181])/g
}, {
    'base': "C",
        'letters': /(&#67;|&#9400;|&#65315;|&#262;|&#264;|&#266;|&#268;|&#199;|&#7688;|&#391;|&#571;|&#42814;|[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E])/g
}, {
    'base': "D",
        'letters': /(&#68;|&#9401;|&#65316;|&#7690;|&#270;|&#7692;|&#7696;|&#7698;|&#7694;|&#272;|&#395;|&#394;|&#393;|&#42873;|&#208;|[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0])/g
}, {
    'base': "DZ",
        'letters': /(&#497;|&#452;|[\u01F1\u01C4])/g
}, {
    'base': "Dz",
        'letters': /(&#498;|&#453;|[\u01F2\u01C5])/g
}, {
    'base': "E",
        'letters': /(&#69;|&#9402;|&#65317;|&#200;|&#201;|&#202;|&#7872;|&#7870;|&#7876;|&#7874;|&#7868;|&#274;|&#7700;|&#7702;|&#276;|&#278;|&#203;|&#7866;|&#282;|&#516;|&#518;|&#7864;|&#7878;|&#552;|&#7708;|&#280;|&#7704;|&#7706;|&#400;|&#398;|[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E])/g
}, {
    'base': "F",
        'letters': /(&#70;|&#9403;|&#65318;|&#7710;|&#401;|&#42875;|[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B])/g
}, {
    'base': "G",
        'letters': /(&#71;|&#9404;|&#65319;|&#500;|&#284;|&#7712;|&#286;|&#288;|&#486;|&#290;|&#484;|&#403;|&#42912;|&#42877;|&#42878;|[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E])/g
}, {
    'base': "H",
        'letters': /(&#72;|&#9405;|&#65320;|&#292;|&#7714;|&#7718;|&#542;|&#7716;|&#7720;|&#7722;|&#294;|&#11367;|&#11381;|&#42893;|[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D])/g
}, {
    'base': "I",
        'letters': /(&#73;|&#9406;|&#65321;|&#204;|&#205;|&#206;|&#296;|&#298;|&#300;|&#304;|&#207;|&#7726;|&#7880;|&#463;|&#520;|&#522;|&#7882;|&#302;|&#7724;|&#407;|[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197])/g
}, {
    'base': "J",
        'letters': /(&#74;|&#9407;|&#65322;|&#308;|&#584;|[\u004A\u24BF\uFF2A\u0134\u0248])/g
}, {
    'base': "K",
        'letters': /(&#75;|&#9408;|&#65323;|&#7728;|&#488;|&#7730;|&#310;|&#7732;|&#408;|&#11369;|&#42816;|&#42818;|&#42820;|&#42914;|[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2])/g
}, {
    'base': "L",
        'letters': /(&#76;|&#9409;|&#65324;|&#319;|&#313;|&#317;|&#7734;|&#7736;|&#315;|&#7740;|&#7738;|&#321;|&#573;|&#11362;|&#11360;|&#42824;|&#42822;|&#42880;|[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780])/g
}, {
    'base': "LJ",
        'letters': /(&#455;|[\u01C7])/g
}, {
    'base': "Lj",
        'letters': /(&#456;|[\u01C8])/g
}, {
    'base': "M",
        'letters': /(&#77;|&#9410;|&#65325;|&#7742;|&#7744;|&#7746;|&#11374;|&#412;|[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C])/g
}, {
    'base': "N",
        'letters': /(&#78;|&#9411;|&#65326;|&#504;|&#323;|&#209;|&#7748;|&#327;|&#7750;|&#325;|&#7754;|&#7752;|&#544;|&#413;|&#42896;|&#42916;|&#330;|[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4\u014A])/g
}, {
    'base': "NJ",
        'letters': /(&#458;|[\u01CA])/g
}, {
    'base': "Nj",
        'letters': /(&#459;|[\u01CB])/g
}, {
    'base': "O",
        'letters': /(&#79;|&#9412;|&#65327;|&#210;|&#211;|&#212;|&#7890;|&#7888;|&#7894;|&#7892;|&#213;|&#7756;|&#556;|&#7758;|&#332;|&#7760;|&#7762;|&#334;|&#558;|&#560;|&#214;|&#554;|&#7886;|&#336;|&#465;|&#524;|&#526;|&#416;|&#7900;|&#7898;|&#7904;|&#7902;|&#7906;|&#7884;|&#7896;|&#490;|&#492;|&#216;|&#510;|&#390;|&#415;|&#42826;|&#42828;|[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C])/g
}, {
    'base': "OE",
        'letters': /(&#338;|[\u0152])/g
}, {
    'base': "OI",
        'letters': /(&#418;|[\u01A2])/g
}, {
    'base': "OO",
        'letters': /(&#42830;|[\uA74E])/g
}, {
    'base': "OU",
        'letters': /(&#546;|[\u0222])/g
}, {
    'base': "P",
        'letters': /(&#80;|&#9413;|&#65328;|&#7764;|&#7766;|&#420;|&#11363;|&#42832;|&#42834;|&#42836;|[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754])/g
}, {
    'base': "Q",
        'letters': /(&#81;|&#9414;|&#65329;|&#42838;|&#42840;|&#586;|[\u0051\u24C6\uFF31\uA756\uA758\u024A])/g
}, {
    'base': "R",
        'letters': /(&#82;|&#9415;|&#65330;|&#340;|&#7768;|&#344;|&#528;|&#530;|&#7770;|&#7772;|&#342;|&#7774;|&#588;|&#11364;|&#42842;|&#42918;|&#42882;|[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782])/g
}, {
    'base': "S",
        'letters': /(&#83;|&#9416;|&#65331;|&#7838;|&#346;|&#7780;|&#348;|&#7776;|&#352;|&#7782;|&#7778;|&#7784;|&#536;|&#350;|&#11390;|&#42920;|&#42884;|[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784])/g
}, {
    'base': "T",
        'letters': /(&#84;|&#9417;|&#65332;|&#7786;|&#356;|&#7788;|&#538;|&#354;|&#7792;|&#7790;|&#358;|&#428;|&#430;|&#574;|&#42886;|[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786])/g
}, {
    'base': "TH",
        'letters': /(&#222;|[\u00DE])/g
}, {
    'base': "TZ",
        'letters': /(&#42792;|[\uA728])/g
}, {
    'base': "U",
        'letters': /(&#85;|&#9418;|&#65333;|&#217;|&#218;|&#219;|&#360;|&#7800;|&#362;|&#7802;|&#364;|&#220;|&#475;|&#471;|&#469;|&#473;|&#7910;|&#366;|&#368;|&#467;|&#532;|&#534;|&#431;|&#7914;|&#7912;|&#7918;|&#7916;|&#7920;|&#7908;|&#7794;|&#370;|&#7798;|&#7796;|&#580;|[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244])/g
}, {
    'base': "V",
        'letters': /(&#86;|&#9419;|&#65334;|&#7804;|&#7806;|&#434;|&#42846;|&#581;|[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245])/g
}, {
    'base': "VY",
        'letters': /(&#42848;|[\uA760])/g
}, {
    'base': "W",
        'letters': /(&#87;|&#9420;|&#65335;|&#7808;|&#7810;|&#372;|&#7814;|&#7812;|&#7816;|&#11378;|[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72])/g
}, {
    'base': "X",
        'letters': /(&#88;|&#9421;|&#65336;|&#7818;|&#7820;|[\u0058\u24CD\uFF38\u1E8A\u1E8C])/g
}, {
    'base': "Y",
        'letters': /(&#89;|&#9422;|&#65337;|&#7922;|&#221;|&#374;|&#7928;|&#562;|&#7822;|&#376;|&#7926;|&#7924;|&#435;|&#590;|&#7934;|[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE])/g
}, {
    'base': "Z",
        'letters': /(&#90;|&#9423;|&#65338;|&#377;|&#7824;|&#379;|&#381;|&#7826;|&#7828;|&#437;|&#548;|&#11391;|&#11371;|&#42850;|[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762])/g
}, {
    'base': "a",
        'letters': /(&#97;|&#9424;|&#65345;|&#7834;|&#224;|&#225;|&#226;|&#7847;|&#7845;|&#7851;|&#7849;|&#227;|&#257;|&#259;|&#7857;|&#7855;|&#7861;|&#7859;|&#551;|&#481;|&#228;|&#479;|&#7843;|&#229;|&#507;|&#462;|&#513;|&#515;|&#7841;|&#7853;|&#7863;|&#7681;|&#261;|&#11365;|&#592;|[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250])/g
}, {
    'base': "aa",
        'letters': /(&#42803;|[\uA733])/g
}, {
    'base': "ae",
        'letters': /(&#230;|&#509;|&#483;|[\u00E6\u01FD\u01E3])/g
}, {
    'base': "ao",
        'letters': /(&#42805;|[\uA735])/g
}, {
    'base': "au",
        'letters': /(&#42807;|[\uA737])/g
}, {
    'base': "av",
        'letters': /(&#42809;|&#42811;|[\uA739\uA73B])/g
}, {
    'base': "ay",
        'letters': /(&#42813;|[\uA73D])/g
}, {
    'base': "b",
        'letters': /(&#98;|&#9425;|&#65346;|&#7683;|&#7685;|&#7687;|&#384;|&#387;|&#595;|[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253])/g
}, {
    'base': "c",
        'letters': /(&#99;|&#9426;|&#65347;|&#263;|&#265;|&#267;|&#269;|&#231;|&#7689;|&#392;|&#572;|&#42815;|&#8580;|[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184])/g
}, {
    'base': "d",
        'letters': /(&#100;|&#9427;|&#65348;|&#7691;|&#271;|&#7693;|&#7697;|&#7699;|&#7695;|&#273;|&#396;|&#598;|&#599;|&#42874;|&#240;|[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A\u00F0])/g
}, {
    'base': "dz",
        'letters': /(&#499;|&#454;|[\u01F3\u01C6])/g
}, {
    'base': "e",
        'letters': /(&#101;|&#9428;|&#65349;|&#232;|&#233;|&#234;|&#7873;|&#7871;|&#7877;|&#7875;|&#7869;|&#275;|&#7701;|&#7703;|&#277;|&#279;|&#235;|&#7867;|&#283;|&#517;|&#519;|&#7865;|&#7879;|&#553;|&#7709;|&#281;|&#7705;|&#7707;|&#583;|&#603;|&#477;|[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD])/g
}, {
    'base': "f",
        'letters': /(&#102;|&#9429;|&#65350;|&#7711;|&#402;|&#42876;|[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C])/g
}, {
    'base': "g",
        'letters': /(&#103;|&#9430;|&#65351;|&#501;|&#285;|&#7713;|&#287;|&#289;|&#487;|&#291;|&#485;|&#608;|&#42913;|&#7545;|&#42879;|[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F])/g
}, {
    'base': "h",
        'letters': /(&#104;|&#9431;|&#65352;|&#293;|&#7715;|&#7719;|&#543;|&#7717;|&#7721;|&#7723;|&#7830;|&#295;|&#11368;|&#11382;|&#613;|[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265])/g
}, {
    'base': "hv",
        'letters': /(&#405;|[\u0195])/g
}, {
    'base': "i",
        'letters': /(&#105;|&#9432;|&#65353;|&#236;|&#237;|&#238;|&#297;|&#299;|&#301;|&#239;|&#7727;|&#7881;|&#464;|&#521;|&#523;|&#7883;|&#303;|&#7725;|&#616;|&#305;|[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131])/g
}, {
    'base': "ij",
        'letters': /(&#307;|[\u0133])/g
}, {
    'base': "j",
        'letters': /(&#106;|&#9433;|&#65354;|&#309;|&#496;|&#585;|[\u006A\u24D9\uFF4A\u0135\u01F0\u0249])/g
}, {
    'base': "k",
        'letters': /(&#107;|&#9434;|&#65355;|&#7729;|&#489;|&#7731;|&#311;|&#7733;|&#409;|&#11370;|&#42817;|&#42819;|&#42821;|&#42915;|[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3])/g
}, {
    'base': "l",
        'letters': /(&#108;|&#9435;|&#65356;|&#320;|&#314;|&#318;|&#7735;|&#7737;|&#316;|&#7741;|&#7739;|&#322;|&#410;|&#619;|&#11361;|&#42825;|&#42881;|&#42823;|[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u0142\u019A\u026B\u2C61\uA749\uA781\uA747])/g
}, {
    'base': "lj",
        'letters': /(&#457;|[\u01C9])/g
}, {
    'base': "m",
        'letters': /(&#109;|&#9436;|&#65357;|&#7743;|&#7745;|&#7747;|&#625;|&#623;|[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F])/g
}, {
    'base': "n",
        'letters': /(&#110;|&#9437;|&#65358;|&#505;|&#324;|&#241;|&#7749;|&#328;|&#7751;|&#326;|&#7755;|&#7753;|&#414;|&#626;|&#329;|&#42897;|&#42917;|&#331;|[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5\u014B])/g
}, {
    'base': "nj",
        'letters': /(&#460;|[\u01CC])/g
}, {
    'base': "o",
        'letters': /(&#111;|&#9438;|&#65359;|&#242;|&#243;|&#244;|&#7891;|&#7889;|&#7895;|&#7893;|&#245;|&#7757;|&#557;|&#7759;|&#333;|&#7761;|&#7763;|&#335;|&#559;|&#561;|&#246;|&#555;|&#7887;|&#337;|&#466;|&#525;|&#527;|&#417;|&#7901;|&#7899;|&#7905;|&#7903;|&#7907;|&#7885;|&#7897;|&#491;|&#493;|&#248;|&#511;|&#596;|&#42827;|&#42829;|&#629;|[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275])/g
}, {
    'base': "oe",
        'letters': /(&#339;|[\u0153])/g
}, {
    'base': "oi",
        'letters': /(&#419;|[\u01A3])/g
}, {
    'base': "ou",
        'letters': /(&#547;|[\u0223])/g
}, {
    'base': "oo",
        'letters': /(&#42831;|[\uA74F])/g
}, {
    'base': "p",
        'letters': /(&#112;|&#9439;|&#65360;|&#7765;|&#7767;|&#421;|&#7549;|&#42833;|&#42835;|&#42837;|[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755])/g
}, {
    'base': "q",
        'letters': /(&#113;|&#9440;|&#65361;|&#587;|&#42839;|&#42841;|[\u0071\u24E0\uFF51\u024B\uA757\uA759])/g
}, {
    'base': "r",
        'letters': /(&#114;|&#9441;|&#65362;|&#341;|&#7769;|&#345;|&#529;|&#531;|&#7771;|&#7773;|&#343;|&#7775;|&#589;|&#637;|&#42843;|&#42919;|&#42883;|[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783])/g
}, {
    'base': "s",
        'letters': /(&#115;|&#9442;|&#65363;|&#347;|&#7781;|&#349;|&#7777;|&#353;|&#7783;|&#7779;|&#7785;|&#537;|&#351;|&#575;|&#42921;|&#42885;|&#7835;|&#383;|[\u0073\u24E2\uFF53\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B\u017F])/g
}, {
    'base': "ss",
        'letters': /(&#223;|[\u00DF])/g
}, {
    'base': "t",
        'letters': /(&#116;|&#9443;|&#65364;|&#7787;|&#7831;|&#357;|&#7789;|&#539;|&#355;|&#7793;|&#7791;|&#359;|&#429;|&#648;|&#11366;|&#42887;|[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787])/g
}, {
    'base': "th",
        'letters': /(&#254;|[\u00FE])/g
}, {
    'base': "tz",
        'letters': /(&#42793;|[\uA729])/g
}, {
    'base': "u",
        'letters': /(&#117;|&#9444;|&#65365;|&#249;|&#250;|&#251;|&#361;|&#7801;|&#363;|&#7803;|&#365;|&#252;|&#476;|&#472;|&#470;|&#474;|&#7911;|&#367;|&#369;|&#468;|&#533;|&#535;|&#432;|&#7915;|&#7913;|&#7919;|&#7917;|&#7921;|&#7909;|&#7795;|&#371;|&#7799;|&#7797;|&#649;|[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289])/g
}, {
    'base': "v",
        'letters': /(&#118;|&#9445;|&#65366;|&#7805;|&#7807;|&#651;|&#42847;|&#652;|[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C])/g
}, {
    'base': "vy",
        'letters': /(&#42849;|[\uA761])/g
}, {
    'base': "w",
        'letters': /(&#119;|&#9446;|&#65367;|&#7809;|&#7811;|&#373;|&#7815;|&#7813;|&#7832;|&#7817;|&#11379;|[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73])/g
}, {
    'base': "x",
        'letters': /(&#120;|&#9447;|&#65368;|&#7819;|&#7821;|[\u0078\u24E7\uFF58\u1E8B\u1E8D])/g
}, {
    'base': "y",
        'letters': /(&#121;|&#9448;|&#65369;|&#7923;|&#253;|&#375;|&#7929;|&#563;|&#7823;|&#255;|&#7927;|&#7833;|&#7925;|&#436;|&#591;|&#7935;|[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF])/g
}, {
    'base': "z",
        'letters': /(&#122;|&#9449;|&#65370;|&#378;|&#7825;|&#380;|&#382;|&#7827;|&#7829;|&#438;|&#549;|&#576;|&#11372;|&#42851;|[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763])/g
}];

How to select/get drop down option in Selenium 2

in ruby for constantly using, add follow:

module Selenium
  module WebDriver
    class Element
      def select(value)
        self.find_elements(:tag_name => "option").find do |option|
          if option.text == value
            option.click
              return
           end
       end
    end
  end
end

and you will be able to select value:

browser.find_element(:xpath, ".//xpath").select("Value")

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

Best way to convert an ArrayList to a string

You can use a Regex for this. This is as concise as it gets

System.out.println(yourArrayList.toString().replaceAll("\\[|\\]|[,][ ]","\t"));

Bootstrap modal not displaying

  1. Check for all js files, the order should be maintained.
  2. The order should be maintained as
    -> jquery.min.js
    -> bootstrap.min.js
    -> any external js files

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

"FATAL: Module not found error" using modprobe

Ensure that your network is brought down before loading module:

sudo stop networking

It helped me - https://help.ubuntu.com/community/UbuntuBonding

Get changes from master into branch in Git

Scenario :

  • I created a branch from master say branch-1 and pulled it to my local.
  • My Friend created a branch from master say branch-2.
  • He committed some code changes to master.
  • Now I want to take those changes from master branch to my local branch.

Solution

git stash // to save all existing changes in local branch
git checkout master // Switch to master branch from branch-1
git pull // take changes from the master
git checkout branch-1 // switchback to your own branch
git rebase master // merge all the changes and move you git head  forward
git stash apply // reapply all you saved changes 

You can find conflicts on your file after executing "git stash apply". You need to fix it manually and now you are ready to push.

Handling the TAB character in Java

Or you could just perform a trim() on the string to handle the case when people use spaces instead of tabs (unless you are reading makefiles)

Add a properties file to IntelliJ's classpath

This is one of the dumb mistakes I've done. I spent a lot of time trying to debug this problem and tried all the responses posted above, but in the end, it was one of my many dumb mistakes.

I was using org.apache.logging.log4j.Logger (:fml:) whereas I should have used org.apache.log4j.Logger. Using this correct logger saved my evening.

using sql count in a case statement

Close... try:

select 
   Sum(case when rsp_ind = 0 then 1 Else 0 End) as 'New',
   Sum(case when rsp_ind = 1 then 1 else 0 end) as 'Accepted'
from tb_a

How can I merge properties of two JavaScript objects dynamically?

My way:

function mergeObjects(defaults, settings) {
    Object.keys(defaults).forEach(function(key_default) {
        if (typeof settings[key_default] == "undefined") {
            settings[key_default] = defaults[key_default];
        } else if (isObject(defaults[key_default]) && isObject(settings[key_default])) {
            mergeObjects(defaults[key_default], settings[key_default]);
        }
    });

    function isObject(object) {
        return Object.prototype.toString.call(object) === '[object Object]';
    }

    return settings;
}

:)

How to declare a constant map in Golang?

As stated above to define a map as constant is not possible. But you can declare a global variable which is a struct that contains a map.

The Initialization would look like this:

var romanNumeralDict = struct {
    m map[int]string
}{m: map[int]string {
    1000: "M",
    900: "CM",
    //YOUR VALUES HERE
}}

func main() {
    d := 1000
    fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000])
}

varbinary to string on SQL Server

Have a go at the below as I was struggling to

bcp "SELECT CAST(BINARYCOL AS VARCHAR(MAX)) FROM OLTP_TABLE WHERE ID=123123 AND COMPANYID=123" 
queryout "C:\Users\USER\Documents\ps_scripts\res.txt" -c -S myserver.db.com  -U admin -P password

Reference: original post

Index (zero based) must be greater than or equal to zero

This can also happen when trying to throw an ArgumentException where you inadvertently call the ArgumentException constructor overload

public static void Dostuff(Foo bar)
{

   // this works
   throw new ArgumentException(String.Format("Could not find {0}", bar.SomeStringProperty));

   //this gives the error
   throw new ArgumentException(String.Format("Could not find {0}"), bar.SomeStringProperty);

}

What does 'super' do in Python?

I had played a bit with super(), and had recognized that we can change calling order.

For example, we have next hierarchy structure:

    A
   / \
  B   C
   \ /
    D

In this case MRO of D will be (only for Python 3):

In [26]: D.__mro__
Out[26]: (__main__.D, __main__.B, __main__.C, __main__.A, object)

Let's create a class where super() calls after method execution.

In [23]: class A(object): #  or with Python 3 can define class A:
...:     def __init__(self):
...:         print("I'm from A")
...:  
...: class B(A):
...:      def __init__(self):
...:          print("I'm from B")
...:          super().__init__()
...:   
...: class C(A):
...:      def __init__(self):
...:          print("I'm from C")
...:          super().__init__()
...:  
...: class D(B, C):
...:      def __init__(self):
...:          print("I'm from D")
...:          super().__init__()
...: d = D()
...:
I'm from D
I'm from B
I'm from C
I'm from A

    A
   / ?
  B ? C
   ? /
    D

So we can see that resolution order is same as in MRO. But when we call super() in the beginning of the method:

In [21]: class A(object):  # or class A:
...:     def __init__(self):
...:         print("I'm from A")
...:  
...: class B(A):
...:      def __init__(self):
...:          super().__init__()  # or super(B, self).__init_()
...:          print("I'm from B")
...:   
...: class C(A):
...:      def __init__(self):
...:          super().__init__()
...:          print("I'm from C")
...:  
...: class D(B, C):
...:      def __init__(self):
...:          super().__init__()
...:          print("I'm from D")
...: d = D()
...: 
I'm from A
I'm from C
I'm from B
I'm from D

We have a different order it is reversed a order of the MRO tuple.

    A
   / ?
  B ? C
   ? /
    D 

For additional reading I would recommend next answers:

  1. C3 linearization example with super (a large hierarchy)
  2. Important behavior changes between old and new style classes
  3. The Inside Story on New-Style Classes

Need table of key codes for android and presenter

OK, I found it finally.

Key Event This document lists volume up as 24. The key code I was looking for is Alt-Menu and apparently it executes regardless of having the key intercepted.

Thanks to those those who took the time to reply.

What is the most effective way to get the index of an iterator of an std::vector?

I just discovered this: https://greek0.net/boost-range/boost-adaptors-indexed.html

    for (const auto & element : str | boost::adaptors::indexed(0)) {
        std::cout << element.index()
                  << " : "
                  << element.value()
                  << std::endl;
    }

Passing HTML input value as a JavaScript Function Parameter

Use this it will work,

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="a"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    var m = document.getElementById("a").value;
    var n = document.getElementById("b").value;
    var sum = m + n;
    alert(sum);
  }
</script>
</body>

Filter Linq EXCEPT on properties

MoreLinq has something useful for this MoreLinq.Source.MoreEnumerable.ExceptBy

https://github.com/gsscoder/morelinq/blob/master/MoreLinq/ExceptBy.cs

namespace MoreLinq
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    static partial class MoreEnumerable
    {
        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector)
        {
            return ExceptBy(first, second, keySelector, null);
        }

        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <param name="keyComparer">The equality comparer to use to determine whether or not keys are equal.
        /// If null, the default equality comparer for <c>TSource</c> is used.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            if (first == null) throw new ArgumentNullException("first");
            if (second == null) throw new ArgumentNullException("second");
            if (keySelector == null) throw new ArgumentNullException("keySelector");
            return ExceptByImpl(first, second, keySelector, keyComparer);
        }

        private static IEnumerable<TSource> ExceptByImpl<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            var keys = new HashSet<TKey>(second.Select(keySelector), keyComparer);
            foreach (var element in first)
            {
                var key = keySelector(element);
                if (keys.Contains(key))
                {
                    continue;
                }
                yield return element;
                keys.Add(key);
            }
        }
    }
}

How do I configure git to ignore some files locally?

For anyone who wants to ignore files locally in a submodule:

Edit my-parent-repo/.git/modules/my-submodule/info/exclude with the same format as a .gitignore file.

What good are SQL Server schemas?

I know it's an old thread, but I just looked into schemas myself and think the following could be another good candidate for schema usage:

In a Datawarehouse, with data coming from different sources, you can use a different schema for each source, and then e.g. control access based on the schemas. Also avoids the possible naming collisions between the various source, as another poster replied above.

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

The default to open/add rows to a table is Edit Top 200 Rows. If you have more than 200 rows, like me now, then you need to change the default setting. Here's what I did to change the edit default to 300:

  1. Go to Tools in top nav
  2. Select options, then SQL Service Object Explorer (on left)
  3. On right side of panel, click into the field that contains 200 and change to 300 (or whatever number you wish)
  4. Click OK and voila, you're all set!

JNI and Gradle in Android Studio

In my case, I'm on Windows and following the answer by Cameron above only works if you use the full name of the ndk-build which is ndk-build.cmd. I have to clean and rebuild the project, then restart the emulator before getting the app to work (Actually I imported the sample HelloJni from NDK, into Android Studio). However, make sure the path to NDK does not contain space.

Finally, my build.gradle is full listed as below:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.hellojni"
        minSdkVersion 4
        targetSdkVersion 4

        ndk {
            moduleName "hello-jni"
        }

        testApplicationId "com.example.hellojni.tests"
        testInstrumentationRunner "android.test.InstrumentationTestRunner"
    }
    sourceSets.main {
        jni.srcDirs = [] // This prevents the auto generation of Android.mk
//        sourceSets.main.jni.srcDirs = []
        jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project.
    }

    task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
        def ndkDir = android.plugin.ndkFolder
        commandLine "$ndkDir/ndk-build.cmd",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                '-j', Runtime.runtime.availableProcessors(),
                'all',
                'NDK_DEBUG=1'
    }

    task cleanNative(type: Exec, description: 'Clean JNI object files') {
        def ndkDir = android.plugin.ndkFolder
        commandLine "$ndkDir/ndk-build.cmd",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                'clean'
    }

    clean.dependsOn 'cleanNative'

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn buildNative
    }

}


dependencies {
    compile 'com.android.support:support-v4:21.0.3'
}

right click context menu for datagridview

While this question is old, the answers aren't proper. Context menus have their own events on DataGridView. There is an event for row context menu and cell context menu.

The reason for which these answers aren't proper is they do not account for different operation schemes. Accessibility options, remote connections, or Metro/Mono/Web/WPF porting might not work and keyboard shortcuts will down right fail (Shift+F10 or Context Menu key).

Cell selection on right mouse click has to be handled manually. Showing the context menu does not need to be handled as this is handled by the UI.

This completely mimics the approach used by Microsoft Excel. If a cell is part of a selected range, the cell selection doesn't change and neither does CurrentCell. If it isn't, the old range is cleared and the cell is selected and becomes CurrentCell.

If you are unclear on this, CurrentCell is where the keyboard has focus when you press the arrow keys. Selected is whether it is part of SelectedCells. The context menu will show on right click as handled by the UI.

private void dgvAccount_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex != -1 && e.RowIndex != -1 && e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        DataGridViewCell c = (sender as DataGridView)[e.ColumnIndex, e.RowIndex];
        if (!c.Selected)
        {
            c.DataGridView.ClearSelection();
            c.DataGridView.CurrentCell = c;
            c.Selected = true;
        }
    }
}

Keyboard shortcuts do not show the context menu by default, so we have to add them in.

private void dgvAccount_KeyDown(object sender, KeyEventArgs e)
{
    if ((e.KeyCode == Keys.F10 && e.Shift) || e.KeyCode == Keys.Apps)
    {
        e.SuppressKeyPress = true;
        DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
        if (currentCell != null)
        {
            ContextMenuStrip cms = currentCell.ContextMenuStrip;
            if (cms != null)
            {
                Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, false);
                Point p = new Point(r.X + r.Width, r.Y + r.Height);
                cms.Show(currentCell.DataGridView, p);
            }
        }
    }
}

I've reworked this code to work statically, so you can copy and paste them into any event.

The key is to use CellContextMenuStripNeeded since this will give you the context menu.

Here's an example using CellContextMenuStripNeeded where you can specify which context menu to show if you want to have different ones per row.

In this context MultiSelect is True and SelectionMode is FullRowSelect. This is just for the example and not a limitation.

private void dgvAccount_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;

    if (e.RowIndex == -1 || e.ColumnIndex == -1)
        return;
    bool isPayment = true;
    bool isCharge = true;
    foreach (DataGridViewRow row in dgv.SelectedRows)
    {
        if ((string)row.Cells["P/C"].Value == "C")
            isPayment = false;
        else if ((string)row.Cells["P/C"].Value == "P")
            isCharge = false;
    }
    if (isPayment)
        e.ContextMenuStrip = cmsAccountPayment;
    else if (isCharge)
        e.ContextMenuStrip = cmsAccountCharge;
}

private void cmsAccountPayment_Opening(object sender, CancelEventArgs e)
{
    int itemCount = dgvAccount.SelectedRows.Count;
    string voidPaymentText = "&Void Payment"; // to be localized
    if (itemCount > 1)
        voidPaymentText = "&Void Payments"; // to be localized
    if (tsmiVoidPayment.Text != voidPaymentText) // avoid possible flicker
        tsmiVoidPayment.Text = voidPaymentText;
}

private void cmsAccountCharge_Opening(object sender, CancelEventArgs e)
{
    int itemCount = dgvAccount.SelectedRows.Count;
    string deleteChargeText = "&Delete Charge"; //to be localized
    if (itemCount > 1)
        deleteChargeText = "&Delete Charge"; //to be localized
    if (tsmiDeleteCharge.Text != deleteChargeText) // avoid possible flicker
        tsmiDeleteCharge.Text = deleteChargeText;
}

private void tsmiVoidPayment_Click(object sender, EventArgs e)
{
    int paymentCount = dgvAccount.SelectedRows.Count;
    if (paymentCount == 0)
        return;

    bool voidPayments = false;
    string confirmText = "Are you sure you would like to void this payment?"; // to be localized
    if (paymentCount > 1)
        confirmText = "Are you sure you would like to void these payments?"; // to be localized
    voidPayments = (MessageBox.Show(
                    confirmText,
                    "Confirm", // to be localized
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button2
                   ) == DialogResult.Yes);
    if (voidPayments)
    {
        // SQLTransaction Start
        foreach (DataGridViewRow row in dgvAccount.SelectedRows)
        {
            //do Work    
        }
    }
}

private void tsmiDeleteCharge_Click(object sender, EventArgs e)
{
    int chargeCount = dgvAccount.SelectedRows.Count;
    if (chargeCount == 0)
        return;

    bool deleteCharges = false;
    string confirmText = "Are you sure you would like to delete this charge?"; // to be localized
    if (chargeCount > 1)
        confirmText = "Are you sure you would like to delete these charges?"; // to be localized
    deleteCharges = (MessageBox.Show(
                    confirmText,
                    "Confirm", // to be localized
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button2
                   ) == DialogResult.Yes);
    if (deleteCharges)
    {
        // SQLTransaction Start
        foreach (DataGridViewRow row in dgvAccount.SelectedRows)
        {
            //do Work    
        }
    }
}

log4j: Log output of a specific class to a specific appender

Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern it will create 0 byte file and not write anything:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false"/>
        <param name="maxFileSize" value="1GB"/>
        <param name="maxBackupIndex" value="2"/>
        <param name="file" value="/tmp/bd.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <logger name="com.example.mypackage" additivity="false">
        <level value="debug"/>
        <appender-ref ref="bdfile"/>
    </logger>

    <root>
        <priority value="info"/>
        <appender-ref ref="bdfile"/>
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>

Bootstrap 3 Flush footer to bottom. not fixed

Or this

<footer class="navbar navbar-default navbar-fixed-bottom">
    <p class="text-muted" align="center">This is a footer</p>
</footer>

Show dialog from fragment?

    public static void OpenDialog (Activity activity, DialogFragment fragment){

    final FragmentManager fm = ((FragmentActivity)activity).getSupportFragmentManager();

    fragment.show(fm, "tag");
}

Best way to disable button in Twitter's Bootstrap

For input and button:

$('button').prop('disabled', true);

For anchor:

$('a').attr('disabled', true);

Checked in firefox, chrome.

See http://jsfiddle.net/czL54/2/

ASP.NET Background image

body {
    background-image: url('../images/background.jpg');
    background-repeat: no-repeat;
    background-size: cover; /* will auto resize to fill the screen */
}

Make var_dump look pretty

I don't seem to have enough rep to close this as a duplicate, but it is one if someone else can do that. I posted the same thing over at A more pretty/informative Var_dump alternative in PHP? but for the sake of saving time, I'll copy/paste it here too:

I had to add another answer here because I didn't really want to go through the steps in the other solutions. It is extremely simple and requires no extensions, includes etc and is what I prefer. It's very easy and very fast.

First just json_encode the variable in question:

echo json_encode($theResult);

Copy the result you get into the JSON Editor at http://jsoneditoronline.org/ just copy it into the left side pane, click Copy > and it pretty prints the JSON in a really nice tree format.

To each their own, but hopefully this helps some others have one more nice option! :)

How to change font of UIButton with Swift

If you need to change only size (Swift 4.0):

button.titleLabel?.font = button.titleLabel?.font.withSize(12)

C# static class why use?

If a class is declared as static then the variables and methods need to be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

->The main features of a static class are:

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.

Example

static class CollegeRegistration
{
  //All static member variables
   static int nCollegeId; //College Id will be same for all the students studying
   static string sCollegeName; //Name will be same
   static string sColegeAddress; //Address of the college will also same

    //Member functions
   public static int GetCollegeId()
   {
     nCollegeId = 100;
     return (nCollegeID);
   }
    //similarly implementation of others also.
} //class end


public class student
{
    int nRollNo;
    string sName;

    public GetRollNo()
    {
       nRollNo += 1;
       return (nRollNo);
    }
    //similarly ....
    public static void Main()
   {
     //Not required.
     //CollegeRegistration objCollReg= new CollegeRegistration();

     //<ClassName>.<MethodName>
     int cid= CollegeRegistration.GetCollegeId();
    string sname= CollegeRegistration.GetCollegeName();


   } //Main end
}

How to copy from CSV file to PostgreSQL table with headers in CSV file?

With the Python library pandas, you can easily create column names and infer data types from a csv file.

from sqlalchemy import create_engine
import pandas as pd

engine = create_engine('postgresql://user:pass@localhost/db_name')
df = pd.read_csv('/path/to/csv_file')
df.to_sql('pandas_db', engine)

The if_exists parameter can be set to replace or append to an existing table, e.g. df.to_sql('pandas_db', engine, if_exists='replace'). This works for additional input file types as well, docs here and here.

Convert character to ASCII numeric value in java

I was trying the same thing, but best and easy solution would be to use charAt and to access the indexes we should create an integer array of [128] size.

String name = "admin"; 
int ascii = name.charAt(0); 
int[] letters = new int[128]; //this will allocate space with 128byte size.
letters[ascii]++; //increments the value of 97 to 1;
System.out.println("Output:" + ascii); //Outputs 97
System.out.println("Output:" +  letters[ascii]); //Outputs 1 if you debug you'll see 97th index value will be 1.

In case if you want to display ascii values of complete String, you need to do this.

String name = "admin";
char[] val = name.toCharArray();
for(char b: val) {
 int c = b;
 System.out.println("Ascii value of " + b + " is: " + c);
}

Your output, in this case, will be: Ascii value of a is: 97 Ascii value of d is: 100 Ascii value of m is: 109 Ascii value of i is: 105 Ascii value of n is: 110

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Remove some jar file from Libs folder and copy to some other folder, And Go to _Project Properties > Select Java Build Path, Select Libraries, Select Add External Jar, Select the Removed jar to your project, Click save, this will be added under Referenced Library instead of Libs folder. Now clean and Run your project. You dont need to add Any code for MultDex. Its simply worked for me.

Sending an HTTP POST request on iOS

Using Swift 3 or 4 you can access these http request for sever communication.

// For POST data to request

 func postAction()  {
//declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
let parameters = ["id": 13, "name": "jack"] as [String : Any]
//create the url with URL
let url = URL(string: "www.requestURL.php")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
    request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
    print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
    guard error == nil else {
        return
    }
    guard let data = data else {
        return
    }
    do {
        //create json object from data
        if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
            print(json)
            // handle json...
        }
    } catch let error {
        print(error.localizedDescription)
    }
})
task.resume() }

// For get the data from request

func GetRequest()  {
    let urlString = URL(string: "http://www.requestURL.php") //change the url

    if let url = urlString {
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error ?? "")
            } else {
                if let responceData = data {
                    print(responceData) //JSONSerialization
                    do {
                        //create json object from data
                        if let json = try JSONSerialization.jsonObject(with:responceData, options: .mutableContainers) as? [String: Any] {
                            print(json)
                            // handle json...
                        }
                    } catch let error {
                        print(error.localizedDescription)
                    }
                }
            }
        }
        task.resume()
    }
}

// For get the download content like image or video from request

func downloadTask()  {
    // Create destination URL
    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
    //Create URL to the source file you want to download
    let fileURL = URL(string: "http://placehold.it/120x120&text=image1")
    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)
    let request = URLRequest(url:fileURL!)

    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Successfully downloaded. Status code: \(statusCode)")
            }

            do {
                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
            } catch (let writeError) {
                print("Error creating a file \(destinationFileUrl) : \(writeError)")
            }

        } else {
            print("Error took place while downloading a file. Error description: %@", error?.localizedDescription ?? "");
        }
    }
    task.resume()

}

How can Perl's print add a newline by default?

If you're stuck with pre-5.10, then the solutions provided above will not fully replicate the say function. For example

sub say { print @_, "\n"; }

Will not work with invocations such as

say for @arr;

or

for (@arr) {
    say;
}

... because the above function does not act on the implicit global $_ like print and the real say function.

To more closely replicate the perl 5.10+ say you want this function

sub say {
    if (@_) { print @_, "\n"; }
    else { print $_, "\n"; }
}

Which now acts like this

my @arr = qw( alpha beta gamma );
say @arr;
# OUTPUT
# alphabetagamma
#
say for @arr;
# OUTPUT
# alpha
# beta
# gamma
#

The say builtin in perl6 behaves a little differently. Invoking it with say @arr or @arr.say will not just concatenate the array items, but instead prints them separated with the list separator. To replicate this in perl5 you would do this

sub say {
    if (@_) { print join($", @_) . "\n"; }
    else { print $_ . "\n"; }
}

$" is the global list separator variable, or if you're using English.pm then is is $LIST_SEPARATOR

It will now act more like perl6, like so

say @arr;
# OUTPUT
# alpha beta gamma
#

Error: Configuration with name 'default' not found in Android Studio

If you want to use the same library folder for several projects, you can reference it in gradle to an external location like this:

settings.gradle:

include 'app', ':volley'
project(':volley').projectDir = new File('../libraries/volley')

in your app build.gradle

dependencies {
    ...
    compile project(':volley')
...}

Clear text in EditText when entered

final EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);

childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        //Log.d("NNN", "Has focus " + hasFocus);
        if (hasFocus) {
            Toast.makeText(ctx.getApplicationContext(), "got the focus", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(ctx.getApplicationContext(),
            "loss the focus", Toast.LENGTH_SHORT).show();
        }
        return;
    });

Why am I getting ImportError: No module named pip ' right after installing pip?

What solved the issue on my case was go to:

cd C:\Program Files\Python37\Scripts

And run below command:

easy_install.exe pip

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

PHP Echo a large block of text

Check out heredoc. Example:

echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

echo <<<"FOOBAR"
Hello World!
FOOBAR;

The is also nowdoc but no parsing is done inside the block.

echo <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;

Check if value already exists within list of dictionaries?

Based on @Mark Byers great answer, and following @Florent question, just to indicate that it will also work with 2 conditions on list of dics with more than 2 keys:

names = []
names.append({'first': 'Nil', 'last': 'Elliot', 'suffix': 'III'})
names.append({'first': 'Max', 'last': 'Sam', 'suffix': 'IX'})
names.append({'first': 'Anthony', 'last': 'Mark', 'suffix': 'IX'})

if not any(d['first'] == 'Anthony' and d['last'] == 'Mark' for d in names):

    print('Not exists!')
else:
    print('Exists!')

Result:

Exists!

Retrieve WordPress root directory path?

I think this would do the trick:

function get_wp_installation()
{
    $full_path = getcwd();
    $ar = explode("wp-", $full_path);
    return $ar[0];
}

Rounded Corners Image in Flutter

you can use ClipRRect like this :

  Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(25),
                    child: Image.asset(
                      'assets/images/pic13.jpeg',
                      fit: BoxFit.cover,
                    ),
                  ),
                )

you can set your radius, or user for only for topLeft or bottom left like :

Padding(
              padding: const EdgeInsets.all(8.0),
              child: ClipRRect(
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(25)
                ,bottomLeft: Radius.circular(25)),
                child: Image.asset(
                  'assets/images/pic13.jpeg',
                  fit: BoxFit.cover,
                ),
              ),
            )

Double border with different color

You can use the border and box-shadow properties along with CSS pseudo elements to achieve a triple-border sort of effect. See the example below for an idea of how to create three borders at the bottom of a div:

_x000D_
_x000D_
.triple-border:after {_x000D_
    content: " ";_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
    background: #FFE962;_x000D_
    height: 9px;_x000D_
    padding-bottom: 8px;_x000D_
    border-bottom: 9px solid #A3C662;_x000D_
    box-shadow: -2px 11px 0 -1px #34b6af;_x000D_
}
_x000D_
<div class="triple-border">Triple border bottom with multiple colours</div>
_x000D_
_x000D_
_x000D_

You'll have to play around with the values to get the alignment correct. However, you can also achieve more flexibility, e.g. 4 borders if you put some of the attributes in the proper element rather than the pseudo selector.

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

mysqld --initialize to initialize the data directory then mysqld &

If you had already launched mysqld& without mysqld --initialize you might have to delete all files in your data directory

You can also modify /etc/my.cnf to add a custom path to your data directory like this :

[mysqld]
...  
datadir=/path/to/directory

Auto height of div

div's will naturally resize in accordance with their content.

If you set no height on your div, it will expand to contain its conent.

An exception to this rule is when the div contains floating elements. If this is the case you'll need to do a bit extra to ensure that the containing div (wrapper) clears the floats.

Here's some ways to do this:

#wrapper{
overflow:hidden;
}

Or

#wrapper:after
{
content:".";
display:block;
clear:both;
visibility:hidden;
}

When to use AtomicReference in Java?

Another simple example is to do a safe-thread modification in a session object.

public PlayerScore getHighScore() {
    ServletContext ctx = getServletConfig().getServletContext();
    AtomicReference<PlayerScore> holder 
        = (AtomicReference<PlayerScore>) ctx.getAttribute("highScore");
    return holder.get();
}

public void updateHighScore(PlayerScore newScore) {
    ServletContext ctx = getServletConfig().getServletContext();
    AtomicReference<PlayerScore> holder 
        = (AtomicReference<PlayerScore>) ctx.getAttribute("highScore");
    while (true) {
        HighScore old = holder.get();
        if (old.score >= newScore.score)
            break;
        else if (holder.compareAndSet(old, newScore))
            break;
    } 
}

Source: http://www.ibm.com/developerworks/library/j-jtp09238/index.html

OS X Terminal Colors

If you want to have your ls colorized you have to edit your ~/.bash_profile file and add the following line (if not already written) :

source .bashrc

Then you edit or create ~/.bashrc file and write an alias to the ls command :

alias ls="ls -G"

Now you have to type source .bashrc in a terminal if already launched, or simply open a new terminal.

If you want more options in your ls juste read the manual ( man ls ). Options are not exactly the same as in a GNU/Linux system.

Seaborn plots not showing up

My advice is just to give a

plt.figure() and give some sns plot. For example

sns.distplot(data).

Though it will look it doesnt show any plot, When you maximise the figure, you will be able to see the plot.

SQL Insert Multiple Rows

You can use SQL Bulk Insert Statement

BULK INSERT TableName
FROM 'filePath'
WITH
(
  FIELDTERMINATOR = '','',
  ROWTERMINATOR = ''\n'',
  ROWS_PER_BATCH = 10000, 
  FIRSTROW = 2,
  TABLOCK
)

for more reference check

https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=sql%20bulk%20insert

You Can Also Bulk Insert Your data from Code as well

for that Please check below Link:

http://www.codeproject.com/Articles/439843/Handling-BULK-Data-insert-from-CSV-to-SQL-Server

How does the bitwise complement operator (~ tilde) work?

The bit-wise operator is a unary operator which works on sign and magnitude method as per my experience and knowledge.

For example ~2 would result in -3.

This is because the bit-wise operator would first represent the number in sign and magnitude which is 0000 0010 (8 bit operator) where the MSB is the sign bit.

Then later it would take the negative number of 2 which is -2.

-2 is represented as 1000 0010 (8 bit operator) in sign and magnitude.

Later it adds a 1 to the LSB (1000 0010 + 1) which gives you 1000 0011.

Which is -3.

What is the facade design pattern?

A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

The Facade design pattern is a structural pattern as it defines a manner for creating relationships between classes or entities. The facade design pattern is used to define a simplified interface to a more complex subsystem.

The facade pattern is ideal when working with a large number of interdependent classes, or with classes that require the use of multiple methods, particularly when they are complicated to use or difficult to understand. The facade class is a "wrapper" that contains a set of members that are easily understood and simple to use. These members access the subsystem on behalf of the facade user, hiding the implementation details.

The facade design pattern is particularly useful when wrapping subsystems that are poorly designed but cannot be refactored because the source code is unavailable or the existing interface is widely used. Sometimes you may decide to implement more than one facade to provide subsets of functionality for different purposes.

One example use of the facade pattern is for integrating a web site with a business application. The existing software may include large amounts of business logic that must be accessed in a particular manner. The web site may require only limited access to this business logic. For example, the web site may need to show whether an item for sale has reached a limited level of stock. The IsLowStock method of the facade class could return a Boolean value to indicate this. Behind the scenes, this method could be hiding the complexities of processing the current physical stock, incoming stock, allocated items and the low stock level for each item.

Subprocess changing directory

If you want to have cd functionality (assuming shell=True) and still want to change the directory in terms of the Python script, this code will allow 'cd' commands to work.

import subprocess
import os

def cd(cmd):
    #cmd is expected to be something like "cd [place]"
    cmd = cmd + " && pwd" # add the pwd command to run after, this will get our directory after running cd
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # run our new command
    out = p.stdout.read()
    err = p.stderr.read()
    # read our output
    if out != "":
        print(out)
        os.chdir(out[0:len(out) - 1]) # if we did get a directory, go to there while ignoring the newline 
    if err != "":
        print(err) # if that directory doesn't exist, bash/sh/whatever env will complain for us, so we can just use that
    return

Proper usage of Java -D command-line parameters

That should be:

java -Dtest="true" -jar myApplication.jar

Then the following will return the value:

System.getProperty("test");

The value could be null, though, so guard against an exception using a Boolean:

boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );

Note that the getBoolean method delegates the system property value, simplifying the code to:

if( Boolean.getBoolean( "test" ) ) {
   // ...
}

How to split a comma-separated value to columns

You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project).

This is the code part from this page:

CREATE FUNCTION [fn_ParseText2Table]
  (@p_SourceText VARCHAR(MAX)
  ,@p_Delimeter VARCHAR(100)=',' --default to comma delimited.
  )
 RETURNS @retTable
  TABLE([Position] INT IDENTITY(1,1)
   ,[Int_Value] INT
   ,[Num_Value] NUMERIC(18,3)
   ,[Txt_Value] VARCHAR(MAX)
   ,[Date_value] DATETIME
   )
AS
/*
********************************************************************************
Purpose: Parse values from a delimited string
  & return the result as an indexed table
Copyright 1996, 1997, 2000, 2003 Clayton Groom (<A href="mailto:[email protected]">[email protected]</A>)
Posted to the public domain Aug, 2004
2003-06-17 Rewritten as SQL 2000 function.
 Reworked to allow for delimiters > 1 character in length
 and to convert Text values to numbers
2016-04-05 Added logic for date values based on "new" ISDATE() function, Updated to use XML approach, which is more efficient.
********************************************************************************
*/


BEGIN
 DECLARE @w_xml xml;
 SET @w_xml = N'<root><i>' + replace(@p_SourceText, @p_Delimeter,'</i><i>') + '</i></root>';


 INSERT INTO @retTable
     ([Int_Value]
    , [Num_Value]
    , [Txt_Value]
    , [Date_value]
     )
     SELECT CASE
       WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
       THEN CAST(CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC) AS INT)
      END AS [Int_Value]
    , CASE
       WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
       THEN CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC(18, 3))
      END AS [Num_Value]
    , [i].value('.', 'VARCHAR(MAX)') AS [txt_Value]
    , CASE
       WHEN ISDATE([i].value('.', 'VARCHAR(MAX)')) = 1
       THEN CAST([i].value('.', 'VARCHAR(MAX)') AS DATETIME)
      END AS [Num_Value]
     FROM @w_xml.nodes('//root/i') AS [Items]([i]);
 RETURN;
END;
GO

add Shadow on UIView using swift 3

Swift 5 Just call this function and pass your view

public func setViewSettingWithBgShade(view: UIView)
{
    view.layer.cornerRadius = 8
    view.layer.borderWidth = 1
    view.layer.borderColor = AppTextFieldBorderColor.cgColor

    //MARK:- Shade a view
    view.layer.shadowOpacity = 0.5
    view.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
    view.layer.shadowRadius = 3.0
    view.layer.shadowColor = UIColor.black.cgColor
    view.layer.masksToBounds = false
}

add a temporary column with a value

I giving you an example in wich the TABLE registrofaena doesn't have the column called minutos. Minutos is created and it content is a result of divide demora/60, in other words, i created a column to show the values of the delay in minutes.

This is the query:

SELECT idfaena,fechahora,demora, demora/60 as minutos,comentario 
FROM registrofaena  
WHERE fecha>='2018-10-17' AND comentario <> '' 
ORDER BY idfaena ASC;

This is the view:

This is the result

Opening popup windows in HTML

I feel like this is the simplest way. (Feel free to change the width and height values).

<a href="http://www.google.com" 
target="popup" 
onclick="window.open('http://www.google.com','popup','width=600,height=600'); return false;">
Link Text goes here...
</a>

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

NodeJS w/Express Error: Cannot GET /

You need to define a root route.

app.get('/', function(req, res) {
  // do something here.
});

Oh and you cannot specify a file within the express.static. It needs to be a directory. The app.get('/'.... will be responsible to render that file accordingly. You can use express' render method, but your going to have to add some configuration options that will tell express where your views are, traditionally within the app/views/ folder.

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

For anyone still having this problem: Use NuGet to install: Microsoft.EntityFrameworkCore.Proxies

This problem is related to the use of Castle Proxy with EFCore.

How to use refs in React with Typescript

Since React 16.3 the way to add refs is to use React.createRef as Jeff Bowen pointed in his answer. However you can take advantage of Typescript to better type your ref.

In your example you're using ref on input element. So they way I would do it is:

class SomeComponent extends React.Component<IProps, IState> {
    private inputRef: React.RefObject<HTMLInputElement>;
    constructor() {
        ...
        this.inputRef = React.createRef();
    }

    ...

    render() {
        <input type="text" ref={this.inputRef} />;
    }
}

By doing this when you want to make use of that ref you have access to all input methods:

someMethod() {
    this.inputRef.current.focus(); // 'current' is input node, autocompletion, yay!
}

You can use it on custom components as well:

private componentRef: React.RefObject<React.Component<IProps>>;

and then have, for example, access to props :

this.componentRef.current.props; // 'props' satisfy IProps interface

How to find all occurrences of a substring?

>>> help(str.find)
Help on method_descriptor:

find(...)
    S.find(sub [,start [,end]]) -> int

Thus, we can build it ourselves:

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches

list(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]

No temporary strings or regexes required.

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

I resolved it by :

1) Sync Project with gradle files
2) Build -> Clean Project
3) Build -> Rebuild Project
4) File -> Invalidate caches

//imp step
5) Check your xml files properly.

Intellij idea subversion checkout error: `Cannot run program "svn"`

If you're going with Manoj's solution (https://stackoverflow.com/a/29509007/2024713) and still having the problem try switching off "Enable interactive mode" if available in your version of IntelliJ. It worked for me

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

For Java, from a command line:

java -version

will indicate whether it's 64-bit or not.

Output from the console on my Ubuntu box:

java version "1.6.0_12-ea"
Java(TM) SE Runtime Environment (build 1.6.0_12-ea-b03)
Java HotSpot(TM) 64-Bit Server VM (build 11.2-b01, mixed mode)

IE will indicate 64-bit versions in the About dialog, I believe.

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

I just think of Rebuild as performing the Clean first followed by the Build. Perhaps I am wrong ... comments?

Stretch child div height to fill parent that has dynamic height

Add the following CSS:

For the parent div:

style="display: flex;"

For child div:

style="align-items: stretch;"

Why do you use typedef when declaring an enum in C++?

It's a C heritage, in C, if you do :

enum TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
};

you'll have to use it doing something like :

enum TokenType foo;

But if you do this :

typedef enum e_TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

You'll be able to declare :

TokenType foo;

But in C++, you can use only the former definition and use it as if it were in a C typedef.

Copying files from one directory to another in Java

    File file = fileChooser.getSelectedFile();
    String selected = fc.getSelectedFile().getAbsolutePath();
     File srcDir = new File(selected);
     FileInputStream fii;
     FileOutputStream fio;
    try {
         fii = new FileInputStream(srcDir);
         fio = new FileOutputStream("C:\\LOvE.txt");
         byte [] b=new byte[1024];
         int i=0;
        try {
            while ((fii.read(b)) > 0)
            {

              System.out.println(b);
              fio.write(b);
            }
            fii.close();
            fio.close();

How to disable Compatibility View in IE

If you're using ASP.NET MVC, I found Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1") in a code block in _Layout to work quite well:

@Code
    Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1")
End Code
<!DOCTYPE html>
everything else

How to display multiple images in one figure correctly?

You could try the following:

import matplotlib.pyplot as plt
import numpy as np

def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional



# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}

# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)

plt.show()

However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.

I hope this helps.

Remove a specific string from an array of string

It is not possible in on step or you need to keep the reference to the array. If you can change the reference this can help:

      String[] n = new String[]{"google","microsoft","apple"};
      final List<String> list =  new ArrayList<String>();
      Collections.addAll(list, n); 
      list.remove("apple");
      n = list.toArray(new String[list.size()]);

I not recommend the following but if you worry about performance:

      String[] n = new String[]{"google","microsoft","apple"};
      final String[] n2 = new String[2]; 
      System.arraycopy(n, 0, n2, 0, n2.length);
      for (int i = 0, j = 0; i < n.length; i++)
      {
        if (!n[i].equals("apple"))
        {
          n2[j] = n[i];
          j++;
        }      
      }

I not recommend it because the code is a lot more difficult to read and maintain.

Mockito. Verify method arguments

  • You don't need the eq matcher if you don't use other matchers.
  • You are not using the correct syntax - your method call should be outside the .verify(mock). You are now initiating verification on the result of the method call, without verifying anything (not making a method call). Hence all tests are passing.

You code should look like:

Mockito.verify(mock).mymethod(obj);
Mockito.verify(mock).mymethod(null);
Mockito.verify(mock).mymethod("something_else");

How to check if an array value exists?

in_array() is fine if you're only checking but if you need to check that a value exists and return the associated key, array_search is a better option.

$data = [
    'hello',
    'world'
];

$key = array_search('world', $data);

if ($key) {
    echo 'Key is ' . $key;
} else {
    echo 'Key not found';
}

This will print "Key is 1"

Setting background images in JFrame

Try this :

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        try {
            f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg")))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        f.pack();
        f.setVisible(true);
    }

}

By the way, this will result in the content pane not being a container. If you want to add things to it you have to subclass a JPanel and override the paintComponent method.

FormData.append("key", "value") is not working

If you are in Chrome you can check the Post Data

Here is How to check the Post data

  1. Go to Network Tab
  2. Look for the Link to which you are sending Post Data
  3. Click on it
  4. In the Headers, you can check Request Payload to check the post data

Chrome's DevTools

Location of the android sdk has not been setup in the preferences in mac os?

If you already setup location in preferences, but see that error, try to create folder "add-ons" in your sdk folder

List of phone number country codes

There is an Excel file with regexps here. You can easily "convert" it to XML and you will be able to determine country by the full phone number.

UPD: The file that I referenced 4 years ago is no longer accessible. I would recommend using Google's libphonenumber.

The answer to Extract code country from phone number [libphonenumber] will show you the proper way to receive country code from a phone number.

Returning null in a method whose signature says return int?

The type int is a primitive and it cannot be null, if you want to return null, mark the signature as

public Integer pollDecrementHigherKey(int x) {
    x = 10;

    if (condition) {
        return x; // This is auto-boxing, x will be automatically converted to Integer
    } else if (condition2) {
        return null; // Integer inherits from Object, so it's valid to return null
    } else {
        return new Integer(x); // Create an Integer from the int and then return
    }
    
    return 5; // Also will be autoboxed and converted into Integer
}

How to make the web page height to fit screen height

you can use css to set the body tag to these settings:

body
{
padding:0px;
margin:0px;
width:100%;
height:100%;
}

VBA array sort function?

Natural Number (Strings) Quick Sort

Just to pile onto the topic. Normally, if you sort strings with numbers you'll get something like this:

    Text1
    Text10
    Text100
    Text11
    Text2
    Text20

But you really want it to recognize the numerical values and be sorted like

    Text1
    Text2
    Text10
    Text11
    Text20
    Text100

Here's how to do it...

Note:

  • I stole the Quick Sort from the internet a long time ago, not sure where now...
  • I translated the CompareNaturalNum function which was originally written in C from the internet as well.
  • Difference from other Q-Sorts: I don't swap the values if the BottomTemp = TopTemp

Natural Number Quick Sort

Public Sub QuickSortNaturalNum(strArray() As String, intBottom As Integer, intTop As Integer)
Dim strPivot As String, strTemp As String
Dim intBottomTemp As Integer, intTopTemp As Integer

    intBottomTemp = intBottom
    intTopTemp = intTop

    strPivot = strArray((intBottom + intTop) \ 2)

    Do While (intBottomTemp <= intTopTemp)
        ' < comparison of the values is a descending sort
        Do While (CompareNaturalNum(strArray(intBottomTemp), strPivot) < 0 And intBottomTemp < intTop)
            intBottomTemp = intBottomTemp + 1
        Loop
        Do While (CompareNaturalNum(strPivot, strArray(intTopTemp)) < 0 And intTopTemp > intBottom) '
            intTopTemp = intTopTemp - 1
        Loop
        If intBottomTemp < intTopTemp Then
            strTemp = strArray(intBottomTemp)
            strArray(intBottomTemp) = strArray(intTopTemp)
            strArray(intTopTemp) = strTemp
        End If
        If intBottomTemp <= intTopTemp Then
            intBottomTemp = intBottomTemp + 1
            intTopTemp = intTopTemp - 1
        End If
    Loop

    'the function calls itself until everything is in good order
    If (intBottom < intTopTemp) Then QuickSortNaturalNum strArray, intBottom, intTopTemp
    If (intBottomTemp < intTop) Then QuickSortNaturalNum strArray, intBottomTemp, intTop
End Sub

Natural Number Compare(Used in Quick Sort)

Function CompareNaturalNum(string1 As Variant, string2 As Variant) As Integer
'string1 is less than string2 -1
'string1 is equal to string2 0
'string1 is greater than string2 1
Dim n1 As Long, n2 As Long
Dim iPosOrig1 As Integer, iPosOrig2 As Integer
Dim iPos1 As Integer, iPos2 As Integer
Dim nOffset1 As Integer, nOffset2 As Integer

    If Not (IsNull(string1) Or IsNull(string2)) Then
        iPos1 = 1
        iPos2 = 1
        Do While iPos1 <= Len(string1)
            If iPos2 > Len(string2) Then
                CompareNaturalNum = 1
                Exit Function
            End If
            If isDigit(string1, iPos1) Then
                If Not isDigit(string2, iPos2) Then
                    CompareNaturalNum = -1
                    Exit Function
                End If
                iPosOrig1 = iPos1
                iPosOrig2 = iPos2
                Do While isDigit(string1, iPos1)
                    iPos1 = iPos1 + 1
                Loop

                Do While isDigit(string2, iPos2)
                    iPos2 = iPos2 + 1
                Loop

                nOffset1 = (iPos1 - iPosOrig1)
                nOffset2 = (iPos2 - iPosOrig2)

                n1 = Val(Mid(string1, iPosOrig1, nOffset1))
                n2 = Val(Mid(string2, iPosOrig2, nOffset2))

                If (n1 < n2) Then
                    CompareNaturalNum = -1
                    Exit Function
                ElseIf (n1 > n2) Then
                    CompareNaturalNum = 1
                    Exit Function
                End If

                ' front padded zeros (put 01 before 1)
                If (n1 = n2) Then
                    If (nOffset1 > nOffset2) Then
                        CompareNaturalNum = -1
                        Exit Function
                    ElseIf (nOffset1 < nOffset2) Then
                        CompareNaturalNum = 1
                        Exit Function
                    End If
                End If
            ElseIf isDigit(string2, iPos2) Then
                CompareNaturalNum = 1
                Exit Function
            Else
                If (Mid(string1, iPos1, 1) < Mid(string2, iPos2, 1)) Then
                    CompareNaturalNum = -1
                    Exit Function
                ElseIf (Mid(string1, iPos1, 1) > Mid(string2, iPos2, 1)) Then
                    CompareNaturalNum = 1
                    Exit Function
                End If

                iPos1 = iPos1 + 1
                iPos2 = iPos2 + 1
            End If
        Loop
        ' Everything was the same so far, check if Len(string2) > Len(String1)
        ' If so, then string1 < string2
        If Len(string2) > Len(string1) Then
            CompareNaturalNum = -1
            Exit Function
        End If
    Else
        If IsNull(string1) And Not IsNull(string2) Then
            CompareNaturalNum = -1
            Exit Function
        ElseIf IsNull(string1) And IsNull(string2) Then
            CompareNaturalNum = 0
            Exit Function
        ElseIf Not IsNull(string1) And IsNull(string2) Then
            CompareNaturalNum = 1
            Exit Function
        End If
    End If
End Function

isDigit(Used in CompareNaturalNum)

Function isDigit(ByVal str As String, pos As Integer) As Boolean
Dim iCode As Integer
    If pos <= Len(str) Then
        iCode = Asc(Mid(str, pos, 1))
        If iCode >= 48 And iCode <= 57 Then isDigit = True
    End If
End Function

Batch / Find And Edit Lines in TXT file

On a native Windows install, you can either use batch(cmd.exe) or vbscript without the need to get external tools. Here's an example in vbscript:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    If InStr(strLine,"ex3")> 0 Then
        strLine = Replace(strLine,"ex3","ex5")
    End If 
    WScript.Echo strLine
Loop    

Save as myreplace.vbs and on the command line:

c:\test> cscript /nologo myreplace.vbs  > newfile
c:\test> ren newfile file.txt

Is there an easy way to convert Android Application to IPad, IPhone

I think you cannot speak of a "conversion" here. That will be a whole project. To "convert" it i think you have to write it again for the iphone.

Have a look at this question:

Is there a multiplatform framework for developing iPhone / Android applications?

As you can see from the answers there, there is no good way of developing applications for both platforms at the same time (except if you're developing games where flash makes it easy to be portable).

How do I use FileSystemObject in VBA?

After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.

Dim intChoice As Integer
Dim strPath As String

' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show

' Get back the user option
If intChoice <> 0 Then
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
    Exit Sub
End If

Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String

Set fsoStream = FSO.OpenTextFile(strPath)

Do Until fsoStream.AtEndOfStream = True
    strLine = fsoStream.ReadLine
    ' ... do your work ...
Loop

fsoStream.Close
Set FSO = Nothing

Hope it help!

Best regards

Fabio

SQL update statement in C#

This is not a correct method of updating record in SQL:

command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";

You should write it like this:

command.CommandText = "UPDATE Student 
SET Address = @add, City = @cit Where FirstName = @fn and LastName = @add";

Then you add the parameters same as you added them for the insert operation.

PL/SQL print out ref cursor returned by a stored procedure

If you want to print all the columns in your select clause you can go with the autoprint command.

CREATE OR REPLACE PROCEDURE sps_detail_dtest(v_refcur OUT sys_refcursor)
AS
BEGIN
  OPEN v_refcur FOR 'select * from dummy_table';
END;

SET autoprint on;

--calling the procedure
VAR vcur refcursor;
DECLARE 
BEGIN
  sps_detail_dtest(vrefcur=>:vcur);
END;

Hope this gives you an alternate solution

How to use hex color values

Swift 2.0:

Make an extension of UIColor.

extension UIColor {
    convenience init(hexString:String) {
        let hexString:NSString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        let scanner            = NSScanner(string: hexString as String)
        if (hexString.hasPrefix("#")) {
            scanner.scanLocation = 1
        }

        var color:UInt32 = 0
        scanner.scanHexInt(&color)

        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask

        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        self.init(red:red, green:green, blue:blue, alpha:1)
    }

    func toHexString() -> String {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
        return NSString(format:"#%06x", rgb) as String
    }

}

Usage:

//Hex to Color
    let countPartColor =  UIColor(hexString: "E43038")

//Color to Hex
let colorHexString =  UIColor(red: 228, green: 48, blue: 56, alpha: 1.0).toHexString()

SQL Server CASE .. WHEN .. IN statement

Try this...

SELECT
    AlarmEventTransactionTableTable.TxnID,
    CASE
        WHEN DeviceID IN('7', '10', '62', '58', '60',
                 '46', '48', '50', '137', '139',
                 '142', '143', '164') THEN '01'
        WHEN DeviceID IN('8', '9', '63', '59', '61',
                 '47', '49', '51', '138', '140',
                 '141', '144', '165') THEN '02'
        ELSE 'NA' END AS clocking,
    AlarmEventTransactionTable.DateTimeOfTxn
 FROM
    multiMAXTxn.dbo.AlarmEventTransactionTable

Just remove highlighted string

SELECT AlarmEventTransactionTableTable.TxnID, CASE AlarmEventTransactions.DeviceID WHEN DeviceID IN('7', '10', '62', '58', '60', ...)

onclick="location.href='link.html'" does not load page in Safari

try

_x000D_
_x000D_
<select onchange="location=this.value">_x000D_
    <option value="unit_01.htm">Unit 1</option>_x000D_
    <option value="#5.2" selected >Bookmark 2</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Upload Image using POST form data in Python-requests

import requests

image_file_descriptor = open('test.jpg', 'rb')
# Requests makes it simple to upload Multipart-encoded files 
files = {'media': image_file_descriptor}
url = '...'
requests.post(url, files=files)
image_file_descriptor.close()

Don't forget to close the descriptor, it prevents bugs: Is explicitly closing files important?

Each for object?

A javascript Object does not have a standard .each function. jQuery provides a function. See http://api.jquery.com/jQuery.each/ The below should work

$.each(object, function(index, value) {
    console.log(value);
}); 

Another option would be to use vanilla Javascript using the Object.keys() and the Array .map() functions like this

Object.keys(object).map(function(objectKey, index) {
    var value = object[objectKey];
    console.log(value);
});

See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/keys and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

These are usually better than using a vanilla Javascript for-loop, unless you really understand the implications of using a normal for-loop and see use for it's specific characteristics like looping over the property chain.

But usually, a for-loop doesn't work better than jQuery or Object.keys().map(). I'll go into two potential issues with using a plain for-loop below.


Right, so also pointed out in other answers, a plain Javascript alternative would be

for(var index in object) { 
    var attr = object[index]; 
}

There are two potential issues with this:

1 . You want to check whether the attribute that you are finding is from the object itself and not from up the prototype chain. This can be checked with the hasOwnProperty function like so

for(var index in object) { 
   if (object.hasOwnProperty(index)) {
       var attr = object[index];
   }
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty for more information.

The jQuery.each and Object.keys functions take care of this automatically.

2 . Another potential issue with a plain for-loop is that of scope and non-closures. This is a bit complicated, but take for example the following code. We have a bunch of buttons with ids button0, button1, button2 etc, and we want to set an onclick on them and do a console.log like this:

<button id='button0'>click</button>
<button id='button1'>click</button>
<button id='button2'>click</button>

var messagesByButtonId = {"button0" : "clicked first!", "button1" : "clicked middle!", "button2" : "clicked last!"];
for(var buttonId in messagesByButtonId ) { 
   if (messagesByButtonId.hasOwnProperty(buttonId)) {
       $('#'+buttonId).click(function() {
           var message = messagesByButtonId[buttonId];
           console.log(message);
       });
   }
}

If, after some time, we click any of the buttons we will always get "clicked last!" in the console, and never "clicked first!" or "clicked middle!". Why? Because at the time that the onclick function is executed, it will display messagesByButtonId[buttonId] using the buttonId variable at that moment. And since the loop has finished at that moment, the buttonId variable will still be "button2" (the value it had during the last loop iteration), and so messagesByButtonId[buttonId] will be messagesByButtonId["button2"], i.e. "clicked last!".

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures for more information on closures. Especially the last part of that page that covers our example.

Again, jQuery.each and Object.keys().map() solve this problem automatically for us, because it provides us with a function(index, value) (that has closure) so we are safe to use both index and value and rest assured that they have the value that we expect.

How to expand 'select' option width after the user wants to select an option

Okay, this option is pretty hackish but should work.

$(document).ready( function() {
$('#select').change( function() {
    $('#hiddenDiv').html( $('#select').val() );
    $('#select').width( $('#hiddenDiv').width() );
 }
 }

Which would offcourse require a hidden div.

<div id="hiddenDiv" style="visibility:hidden"></div>

ohh and you will need jQuery

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

Why Java Calendar set(int year, int month, int date) not returning correct date?

1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:

c1.set(2000, Calendar.JANUARY, 30);

Check a collection size with JSTL

You can use like this

${fn:length(numList)}

How do I turn off Oracle password expiration?

As the other answers state, changing the user's profile (e.g. the 'DEFAULT' profile) appropriately will lead to passwords, that once set, will never expire.

However, as one commenter points out, passwords set under the profile's old values may already be expired, and (if after the profile's specified grace period) the account locked.

The solution for expired passwords with locked accounts (as provided in an answering comment) is to use one version of the ALTER USER command:

ALTER USER xyz_user ACCOUNT UNLOCK;

However the unlock command only works for accounts where the account is actually locked, but not for those accounts that are in the grace period, i.e. where the password is expired but the account is not yet locked. For these accounts the password must be reset with another version of the ALTER USER command:

ALTER USER xyz_user IDENTIFIED BY new_password;

Below is a little SQL*Plus script that a privileged user (e.g. user 'SYS') can use to reset a user's password to the current existing hashed value stored in the database.

EDIT: Older versions of Oracle store the password or password-hash in the pword column, newer versions of Oracle store the password-hash in the spare4 column. Script below changed to collect the pword and spare4 columns, but to use the spare4 column to reset the user's account; modify as needed.

REM Tell SQL*Plus to show before and after versions of variable substitutions.
SET VERIFY ON
SHOW VERIFY

REM Tell SQL*Plus to use the ampersand '&' to indicate variables in substitution/expansion.
SET DEFINE '&'
SHOW DEFINE

REM Specify in a SQL*Plus variable the account to 'reset'.
REM Note that user names are case sensitive in recent versions of Oracle.
REM DEFINE USER_NAME = 'xyz_user'

REM Show the status of the account before reset.
SELECT
  ACCOUNT_STATUS,
  TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
  TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
  DBA_USERS
WHERE
  USERNAME = '&USER_NAME';

REM Create SQL*Plus variable to hold the existing values of the password and spare4 columns.
DEFINE OLD_SPARE4 = ""
DEFINE OLD_PASSWORD = ""

REM Tell SQL*Plus where to store the values to be selected with SQL.
REM Note that the password hash value is stored in spare4 column in recent versions of Oracle,
REM   and in the password column in older versions of Oracle.
COLUMN SPARE4HASH NEW_VALUE OLD_SPARE4
COLUMN PWORDHASH NEW_VALUE OLD_PASSWORD

REM Select the old spare4 and password columns as delimited strings 
SELECT 
  '''' || SPARE4 || '''' AS SPARE4HASH,
  '''' || PASSWORD || '''' AS PWORDHASH
FROM 
  SYS.USER$ 
WHERE 
  NAME = '&USER_NAME';

REM Show the contents of the SQL*Plus variables
DEFINE OLD_SPARE4
DEFINE OLD_PASSWORD

REM Reset the password - Older versions of Oracle (e.g. Oracle 10g and older) 
REM ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_PASSWORD;

REM Reset the password - Newer versions of Oracle (e.g. Oracle 11g and newer) 
ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_SPARE4;

REM Show the status of the account after reset
SELECT
  ACCOUNT_STATUS,
  TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
  TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
  DBA_USERS
WHERE
  USERNAME = '&USER_NAME';

How much should a function trust another function

The addEdge is trusting more than the correction of the addNode method. It's also trusting that the addNode method has been invoked by other method. I'd recommend to include check if m is not null.

excel - if cell is not blank, then do IF statement

You need to use AND statement in your formula

=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")

And if both conditions are met, return 1.

You could also add more conditions in your AND statement.

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

Canvas width and height in HTML5

The canvas DOM element has .height and .width properties that correspond to the height="…" and width="…" attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:

var canvas = document.getElementsByTagName('canvas')[0];
canvas.width  = 800;
canvas.height = 600;

Note that this clears the canvas, though you should follow with ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height); to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.

Note further that the height and width are the logical canvas dimensions used for drawing and are different from the style.height and style.width CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:

// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width  = 400;
canvas.height = 300; 
canvas.style.width  = '800px';
canvas.style.height = '600px';

See this live example of a canvas that is zoomed in by 4x.

_x000D_
_x000D_
var c = document.getElementsByTagName('canvas')[0];_x000D_
var ctx = c.getContext('2d');_x000D_
ctx.lineWidth   = 1;_x000D_
ctx.strokeStyle = '#f00';_x000D_
ctx.fillStyle   = '#eff';_x000D_
_x000D_
ctx.fillRect(  10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.fillRect(   40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.fillRect(   70, 10, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );_x000D_
_x000D_
ctx.strokeStyle = '#fff';_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );
_x000D_
body { background:#eee; margin:1em; text-align:center }_x000D_
canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }
_x000D_
<canvas width="100" height="40"></canvas>_x000D_
<p>Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.</p>
_x000D_
_x000D_
_x000D_

What is attr_accessor in Ruby?

attr_accessor is very simple:

attr_accessor :foo

is a shortcut for:

def foo=(val)
  @foo = val
end

def foo
  @foo
end

it is nothing more than a getter/setter for an object

Pass variables between two PHP pages without using a form or the URL of page

<?php
session_start();

$message1 = "A message";
$message2 = "Another message";

$_SESSION['firstMessage'] = $message1;
$_SESSION['secondMessage'] = $message2; 
?>

Stores the sessions on page 1 then on page 2 do

<?php
session_start();

echo $_SESSION['firstMessage'];
echo $_SESSION['secondMessage'];
?>

Increase max execution time for php

Use mod_php7.c instead of mod_php5.c for PHP 7

Example

<IfModule mod_php7.c>
   php_value max_execution_time 500
</IfModule>

android: how to change layout on button click?

I know I'm coming to this late, but what the heck.

I've got almost the exact same code as Kris, using just one Activity but with 2 different layouts/views, and I want to switch between the layouts at will.

As a test, I added 2 menu options, each one switches the view:

public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.item1:
                setContentView(R.layout.main);
                return true;
            case R.id.item2:
                setContentView(R.layout.alternate);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Note, I've got one Activity class. This works perfectly. So I have no idea why people are suggesting using different Activities / Intents. Maybe someone can explain why my code works and Kris's didn't.

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.

pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')

Swift: Sort array of objects alphabetically

let sortArray =  array.sorted(by: { $0.name.lowercased() < $1.name.lowercased() })

jQuery.ajax returns 400 Bad Request

Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.

$.ajax({
    type: 'get',

must be met with

app.get('/', function(req, res) {

=============== and for post

$.ajax({
    type: 'post',

must be met with

app.post('/', function(req, res) {

Why aren't programs written in Assembly more often?

I've been programming in assembly now for about a month. I often write a piece of code in C and then compile it to assembly to assist me. Perhaps I am not utilizing the full optimizing power of the C compiler but it appears that my C asm source is including unnecessary operations. So I am beginning to see that the talk of a good C compiler outperforming a good assembly coder is not always true.

Anyways, my assembly programs are so fast. And the more I use assembly the less time it takes me to write out my code because it's really not that hard. Also the comment about assembly having poor legibility is not true. If you label your programs correctly and make comments when there is additional elaboration needed you should be all set. In fact in ways assembly is more clear to the programmer because they are seeing what is happening at the level of the processor. I don't know about other programmers but for me I like knowing what's happening, rather than things being in a sort of black box.

With that said the real advantage of compilers is that a compiler can understand patterns and relationships and then automatically code them in the appropriate locations in the source. One popular example are virtual functions in C++ which requires the compiler to optimally map function pointers. However a compiler is limited to doing what the maker of the compiler allows the compiler to do. This leads to programmers sometimes having to resort to doing bizarre things with their code , adding coding time, when they could have been done trivially with assembly.

Personally I think the marketplace heavily supports high level languages. If assembly language was the only language in existence today then their would be about 70% less people programming and who knows where our world would be, probably back in the 90's. Higher level languages appeal to a broader range of people. This allows a higher supply of programmers to build the needed infrastructure of our world. Developing nations like China and India benefit heavily from languages like Java. These countries will fast develop their IT infrastructure and people will become more interconnected. So my point is that high level languages are popular not because they produce superior code but because they help to meet demand in the world's marketplaces.

input checkbox true or checked or yes

Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.

disabled, readonly and ismap input's attributes go on the same way.

EDITED

empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin

How to update value of a key in dictionary in c#?

Just use the indexer and update directly:

dictionary["cat"] = 3

jQuery addClass onClick

$('#button').click(function(){
    $(this).addClass('active');
});

How to disable the resize grabber of <textarea>?

<textarea style="resize:none" name="name" cols="num" rows="num"></textarea>

Just an example

Initialize Array of Objects using NSArray

This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.

NSArray *data = @[@"The String Value"];

if you need to send more than just 1 string value, you could also use

NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];

then you can send it to the function like below

theFunction(data);

Retaining file permissions with Git

Git is Version Control System, created for software development, so from the whole set of modes and permissions it stores only executable bit (for ordinary files) and symlink bit. If you want to store full permissions, you need third party tool, like git-cache-meta (mentioned by VonC), or Metastore (used by etckeeper). Or you can use IsiSetup, which IIRC uses git as backend.

See Interfaces, frontends, and tools page on Git Wiki.

Is there an equivalent of CSS max-width that works in HTML emails?

This is the solution that worked for me

https://gist.github.com/elidickinson/5525752#gistcomment-1649300, thanks to @philipp-klinz

<table cellpadding="0" cellspacing="0" border="0" style="padding:0px;margin:0px;width:100%;">
    <tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20">&nbsp;</td></tr>
     <tr>
        <td style="padding:0px;margin:0px;">&nbsp;</td>
        <td style="padding:0px;margin:0px;" width="560"><!-- max width goes here -->

             <!-- PLACE CONTENT HERE -->

        </td>
        <td style="padding:0px;margin:0px;">&nbsp;</td>
    </tr>
    <tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20">&nbsp;</td></tr>
</table>

Is Unit Testing worth the effort?

If your existing code base doesn't lend itself to unit testing, and it's already in production, you might create more problems than you solve by trying to refactor all of your code so that it is unit-testable.

You may be better off putting efforts towards improving your integration testing instead. There's lots of code out there that's just simpler to write without a unit test, and if a QA can validate the functionality against a requirements document, then you're done. Ship it.

The classic example of this in my mind is a SqlDataReader embedded in an ASPX page linked to a GridView. The code is all in the ASPX file. The SQL is in a stored procedure. What do you unit test? If the page does what it's supposed to do, should you really redesign it into several layers so you have something to automate?

Why is enum class preferred over plain enum?

The basic advantage of using enum class over normal enums is that you may have same enum variables for 2 different enums and still can resolve them(which has been mentioned as type safe by OP)

For eg:

enum class Color1 { red, green, blue };    //this will compile
enum class Color2 { red, green, blue };

enum Color1 { red, green, blue };    //this will not compile 
enum Color2 { red, green, blue };

As for the basic enums, compiler will not be able to distinguish whether red is refering to the type Color1 or Color2 as in hte below statement.

enum Color1 { red, green, blue };   
enum Color2 { red, green, blue };
int x = red;    //Compile time error(which red are you refering to??)

How to reload page every 5 seconds?

If you are developing and testing in Firefox, there's a plug-in called "ReloadEvery" is available, which allows you to reload the page at the specified intervals.

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

Remove attribute "checked" of checkbox

You could try $(this):

$("#captureAudio").live("change", function() {
    if($(this).val() !== undefined) { /* IF THIS VALUE IS NOT UNDEFINED */
            navigator.device.capture.captureAudio(function(mediaFiles) {
            console.log("audio");
        }, function() {
            $(this).removeAttr('checked'); /* REMOVE checked ATTRIBUTE; */
            /* YOU CAN USE `$(this).prop("checked", false);` ALSO */
            _callback.error;
        }, {limit: 1});
    }
});

Can I do a max(count(*)) in SQL?

Thanks to the last answer

SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr HAVING COUNT(title) >= ALL
  (SELECT COUNT(title)
   FROM actor
   JOIN casting ON actor.id = casting.actorid
   JOIN movie ON casting.movieid = movie.id
   WHERE name = 'John Travolta'
   GROUP BY yr)

I had the same problem: I needed to know just the records which their count match the maximus count (it could be one or several records).

I have to learn more about "ALL clause", and this is exactly the kind of simple solution that I was looking for.

How to draw a checkmark / tick using CSS?

Also, using the awesome font, you can use the following tag. Simple and beautiful

With the possibility of changing the size and color and other features in CSS

See result here

How do I remove whitespace from the end of a string in Python?

You can use strip() or split() to control the spaces values as in the following:

words = "   first  second   "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# Remove the first and end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())


# Remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())


# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))

SQL query: Delete all records from the table except latest N?

Answering this after a long time...Came across the same situation and instead of using the answers mentioned, I came with below -

DELETE FROM table_name order by ID limit 10

This will delete the 1st 10 records and keep the latest records.

How to set an environment variable from a Gradle build?

For a test task, you can use the environment property like this:

test {
  environment "VAR", "val"
}

you can also use the environment property in an exec task

task dropDatabase(type: Exec) {
    environment "VAR", "val"
    commandLine "doit"
}

Note that with this method the environment variables are set only during the task.

Add regression line equation and R^2 on graph

Here's the most simplest code for everyone

Note: Showing Pearson's Rho and not R^2.

library(ggplot2)
library(ggpubr)

df <- data.frame(x = c(1:100)
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
        geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
        geom_point()+
        stat_cor(label.y = 35)+ #this means at 35th unit in the y axis, the r squared and p value will be shown
        stat_regline_equation(label.y = 30) #this means at 30th unit regresion line equation will be shown

p

One such example with my own dataset

Make docker use IPv4 for port binding

Setting net.ipv6.conf.all.forwarding=1 will fix the issue.

This can be done on a live system using sudo sysctl -w net.ipv6.conf.all.forwarding=1

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

Failed to install Python Cryptography package with PIP and setup.py

This worked for me (I'm using Ubuntu 14.04):

first install libffi-dev libssl-dev libpython2.7-dev:

sudo apt-get install libffi-dev libssl-dev libpython2.7-dev

then inside virtualenv:

pip install cryptography
pip install pyopenssl ndg-httpsclient pyasn1

Sources:

https://stackoverflow.com/a/32800685/5123544

https://stackoverflow.com/a/29202163/5123544

Permission denied (publickey) when SSH Access to Amazon EC2 instance

Another Possible Issue: Wrong login ID

Check 'Usage Instructions'

All good suggestions above, but what I ran into was that I selected a pre-made instance. After the instance has started , look at the usage instructions. I incorrectly used login id of the private key when in the instructions I was supposed to use 'bitnami' (e.g. bitnami@domain -i key.pem)

What is the best way to repeatedly execute a function every x seconds?

If you want a non-blocking way to execute your function periodically, instead of a blocking infinite loop I'd use a threaded timer. This way your code can keep running and perform other tasks and still have your function called every n seconds. I use this technique a lot for printing progress info on long, CPU/Disk/Network intensive tasks.

Here's the code I've posted in a similar question, with start() and stop() control:

from threading import Timer

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer     = None
        self.interval   = interval
        self.function   = function
        self.args       = args
        self.kwargs     = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

Usage:

from time import sleep

def hello(name):
    print "Hello %s!" % name

print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
    sleep(5) # your long-running job goes here...
finally:
    rt.stop() # better in a try/finally block to make sure the program ends!

Features:

  • Standard library only, no external dependencies
  • start() and stop() are safe to call multiple times even if the timer has already started/stopped
  • function to be called can have positional and named arguments
  • You can change interval anytime, it will be effective after next run. Same for args, kwargs and even function!

how to overwrite css style

You can add your styles in the required page after the external style sheet so they'll cascade and overwrite the first set of rules.

<link rel="stylesheet" href="allpages.css">
<style>
.flex-control-thumbs li {
  width: auto;
  float: none;
}
</style>

Maven: add a folder or jar file into current classpath

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

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

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

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

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

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

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

Read file (Read a file into a Maven property)

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

and finally

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