Programs & Examples On #Kdiff3

KDiff3 is a diff/merge program that compares or merges two or three text input files or directories and shows the differences line by line and character by character (!).

Git: How configure KDiff3 as merge tool and diff tool

(When trying to find out how to use kdiff3 from WSL git I ended up here and got the final pieces, so I'll post my solution for anyone else also stumbling in here while trying to find that answer)

How to use kdiff3 as diff/merge tool for WSL git

With Windows update 1903 it is a lot easier; just use wslpath and there is no need to share TMP from Windows to WSL since the Windows side now has access to the WSL filesystem via \wsl$:

[merge]
    renormalize = true
    guitool = kdiff3
[diff]
    tool = kdiff3
[difftool]
    prompt = false
[difftool "kdiff3"]
    # Unix style paths must be converted to windows path style
    cmd = kdiff3.exe \"`wslpath -w $LOCAL`\" \"`wslpath -w $REMOTE`\"
    trustExitCode = false
[mergetool]
    keepBackup = false
    prompt = false
[mergetool "kdiff3"]
    path = kdiff3.exe
    trustExitCode = false

Before Windows update 1903

Steps for using kdiff3 installed on Windows 10 as diff/merge tool for git in WSL:

  1. Add the kdiff3 installation directory to the Windows Path.
  2. Add TMP to the WSLENV Windows environment variable (WSLENV=TMP/up). The TMP dir will be used by git for temporary files, like previous revisions of files, so the path must be on the windows filesystem for this to work.
  3. Set TMPDIR to TMP in .bashrc:
# If TMP is passed via WSLENV then use it as TMPDIR
[[ ! -z "$WSLENV" && ! -z "$TMP" ]] && export TMPDIR=$TMP
  1. Convert unix-path to windows-path when calling kdiff3. Sample of my .gitconfig:
[merge]
    renormalize = true
    guitool = kdiff3
[diff]
    tool = kdiff3
[difftool]
    prompt = false
[difftool "kdiff3"]
    #path = kdiff3.exe
    # Unix style paths must be converted to windows path style by changing '/mnt/c/' or '/c/' to 'c:/'
    cmd = kdiff3.exe \"`echo $LOCAL | sed 's_^\\(/mnt\\)\\?/\\([a-z]\\)/_\\2:/_'`\" \"`echo $REMOTE | sed 's_^\\(/mnt\\)\\?/\\([a-z]\\)/_\\2:/_'`\"
    trustExitCode = false
[mergetool]
    keepBackup = false
    prompt = false
[mergetool "kdiff3"]
    path = kdiff3.exe
    trustExitCode = false

How do I convert between big-endian and little-endian values in C++?

Using the codes below, you can swap between BigEndian and LittleEndian easily

#define uint32_t unsigned 
#define uint16_t unsigned short

#define swap16(x) ((((uint16_t)(x) & 0x00ff)<<8)| \
(((uint16_t)(x) & 0xff00)>>8))

#define swap32(x) ((((uint32_t)(x) & 0x000000ff)<<24)| \
(((uint32_t)(x) & 0x0000ff00)<<8)| \
(((uint32_t)(x) & 0x00ff0000)>>8)| \
(((uint32_t)(x) & 0xff000000)>>24))

Git: Create a branch from unstaged/uncommitted changes on master

If you are using the GitHub Windows client (as I am) and you are in the situation of having made uncommitted changes that you wish to move to a new branch, you can simply "Crate a new branch" via the GitHub client. It will switch to the newly created branch and preserve your changes.

enter image description here

Subset data to contain only columns whose names match a condition

Just in case for data.table users, the following works for me:

df[, grep("ABC", names(df)), with = FALSE]

How to convert timestamp to datetime in MySQL?

You can use

select from_unixtime(1300464000,"%Y-%m-%d %h %i %s") from table;

For in details description about

  1. from_unixtime()
  2. unix_timestamp()

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

Simple way to sort strings in the (case sensitive) alphabetical order

I recently answered a similar question here. Applying the same approach to your problem would yield following solution:

list.sort(
  p2Ord(stringOrd, stringOrd).comap(new F<String, P2<String, String>>() {
    public P2<String, String> f(String s) {
      return p(s.toLowerCase(), s);
    }
  })
);

Selecting a Record With MAX Value

Here's an option if you have multiple records for each Customer and are looking for the latest balance for each (say they are dated records):

SELECT ID, BALANCE FROM (
    SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DateModified DESC) as RowNum, ID, BALANCE
    FROM CUSTOMERS
) C
WHERE RowNum = 1

Sublime Text 3, convert spaces to tabs

At the bottom of the Sublime window, you'll see something representing your tab/space setting.

You'll then get a dropdown with a bunch of options. The options you care about are:

  • Convert Indentation to Spaces
  • Convert Indentation to Tabs

Apply your desired setting to the entire document.

Hope this helps.

Netbeans how to set command line arguments in Java

import java.io.*;
class Main
{
public static void main(String args[]) throws IOException
{
    int n1,n2,n3,l;
    n1=Integer.parseInt(args[0]);
    n2=Integer.parseInt(args[1]);
    n3=Integer.parseInt(args[2]);
    
    if(n1>n2)
    {
        l=n1;
    }
    else
    {
        l=n2;
    }
    
    if(l<n3)
    {
        System.out.println("largest no is "+n3);
    }
    else
    {
        System.out.println("largest no is "+l);
    }
    
}}

Consider above program, in this program I want to pass 3 no's from Command Line, to do so.

Step 1 : Right Click on Cup and Saucer icon, u'll see this window

1

Step 2: Click on Properties

Step 3: Click Run _> Arguments _> type three no's eg. 32 98 16 then click OK. Plz add space between two arguments. See here

2

Step 4: Run the Program by using F6.

Slidedown and slideup layout with animation

Create two animation xml under res/anim folder

slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

<translate
    android:duration="1000"
    android:fromYDelta="0"
    android:toYDelta="100%" />
</set>

slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

<translate
    android:duration="1000"
    android:fromYDelta="100%"
    android:toYDelta="0" />
</set>

Load animation Like bellow Code and start animation when you want According to your Requirement

//Load animation 
Animation slide_down = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.slide_down);

Animation slide_up = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.slide_up);

// Start animation
linear_layout.startAnimation(slide_down); 

Using Spring 3 autowire in a standalone Java application

Spring is moving away from XML files and uses annotations heavily. The following example is a simple standalone Spring application which uses annotation instead of XML files.

package com.zetcode.bean;

import org.springframework.stereotype.Component;

@Component
public class Message {

   private String message = "Hello there!";

   public void setMessage(String message){

      this.message  = message;
   }

   public String getMessage(){

      return message;
   }
}

This is a simple bean. It is decorated with the @Component annotation for auto-detection by Spring container.

package com.zetcode.main;

import com.zetcode.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.zetcode")
public class Application {

    public static void main(String[] args) {

        ApplicationContext context
                = new AnnotationConfigApplicationContext(Application.class);

        Application p = context.getBean(Application.class);
        p.start();
    }

    @Autowired
    private Message message;
    private void start() {
        System.out.println("Message: " + message.getMessage());
    }
}

This is the main Application class. The @ComponentScan annotation searches for components. The @Autowired annotation injects the bean into the message variable. The AnnotationConfigApplicationContext is used to create the Spring application context.

My Standalone Spring tutorial shows how to create a standalone Spring application with both XML and annotations.

Option to ignore case with .contains method?

This probably isn't the best way for your particular problem, but you can use the String.matches(String regex) method or the matcher equivalent. We just need to construct a regular expression from your prospective title. Here it gets complex.

List<DVD> matchingDvds(String titleFragment) {
    String escapedFragment = Pattern.quote(titleFragment);
    // The pattern may have contained an asterisk, dollar sign, etc.
    // For example, M*A*S*H, directed by Robert Altman.
    Pattern pat = Pattern.compile(escapedFragment, Pattern.CASE_INSENSITIVE);
    List<DVD> foundDvds = new ArrayList<>();
    for (DVD dvd: catalog) {
        Matcher m = pat.matcher(dvd.getTitle());
        if (m.find()) {
            foundDvds.add(dvd);
        }
    }
    return foundDvds;
}

But this is inefficient, and it's being done purely in Java. You would do better to try one of these techniques:

  1. Learn the Collator and CollationKey classes.
  2. If you have no choice but to stay in the Java world, add a method to DVD, boolean matches(String fragment). Have the DVD tell you what it matches.
  3. Use a database. If it supports case-insensitive collations, declare the title column of the DVD table that way. Use JDBC or Hibernate or JPA or Spring Data, whichever you choose.
  4. If the database supports advanced text search, like Oracle, use that.
  5. Back in the Java world, use Apache Lucene and possibly Apache Solr.
  6. Use a language tuned for case-insensitive matches.

If you can wait until Java 8, use lambda expressions. You can avoid the Pattern and Matcher class that I used above by building the regex this way:

   String escapedFragment = Pattern.quote(titleFragment);
   String fragmentAnywhereInString = ".*" + escapedFragment + ".*";
   String caseInsensitiveFragment = "(?i)" + fragmentAnywhereInString;
   // and in the loop, use:
   if(dvd.getTitle().matches(caseInsensitiveFragment)) {
        foundDvds.add(dvd);
    }

But this compiles the pattern too many times. What about lower-casing everything?

if (dvd.getTitle().toLowerCase().contains(titleFragment.toLowerCase()))

Congratulations; you've just discovered the Turkish problem. Unless you state the locale in toLowerCase, Java finds the current locale. And the lower-casing is slow because it has to take into account the Turkish dotless i and dotted I. At least you have no patterns and no matchers.

How do I stretch a background image to cover the entire HTML element?

Not sure that stretching a background image is possible. If you find that it's not possible, or not reliable in all of your target browsers, you could try using a stretched img tag with z-index set lower, and position set to absolute so that other content appears on top of it.

Let us know what you end up doing.

Edit: What I suggested is basically what's in gabriel's link. So try that :)

How to obtain image size using standard Python class (without using external library)?

If you happen to have ImageMagick installed, then you can use 'identify'. For example, you can call it like this:

path = "//folder/image.jpg"
dim = subprocess.Popen(["identify","-format","\"%w,%h\"",path], stdout=subprocess.PIPE).communicate()[0]
(width, height) = [ int(x) for x in re.sub('[\t\r\n"]', '', dim).split(',') ]

ASP.NET MVC View Engine Comparison

I think this list should also include samples of each view engine so users can get a flavour of each without having to visit every website.

Pictures say a thousand words and markup samples are like screenshots for view engines :) So here's one from my favourite Spark View Engine

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
  <li each="var p in products">${p.Name}</li>
</ul>
<else>
  <p>No products available</p>
</else>

Where's my invalid character (ORA-00911)

If you use the string literal exactly as you have shown us, the problem is the ; character at the end. You may not include that in the query string in the JDBC calls.

As you are inserting only a single row, a regular INSERT should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):

String query1 = "select substr(to_char(max_data),1,4) as year, " + 
  "substr(to_char(max_data),5,6) as month, max_data " +
  "from dss_fin_user.acq_dashboard_src_load_success " + 
  "where source = 'CHQ PeopleSoft FS'";

String query2 = ".....";

String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();

reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();

pstmt.executeBatch();   
con.commit();

How to implement history.back() in angular.js

Another nice and reusable solution is to create a directive like this:

app.directive( 'backButton', function() {
    return {
        restrict: 'A',
        link: function( scope, element, attrs ) {
            element.on( 'click', function () {
                history.back();
                scope.$apply();
            } );
        }
    };
} );

then just use it like this:

<a href back-button>back</a>

What's the difference between django OneToOneField and ForeignKey?

The best and the most effective way to learn new things is to see and study real world practical examples. Suppose for a moment that you want to build a blog in django where reporters can write and publish news articles. The owner of the online newspaper wants to allow each of his reporters to publish as many articles as they want, but does not want different reporters to work on the same article. This means that when readers go and read an article they will se only one author in the article.

For example: Article by John, Article by Harry, Article by Rick. You can not have Article by Harry & Rick because the boss does not want two or more authors to work on the same article.

How can we solve this 'problem' with the help of django? The key to the solution of this problem is the django ForeignKey.

The following is the full code which can be used to implement the idea of our boss.

from django.db import models

# Create your models here.

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.first_name


class Article(models.Model):
    title = models.CharField(max_length=100)
    reporter = models.ForeignKey(Reporter)

    def __unicode__(self):
        return self.title

Run python manage.py syncdb to execute the sql code and build the tables for your app in your database. Then use python manage.py shell to open a python shell.

Create the Reporter object R1.

In [49]: from thepub.models import Reporter, Article

In [50]: R1 = Reporter(first_name='Rick')

In [51]: R1.save()

Create the Article object A1.

In [5]: A1 = Article.objects.create(title='TDD In Django', reporter=R1)

In [6]: A1.save()

Then use the following piece of code to get the name of the reporter.

In [8]: A1.reporter.first_name
Out[8]: 'Rick'

Now create the Reporter object R2 by running the following python code.

In [9]: R2 = Reporter.objects.create(first_name='Harry')

In [10]: R2.save()

Now try to add R2 to the Article object A1.

In [13]: A1.reporter.add(R2)

It does not work and you will get an AttributeError saying 'Reporter' object has no attribute 'add'.

As you can see an Article object can not be related to more than one Reporter object.

What about R1? Can we attach more than one Article objects to it?

In [14]: A2 = Article.objects.create(title='Python News', reporter=R1)

In [15]: R1.article_set.all()
Out[15]: [<Article: Python News>, <Article: TDD In Django>]

This practical example shows us that django ForeignKey is used to define many-to-one relationships.

OneToOneField is used to create one-to-one relationships.

We can use reporter = models.OneToOneField(Reporter) in the above models.py file but it is not going to be useful in our example as an author will not be able to post more than one article.

Each time you want to post a new article you will have to create a new Reporter object. This is time consuming, isn't it?

I highly recommend to try the example with the OneToOneField and realize the difference. I am pretty sure that after this example you will completly know the difference between django OneToOneField and django ForeignKey.

How to get the directory of the currently running file?

Use package osext

It's providing function ExecutableFolder() that returns an absolute path to folder where the currently running program executable reside (useful for cron jobs). It's cross platform.

Online documentation

package main

import (
    "github.com/kardianos/osext"
    "fmt"
    "log"
)

func main() {
    folderPath, err := osext.ExecutableFolder()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(folderPath)
}

Showing the stack trace from a running Python application

I am in the GDB camp with the python extensions. Follow https://wiki.python.org/moin/DebuggingWithGdb, which means

  1. dnf install gdb python-debuginfo or sudo apt-get install gdb python2.7-dbg
  2. gdb python <pid of running process>
  3. py-bt

Also consider info threads and thread apply all py-bt.

mysql count group by having

What about:

SELECT COUNT(*) FROM (SELECT ID FROM Movies GROUP BY ID HAVING COUNT(Genre)=4) a

Want to move a particular div to right

You can use float on that particular div, e.g.

<div style="float:right;">

Float the div you want more space to have to the left as well:

<div style="float:left;">

If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

<div style="position:absolute; left:-500px; top:30px;"> 

etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

pythonw.exe or python.exe?

If you don't want a terminal window to pop up when you run your program, use pythonw.exe;
Otherwise, use python.exe

Regarding the syntax error: print is now a function in 3.x
So use instead:

print("a")

Run all SQL files in a directory

  1. In the SQL Management Studio open a new query and type all files as below

    :r c:\Scripts\script1.sql
    :r c:\Scripts\script2.sql
    :r c:\Scripts\script3.sql
    
  2. Go to Query menu on SQL Management Studio and make sure SQLCMD Mode is enabled
  3. Click on SQLCMD Mode; files will be selected in grey as below

    :r c:\Scripts\script1.sql
    :r c:\Scripts\script2.sql
    :r c:\Scripts\script3.sql
    
  4. Now execute

iterating over and removing from a map

An alternative, more verbose way

List<SomeObject> toRemove = new ArrayList<SomeObject>();
for (SomeObject key: map.keySet()) {
    if (something) {
        toRemove.add(key);
    }
}

for (SomeObject key: toRemove) {
    map.remove(key);
}

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

python3x or higher

  1. load file in byte stream:
     body = ''
        for lines in open('website/index.html','rb'):
            decodedLine = lines.decode('utf-8')
            body = body+decodedLine.strip()
        return body
  1. use global setting:
    import io
    import sys
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

Parsing JSON giving "unexpected token o" error

Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.

var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details['ques_title']);

find first sequence item that matches a criterion

a=[100,200,300,400,500]
def search(b):
 try:
  k=a.index(b)
  return a[k] 
 except ValueError:
    return 'not found'
print(search(500))

it'll return the object if found else it'll return "not found"

How to execute raw SQL in Flask-SQLAlchemy app

This is a simplified answer of how to run SQL query from Flask Shell

First, map your module (if your module/app is manage.py in the principal folder and you are in a UNIX Operating system), run:

export FLASK_APP=manage

Run Flask shell

flask shell

Import what we need::

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
from sqlalchemy import text

Run your query:

result = db.engine.execute(text("<sql here>").execution_options(autocommit=True))

This use the currently database connection which has the application.

Laravel: Get base url

Laravel < 5.2

echo url();

Laravel >= 5.2

echo url('/');

Hope this helps you

Why em instead of px?

You probably want to use em for font sizes until IE6 is gone (from your site). Px will be alright when page zooming (as opposed to text zooming) becomes the standard behaviour.

Traingamer already provided the neccessary links.

Creating a search form in PHP to search a database?

You're getting errors 'table liam does not exist' because the table's name is Liam which is not the same as liam. MySQL table names are case sensitive.

val() doesn't trigger change() in jQuery

From https://api.jquery.com/change/:

The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

How to list all the roles existing in Oracle database?

all_roles.sql

SELECT SUBSTR(TRIM(rtp.role),1,12)          AS ROLE
     , SUBSTR(rp.grantee,1,16)              AS GRANTEE
     , SUBSTR(TRIM(rtp.privilege),1,12)     AS PRIVILEGE
     , SUBSTR(TRIM(rtp.owner),1,12)         AS OWNER
     , SUBSTR(TRIM(rtp.table_name),1,28)    AS TABLE_NAME
     , SUBSTR(TRIM(rtp.column_name),1,20)   AS COLUMN_NAME
     , SUBSTR(rtp.common,1,4)               AS COMMON
     , SUBSTR(rtp.grantable,1,4)            AS GRANTABLE
     , SUBSTR(rp.default_role,1,16)         AS DEFAULT_ROLE
     , SUBSTR(rp.admin_option,1,4)          AS ADMIN_OPTION
  FROM role_tab_privs rtp
  LEFT JOIN dba_role_privs rp
    ON (rtp.role = rp.granted_role)
 WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
   AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
   AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
   AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
 ORDER BY 1
        , 2
        , 3
        , 4
;

Usage

SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.

What does "request for member '*******' in something not a structure or union" mean?

It may also happen in the following case:

eg. if we consider the push function of a stack:

typedef struct stack
{
    int a[20];
    int head;
}stack;

void push(stack **s)
{
    int data;
    printf("Enter data:");
    scanf("%d",&(*s->a[++*s->head])); /* this is where the error is*/
}

main()
{
    stack *s;
    s=(stack *)calloc(1,sizeof(stack));
    s->head=-1;
    push(&s);
    return 0;
}

The error is in the push function and in the commented line. The pointer s has to be included within the parentheses. The correct code:

scanf("%d",&( (*s)->a[++(*s)->head]));

Get current time as formatted string in Go?

All the other response are very miss-leading for somebody coming from google and looking for "timestamp in go"! YYYYMMDDhhmmss is not a "timestamp".

To get the "timestamp" of a date in go (number of seconds from january 1970), the correct function is .Unix(), and it really return an integer

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

This is an addition to the answer by Abdull somewhere in this thread:

I had to modify instead of adding a port

semanage port -m -t http_port_t -p tcp 5000

because I get this error on adding the port

ValueError: Port tcp/5000 already defined

How to remove button shadow (android)

try : android:stateListAnimator="@null"

How to check for a valid Base64 encoded string

Knibb High football rules!

This should be relatively fast and accurate but I admit I didn't put it through a thorough test, just a few.

It avoids expensive exceptions, regex, and also avoids looping through a character set, instead using ascii ranges for validation.

public static bool IsBase64String(string s)
    {
        s = s.Trim();
        int mod4 = s.Length % 4;
        if(mod4!=0){
            return false;
        }
        int i=0;
        bool checkPadding = false;
        int paddingCount = 1;//only applies when the first is encountered.
        for(i=0;i<s.Length;i++){
            char c = s[i];
            if (checkPadding)
            {
                if (c != '=')
                {
                    return false;
                }
                paddingCount++;
                if (paddingCount > 3)
                {
                    return false;
                }
                continue;
            }
            if(c>='A' && c<='z' || c>='0' && c<='9'){
                continue;
            }
            switch(c){ 
              case '+':
              case '/':
                 continue;
              case '=': 
                 checkPadding = true;
                 continue;
            }
            return false;
        }
        //if here
        //, length was correct
        //, there were no invalid characters
        //, padding was correct
        return true;
    }

Simple http post example in Objective-C?

Here i'm adding sample code for http post print response and parsing as JSON if possible, it will handle everything async so your GUI will be refreshing just fine and will not freeze at all - which is important to notice.

//POST DATA
NSString *theBody = [NSString stringWithFormat:@"parameter=%@",YOUR_VAR_HERE];
NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//URL CONFIG
NSString *serverURL = @"https://your-website-here.com";
NSString *downloadUrl = [NSString stringWithFormat:@"%@/your-friendly-url-here/json",serverURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
//POST DATA SETUP
[request setHTTPMethod:@"POST"];
[request setHTTPBody:bodyData];
//DEBUG MESSAGE
NSLog(@"Trying to call ws %@",downloadUrl);
//EXEC CALL
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        NSLog(@"Download Error:%@",error.description);
    }
    if (data) {

        //
        // THIS CODE IS FOR PRINTING THE RESPONSE
        //
        NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
        NSLog(@"Response:%@",returnString);

        //PARSE JSON RESPONSE
        NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
                                                                      options:0
                                                                        error:NULL];

        if ( json_response ) {
            if ( [json_response isKindOfClass:[NSDictionary class]] ) {
                // do dictionary things
                for ( NSString *key in [json_response allKeys] ) {
                    NSLog(@"%@: %@", key, json_response[key]);
                }
            }
            else if ( [json_response isKindOfClass:[NSArray class]] ) {
                NSLog(@"%@",json_response);
            }
        }
        else {
            NSLog(@"Error serializing JSON: %@", error);
            NSLog(@"RAW RESPONSE: %@",data);
            NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
            NSLog(@"Response:%@",returnString2);
        }
    }
}];

Hope this helps!

How can I make a JPA OneToOne relation lazy

As already perfectly explained by ChssPly76, Hibernate's proxies don't help with unconstrained (nullable) one-to-one associations, BUT there is a trick explained here to avoid to set up instrumentation. The idea is to fool Hibernate that the entity class which we want to use has been already instrumented: you instrument it manually in the source code. It's easy! I've implemented it with CGLib as bytecode provider and it works (ensure that you configure lazy="no-proxy" and fetch="select", not "join", in your HBM).

I think this is a good alternative to real (I mean automatic) instrumentation when you have just one one-to-one nullable relation that you want to make lazy. The main drawback is that the solution depends on the bytecode provider you are using, so comment your class accurately because you could have to change the bytecode provider in the future; of course, you are also modifying your model bean for a technical reason and this is not fine.

How do I completely rename an Xcode project (i.e. inclusive of folders)?

A quicker solution using shell commands (works with CocoaPods too):

PLEASE cd TO A NON-GIT REPOSITORY BEFORE PROCEEDING ??

Step 1 - Prerequisites

  1. Copy your original project folder to a temporary /NewProjectFolder OUTSIDE your git repository. ?? changes to .git could corrupt your git index ?

Step 2 - Open Terminal

Now we're going to rename the project from oldName to NewProject.

  • Close XCode.
  • Go to your /NewProjectFolder.
cd /Path/to/your/NewProjectFolder
  • Install the extra tools needed.
brew install rename ack
  • Rename the files and directories containing the source string. You’ll need to RUN THIS COMMAND TWICE, because directories will be renamed first, then files and directories inside those will be renamed on the next iteration.
find . -name 'oldName*' -print0 | xargs -0 rename --subst-all 'oldName' 'NewProject'
  • Check if all the files containing the source string are renamed. You should see empty output.
find . -name 'oldName*'
  • Replace all occurrences of the string in all files.
ack --literal --files-with-matches 'oldName' --print0 | xargs -0 sed -i '' 's/oldName/NewProject/g'
  • Check if all occurrences of the string in all files were replaced. You should see empty output.
ack --literal 'oldName'
  • Run pod install
  • Add NewProjectFolder to your repository.
  • You are done!

How to enable authentication on MongoDB through Docker?

The Dockerfile for the official mongo image is here. The default command is mongod but you can override to add the --auth switch assuming user's are already configured.

docker run -d .... mongodb:latest mongod --auth

If the user has to be created then you need to volume mount a startup script into /entrypoint.sh to replace the default startup script and then have that script create users and start mongo with the auth switch.

docker run -d .... -v $PWD/my_custom_script.sh:/entrypoint.sh mongodb:latest

Google Chrome "window.open" workaround?

The other answers are outdated. The behavior of Chrome for window.open depends on where it is called from. See also this topic.

When window.open is called from a handler that was triggered though a user action (e.g. onclick event), it will behave similar as <a target="_blank">, which by default opens in a new tab. However if window.open is called elsewhere, Chrome ignores other arguments and always opens a new window with a non-editable address bar.

This looks like some kind of security measure, although the rationale behind it is not completely clear.

Using Python 3 in virtualenv

For those of you who are using pipenv and want to install specific version:

pipenv install --python 3.6

How to change max_allowed_packet size

Change in the my.ini or ~/.my.cnf file by including the single line under [mysqld] or [client] section in your file:

max_allowed_packet=500M

then restart the MySQL service and you are done.

See the documentation for further information.

How to style child components from parent component's CSS file?

Actually there is one more option. Which is rather safe. You can use ViewEncapsulation.None BUT put all your component styles into its tag (aka selector). But anyway always prefer some global style plus encapsulated styles.

Here is modified Denis Rybalka example:

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'parent',
  styles: [`
    parent {
      .first {
        color:blue;
      }
      .second {
        color:red;
      }
    }
 `],
 template: `
    <div>
      <child class="first">First</child>
      <child class="second">Second</child>
    </div>`,
  encapsulation: ViewEncapsulation.None,
})
export class ParentComponent  {
  constructor() { }
}

Remove all the children DOM elements in div

In Dojo 1.7 or newer, use domConstruct.empty(String|DomNode):

require(["dojo/dom-construct"], function(domConstruct){
  // Empty node's children byId:
  domConstruct.empty("someId");
});

In older Dojo, use dojo.empty(String|DomNode) (deprecated at Dojo 1.8):

dojo.empty( id or DOM node );

Each of these empty methods safely removes all children of the node.

Format ints into string of hex

Python 2:

>>> str(bytearray([0,1,2,3,127,200,255])).encode('hex')
'000102037fc8ff'

Python 3:

>>> bytearray([0,1,2,3,127,200,255]).hex()
'000102037fc8ff'

jQuery: Check if special characters exists in string

You could also use the whitelist method -

var str = $('#Search').val();
var regex = /[^\w\s]/gi;

if(regex.test(str) == true) {
    alert('Your search string contains illegal characters.');
}

The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

How to check for registry value using VbScript

This should work for you:

Dim oShell
Dim iValue

Set oShell = CreateObject("WScript.Shell")

iValue = oShell.RegRead("HKLM\SOFTWARE\SOMETHINGSOMETHING")

Cursor adapter and sqlite example

In Android, How to use a Cursor with a raw query in sqlite:

Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
           "where Age > 10 LIMIT 5", null);

if (c != null ) {
    if  (c.moveToFirst()) {
        do {
            String firstName = c.getString(c.getColumnIndex("FirstName"));
            int age = c.getInt(c.getColumnIndex("Age"));
            results.add("" + firstName + ",Age: " + age);
        }while (c.moveToNext());
    }
}
c.close();

Java Set retain order?

Set is just an interface. In order to retain order, you have to use a specific implementation of that interface and the sub-interface SortedSet, for example TreeSet or LinkedHashSet. You can wrap your Set this way:

Set myOrderedSet = new LinkedHashSet(mySet);

How can I write a byte array to a file in Java?

No need for external libs to bloat things - especially when working with Android. Here is a native solution that does the trick. This is a pice of code from an app that stores a byte array as an image file.

    // Byte array with image data.
    final byte[] imageData = params[0];

    // Write bytes to tmp file.
    final File tmpImageFile = new File(ApplicationContext.getInstance().getCacheDir(), "scan.jpg");
    FileOutputStream tmpOutputStream = null;
    try {
        tmpOutputStream = new FileOutputStream(tmpImageFile);
        tmpOutputStream.write(imageData);
        Log.d(TAG, "File successfully written to tmp file");
    }
    catch (FileNotFoundException e) {
        Log.e(TAG, "FileNotFoundException: " + e);
        return null;
    }
    catch (IOException e) {
        Log.e(TAG, "IOException: " + e);
        return null;
    }
    finally {
        if(tmpOutputStream != null)
            try {
                tmpOutputStream.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e);
            }
    }

How to clear the cache in NetBeans

Just install cache eraser plugin, it is compatible with nb6.9, 7.0,7.1,7.2 and 7.3: To configure the plugin you have to provide the cache dir which is in netbean's about screen. Then with Tools->erase cache, you clear the netbeans cache. That is all, good luck.

http://plugins.netbeans.org/plugin/40014/cache-eraser

Differences between unique_ptr and shared_ptr

unique_ptr
is a smart pointer which owns an object exclusively.

shared_ptr
is a smart pointer for shared ownership. It is both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

Since API 17, the View class has a static method generateViewId() that will

generate a value suitable for use in setId(int)

Confirm button before running deleting routine from website

Try this one :

 <script type="text/javascript">
      var baseUrl='http://example.com';
      function ConfirmDelete()
      {
            if (confirm("Delete Account?"))
                 location.href=baseUrl+'/deleteRecord.php';
      }
  </script>


  echo '<a type="button" onclick="ConfirmDelete()">DELETE ACCOUNT</a>';

How to overlay one div over another div

This is what you need:

_x000D_
_x000D_
function showFrontLayer() {_x000D_
  document.getElementById('bg_mask').style.visibility='visible';_x000D_
  document.getElementById('frontlayer').style.visibility='visible';_x000D_
}_x000D_
function hideFrontLayer() {_x000D_
  document.getElementById('bg_mask').style.visibility='hidden';_x000D_
  document.getElementById('frontlayer').style.visibility='hidden';_x000D_
}
_x000D_
#bg_mask {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;  bottom: 0;_x000D_
  left: 0;_x000D_
  margin: auto;_x000D_
  margin-top: 0px;_x000D_
  width: 981px;_x000D_
  height: 610px;_x000D_
  background : url("img_dot_white.jpg") center;_x000D_
  z-index: 0;_x000D_
  visibility: hidden;_x000D_
} _x000D_
_x000D_
#frontlayer {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  margin: 70px 140px 175px 140px;_x000D_
  padding : 30px;_x000D_
  width: 700px;_x000D_
  height: 400px;_x000D_
  background-color: orange;_x000D_
  visibility: hidden;_x000D_
  border: 1px solid black;_x000D_
  z-index: 1;_x000D_
} _x000D_
_x000D_
_x000D_
</style>
_x000D_
<html>_x000D_
  <head>_x000D_
    <META HTTP-EQUIV="EXPIRES" CONTENT="-1" />_x000D_
_x000D_
  </head>_x000D_
  <body>_x000D_
    <form action="test.html">_x000D_
      <div id="baselayer">_x000D_
_x000D_
        <input type="text" value="testing text"/>_x000D_
        <input type="button" value="Show front layer" onclick="showFrontLayer();"/> Click 'Show front layer' button<br/><br/><br/>_x000D_
_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing textsting text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        <div id="bg_mask">_x000D_
          <div id="frontlayer"><br/><br/>_x000D_
            Now try to click on "Show front layer" button or the text box. It is not active.<br/><br/><br/>_x000D_
            Use position: absolute to get the one div on top of another div.<br/><br/><br/>_x000D_
            The bg_mask div is between baselayer and front layer.<br/><br/><br/>_x000D_
            In bg_mask, img_dot_white.jpg(1 pixel in width and height) is used as background image to avoid IE browser transparency issue;<br/><br/><br/>_x000D_
            <input type="button" value="Hide front layer" onclick="hideFrontLayer();"/>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </form>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I calculate the time between 2 Dates in typescript

Use the getTime method to get the time in total milliseconds since 1970-01-01, and subtract those:

var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();

Hive: how to show all partitions of a table?

hive> show partitions table_name;

fatal: early EOF fatal: index-pack failed

I had the same problem, I even tried to download the project directly from the website as a zip file but the download got interrupted at the exact same percent.

This single line fixed my problem like a charm

git config --global core.compression 0

I know other answers have mentioned this but, no one here mentioned that this line alone can fix the problem.

Hope it helps.

Delete a row from a table by id

How about:

function deleteRow(rowid)  
{   
    var row = document.getElementById(rowid);
    row.parentNode.removeChild(row);
}

And, if that fails, this should really work:

function deleteRow(rowid)  
{   
    var row = document.getElementById(rowid);
    var table = row.parentNode;
    while ( table && table.tagName != 'TABLE' )
        table = table.parentNode;
    if ( !table )
        return;
    table.deleteRow(row.rowIndex);
}

How to capitalize the first character of each word in a string

Try this very simple way

example givenString="ram is good boy"

public static String toTitleCase(String givenString) {
    String[] arr = givenString.split(" ");
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < arr.length; i++) {
        sb.append(Character.toUpperCase(arr[i].charAt(0)))
            .append(arr[i].substring(1)).append(" ");
    }          
    return sb.toString().trim();
}  

Output will be: Ram Is Good Boy

Working with $scope.$emit and $scope.$on

According to the angularjs event docs the receiving end should be containing arguments with a structure like

@params

-- {Object} event being the event object containing info on the event

-- {Object} args that are passed by the callee (Note that this can only be one so better to send in a dictionary object always)

$scope.$on('fooEvent', function (event, args) { console.log(args) }); From your code

Also if you are trying to get a shared piece of information to be available accross different controllers there is an another way to achieve that and that is angular services.Since the services are singletons information can be stored and fetched across controllers.Simply create getter and setter functions in that service, expose these functions, make global variables in the service and use them to store the info

How can I check the extension of a file?

file='test.xlsx'
if file.endswith('.csv'):
    print('file is CSV')
elif file.endswith('.xlsx'):
    print('file is excel')
else:
    print('none of them')

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.

Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.

However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.

How can I perform a reverse string search in Excel without using VBA?

A more robust version of Jerry's answer:

=TRIM(RIGHT(SUBSTITUTE(TRIM(A1), " ", REPT(" ", LEN(TRIM(A1)))), LEN(TRIM(A1))))

That works regardless of the length of the string, leading or trailing spaces, or whatever else and it's still pretty short and simple.

Angular 2 Sibling Component Communication

This is not what you exactly want but for sure will help you out

I'm surprised there's not more information out there about component communication <=> consider this tutorial by angualr2

For sibling components communication, I'd suggest to go with sharedService. There are also other options available though.

import {Component,bind} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {NameService} from 'src/nameService';


import {TheContent} from 'src/content';
import {Navbar} from 'src/nav';


@Component({
  selector: 'app',
  directives: [TheContent,Navbar],
  providers: [NameService],
  template: '<navbar></navbar><thecontent></thecontent>'
})


export class App {
  constructor() {
    console.log('App started');
  }
}

bootstrap(App,[]);

Please refer to link at top for more code.

Edit: This is a very small demo. You have already mention that you have already tried with sharedService. So please consider this tutorial by angualr2 for more information.

How to find encoding of a file via script on Linux?

here is an example script using file -I and iconv which works on MacOsX For your question you need to use mv instead of iconv

#!/bin/bash
# 2016-02-08
# check encoding and convert files
for f in *.java
do
  encoding=`file -I $f | cut -f 2 -d";" | cut -f 2 -d=`
  case $encoding in
    iso-8859-1)
    iconv -f iso8859-1 -t utf-8 $f > $f.utf8
    mv $f.utf8 $f
    ;;
  esac
done

Why is "using namespace std;" considered bad practice?

I agree with everything Greg wrote, but I'd like to add: It can even get worse than Greg said!

Library Foo 2.0 could introduce a function, Quux(), that is an unambiguously better match for some of your calls to Quux() than the bar::Quux() your code called for years. Then your code still compiles, but it silently calls the wrong function and does god-knows-what. That's about as bad as things can get.

Keep in mind that the std namespace has tons of identifiers, many of which are very common ones (think list, sort, string, iterator, etc.) which are very likely to appear in other code, too.

If you consider this unlikely: There was a question asked here on Stack Overflow where pretty much exactly this happened (wrong function called due to omitted std:: prefix) about half a year after I gave this answer. Here is another, more recent example of such a question. So this is a real problem.


Here's one more data point: Many, many years ago, I also used to find it annoying having to prefix everything from the standard library with std::. Then I worked in a project where it was decided at the start that both using directives and declarations are banned except for function scopes. Guess what? It took most of us very few weeks to get used to writing the prefix, and after a few more weeks most of us even agreed that it actually made the code more readable. There's a reason for that: Whether you like shorter or longer prose is subjective, but the prefixes objectively add clarity to the code. Not only the compiler, but you, too, find it easier to see which identifier is referred to.

In a decade, that project grew to have several million lines of code. Since these discussions come up again and again, I once was curious how often the (allowed) function-scope using actually was used in the project. I grep'd the sources for it and only found one or two dozen places where it was used. To me this indicates that, once tried, developers don't find std:: painful enough to employ using directives even once every 100 kLoC even where it was allowed to be used.


Bottom line: Explicitly prefixing everything doesn't do any harm, takes very little getting used to, and has objective advantages. In particular, it makes the code easier to interpret by the compiler and by human readers — and that should probably be the main goal when writing code.

How to remove numbers from a string?

This can be done without regex which is more efficient:

var questionText = "1 ding ?"
var index = 0;
var num = "";
do
{
    num += questionText[index];
} while (questionText[++index] >= "0" && questionText[index] <= "9");
questionText = questionText.substring(num.length);

And as a bonus, it also stores the number, which may be useful to some people.

Serialize object to query string in JavaScript/jQuery

You want $.param(): http://api.jquery.com/jQuery.param/

Specifically, you want this:

var data = { one: 'first', two: 'second' };
var result = $.param(data);

When given something like this:

{a: 1, b : 23, c : "te!@#st"}

$.param will return this:

a=1&b=23&c=te!%40%23st

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

We ran into this problem and tracked it down to the Geocoding.net NuGet package that we were using to help with our Google Maps views (Geocoding.net version 3.1.0 published 2/4/2014).

The Geocoding dll appears to be .Net 4.0 when you examine the package file or view it using Jet Brains’ Dot Peek application; however, a colleague of mine says that it was compiled using ilmerge so it is most likely related to the ilmerge problems listed above.

It was a long process to track it down. We fetched different changesets from TFS till we narrowed it down to the changeset that added the aforementioned NuGet package. After removing it, we were able to deploy to our .NET 4 server.

How to show live preview in a small popup of linked page on mouse over on link?

I have done a little plugin to show a iframe window to preview a link. Still in beta version. Maybe it fits your case: https://github.com/Fischer-L/previewbox.

Loop over html table and get checked checkboxes (JQuery)

Use this instead:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked') //...
});

Let me explain you what the selector does: input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox After that: :checked will match all checked checkboxes.

You can loop over these checkboxes with:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked').each(function () {
       //this is the current checkbox
    });
});

Here is demo in JSFiddle.


And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.

$('#save').click(function () {
    $('#mytable').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked') &&
            row.find('textarea').val().length <= 0) {
            alert('You must fill the text area!');
        }
    });
});

Fragment Inside Fragment

AFAIK, fragments cannot hold other fragments.


UPDATE

With current versions of the Android Support package -- or native fragments on API Level 17 and higher -- you can nest fragments, by means of getChildFragmentManager(). Note that this means that you need to use the Android Support package version of fragments on API Levels 11-16, because even though there is a native version of fragments on those devices, that version does not have getChildFragmentManager().

What svn command would list all the files modified on a branch?

This will list only modified files:

svn status -u | grep M

How to extract numbers from a string and get an array of ints?

What about to use replaceAll java.lang.String method:

    String str = "qwerty-1qwerty-2 455 f0gfg 4";      
    str = str.replaceAll("[^-?0-9]+", " "); 
    System.out.println(Arrays.asList(str.trim().split(" ")));

Output:

[-1, -2, 455, 0, 4]

Description

[^-?0-9]+
  • [ and ] delimites a set of characters to be single matched, i.e., only one time in any order
  • ^ Special identifier used in the beginning of the set, used to indicate to match all characters not present in the delimited set, instead of all characters present in the set.
  • + Between one and unlimited times, as many times as possible, giving back as needed
  • -? One of the characters “-” and “?”
  • 0-9 A character in the range between “0” and “9”

Detect click outside React component

I found this from the article below:

render() { return ( { this.node = node; }} > Toggle Popover {this.state.popupVisible && ( I'm a popover! )} ); } }

Here is a great article about this issue: "Handle clicks outside of React components" https://larsgraubner.com/handle-outside-clicks-react/

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

I'm quite a beginner in Python and I found the answer of Anand was very good but quite complicated to me, so I try to reformulate :

1) insert and append methods are not specific to sys.path and as in other languages they add an item into a list or array and :
* append(item) add item to the end of the list,
* insert(n, item) inserts the item at the nth position in the list (0 at the beginning, 1 after the first element, etc ...).

2) As Anand said, python search the import files in each directory of the path in the order of the path, so :
* If you have no file name collisions, the order of the path has no impact,
* If you look after a function already defined in the path and you use append to add your path, you will not get your function but the predefined one.

But I think that it is better to use append and not insert to not overload the standard behaviour of Python, and use non-ambiguous names for your files and methods.

What is the difference between up-casting and down-casting with respect to class variable

Upcasting is casting to a supertype, while downcasting is casting to a subtype. Upcasting is always allowed, but downcasting involves a type check and can throw a ClassCastException.

In your case, a cast from a Dog to an Animal is an upcast, because a Dog is-a Animal. In general, you can upcast whenever there is an is-a relationship between two classes.

Downcasting would be something like this:

Animal animal = new Dog();
Dog castedDog = (Dog) animal;

Basically what you're doing is telling the compiler that you know what the runtime type of the object really is. The compiler will allow the conversion, but will still insert a runtime sanity check to make sure that the conversion makes sense. In this case, the cast is possible because at runtime animal is actually a Dog even though the static type of animal is Animal.

However, if you were to do this:

Animal animal = new Animal();
Dog notADog = (Dog) animal;

You'd get a ClassCastException. The reason why is because animal's runtime type is Animal, and so when you tell the runtime to perform the cast it sees that animal isn't really a Dog and so throws a ClassCastException.

To call a superclass's method you can do super.method() or by performing the upcast.

To call a subclass's method you have to do a downcast. As shown above, you normally risk a ClassCastException by doing this; however, you can use the instanceof operator to check the runtime type of the object before performing the cast, which allows you to prevent ClassCastExceptions:

Animal animal = getAnimal(); // Maybe a Dog? Maybe a Cat? Maybe an Animal?
if (animal instanceof Dog) {
    // Guaranteed to succeed, barring classloader shenanigans
    Dog castedDog = (Dog) animal;
}

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Effect of NOLOCK hint in SELECT statements

NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.

NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.

Here is information about all of the isolation levels at your disposal, as well as table hints.

SET TRANSACTION ISOLATION LEVEL

Table Hint (Transact-SQL)

Change directory in PowerShell

To go directly to that folder, you can use the Set-Location cmdlet or cd alias:

Set-Location "Q:\My Test Folder"

How to launch an application from a browser?

I achieved the same thing using a local web server and PHP. I used a script containing shell_exec to launch an application locally.

Alternatively, you could do something like this:

<a href="file://C:/Windows/notepad.exe">Notepad</a>

HTML display result in text (input) field?

innerHTML sets the text (including html elements) inside an element. Normally we use it for elements like div, span etc to insert other html elements inside it.

For your case you want to set the value of an input element. So you should use the value attribute.

Change innerHTML to value

document.getElementById('add').value = sum;

How can I open a Shell inside a Vim Window?

You can use tmux or screen (second is able to do only horizontal splits without a patch) to split your terminal. But I do not know the way to have one instance of Vim in both panes.

How to select date without time in SQL

I guess he wants a string.

select convert(varchar(10), '2011-02-25 21:17:33.933', 120)

120 here tells the convert function that we pass the input date in the following format: yyyy-mm-dd hh:mi:ss.

Is it possible to include one CSS file in another?

@import url('style.css');

As opposed to the best answer, it is not recommended to aggregate all CSS files into one chunk when using HTTP/2.0

Android Studio drawable folders

Its little tricky in android studio there is no default folder for all screen size you need to create but with little trick.

  • when you paste your image into drawable folder a popup will appear to ask about directory
  • Add subfolder name after drawable like drawable-xxhdpi
  • I will suggest you to paste image with highest resolution it will auto detect for other size.. thats it next time when you will paste it will ask to you about directory

i cant post image here so if still having any problem. here is tutorial..

Drawable folder in android studio

Using VBA to get extended file attributes

I was finally able to get this to work for my needs.

The old voted up code does not run on windows 10 system (at least not mine). The referenced MS library link below provides current examples on how to make this work. My example uses them with late bindings.

https://docs.microsoft.com/en-us/windows/win32/shell/folder-getdetailsof.

The attribute codes were different on my computer and like someone mentioned above most return blank values even if they are not. I used a for loop to cycle through all of them and found out that Title and Subject can still be accessed which is more then enough for my purposes.

Private Sub MySubNamek()
Dim objShell  As Object 'Shell
Dim objFolder As Object 'Folder

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace("E:\MyFolder")

If (Not objFolder Is Nothing) Then
Dim objFolderItem As Object 'FolderItem
Set objFolderItem = objFolder.ParseName("Myfilename.txt")
        For i = 0 To 288
           szItem = objFolder.GetDetailsOf(objFolderItem, i)
           Debug.Print i & " - " & szItem
       Next
Set objFolderItem = Nothing
End If

Set objFolder = Nothing
Set objShell = Nothing
End Sub

Unit Testing C Code

I used RCUNIT to do some unit testing for embedded code on PC before testing on the target. Good hardware interface abstraction is important else endianness and memory mapped registers are going to kill you.

How to add a margin to a table row <tr>

add this style before the class="highlighted" padding-bottom and display is inline-table

Getting Access Denied when calling the PutObject operation with bucket-level permission

In case this help out anyone else, in my case, I was using a CMK (it worked fine using the default aws/s3 key)

I had to go into my encryption key definition in IAM and add the programmatic user logged into boto3 to the list of users that "can use this key to encrypt and decrypt data from within applications and when using AWS services integrated with KMS.".

Go: panic: runtime error: invalid memory address or nil pointer dereference

Make sure that you handle all the errors by sending a return value.

`if err!=nil{
    return nil, err
 }`

How to check if a file exists in Documents folder?

Swift 2.0

This is how to check if the file exists using Swift

func isFileExistsInDirectory() -> Bool {
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDirectory: AnyObject = paths[0]
    let dataPath = documentsDirectory.stringByAppendingPathComponent("/YourFileName")

    return NSFileManager.defaultManager().fileExistsAtPath(dataPath)
}

MySQL: how to get the difference between two timestamps in seconds

UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)

If you want an unsigned difference, add an ABS() around the expression.

Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

Expand a random range from 1–5 to 1–7

Why not do it simple?

int random7() {
  return random5() + (random5() % 3);
}

The chances of getting 1 and 7 in this solution is lower due to the modulo, however, if you just want a quick and readable solution, this is the way to go.

How do I use the conditional operator (? :) in Ruby?

It is the ternary operator, and it works like in C (the parenthesis are not required). It's an expression that works like:

if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this

However, in Ruby, if is also an expression so: if a then b else c end === a ? b : c, except for precedence issues. Both are expressions.

Examples:

puts (if 1 then 2 else 3 end) # => 2

puts 1 ? 2 : 3                # => 2

x = if 1 then 2 else 3 end
puts x                        # => 2

Note that in the first case parenthesis are required (otherwise Ruby is confused because it thinks it is puts if 1 with some extra junk after it), but they are not required in the last case as said issue does not arise.

You can use the "long-if" form for readability on multiple lines:

question = if question.size > 20 then
  question.slice(0, 20) + "..."
else 
  question
end

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

Excel VBA, How to select rows based on data in a column?

Yes using Option Explicit is a good habit. Using .Select however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet which might not be what you actually wanted.

Is this what you are trying?

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            Else
                Exit For
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

NOTE

If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10

If you want to copy all rows which have data then use this code.

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

Hope this is what you wanted?

Sid

How to view the assembly behind the code using Visual C++?

For MSVC you can use the linker.

link.exe /dump /linenumbers /disasm /out:foo.dis foo.dll

foo.pdb needs to be available to get symbols

Check if a class `active` exist on element with jquery

I think you want to use hasClass()

$('li.menu').hasClass('active');

How to generate all permutations of a list?

list2Perm = [1, 2.0, 'three']
listPerm = [[a, b, c]
            for a in list2Perm
            for b in list2Perm
            for c in list2Perm
            if ( a != b and b != c and a != c )
            ]
print listPerm

Output:

[
    [1, 2.0, 'three'], 
    [1, 'three', 2.0], 
    [2.0, 1, 'three'], 
    [2.0, 'three', 1], 
    ['three', 1, 2.0], 
    ['three', 2.0, 1]
]

Using Java to find substring of a bigger string using Regular Expression

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public static String get_match(String s, String p) {
    // returns first match of p in s for first group in regular expression 
    Matcher m = Pattern.compile(p).matcher(s);
    return m.find() ? m.group(1) : "";
}

get_match("FOO[BAR]", "\\[(.*?)\\]")  // returns "BAR"

public static List<String> get_matches(String s, String p) {
    // returns all matches of p in s for first group in regular expression 
    List<String> matches = new ArrayList<String>();
    Matcher m = Pattern.compile(p).matcher(s);
    while(m.find()) {
        matches.add(m.group(1));
    }
    return matches;
}

get_matches("FOO[BAR] FOO[CAT]", "\\[(.*?)\\]")) // returns [BAR, CAT]

C++ int to byte array

return ((byte[0]<<24)|(byte[1]<<16)|(byte[2]<<8)|(byte[3]));

:D

What does an exclamation mark before a cell reference mean?

If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.

As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).

edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p

How to read file binary in C#?

Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:

using System;
using System.IO;
using System.Text;

class Program {
    static void Main(string[] args) {
        // Read the file into <bits>
        var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
        var len = (int)fs.Length;
        var bits = new byte[len];
        fs.Read(bits, 0, len);
        // Dump 16 bytes per line
        for (int ix = 0; ix < len; ix += 16) {
            var cnt = Math.Min(16, len - ix);
            var line = new byte[cnt];
            Array.Copy(bits, ix, line, 0, cnt);
            // Write address + hex + ascii
            Console.Write("{0:X6}  ", ix);
            Console.Write(BitConverter.ToString(line));
            Console.Write("  ");
            // Convert non-ascii characters to .
            for (int jx = 0; jx < cnt; ++jx)
                if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
        }
        Console.ReadLine();
    }
}

JAVA_HOME is set to an invalid directory:

You should set it with C:\Program Files\Java\jdk1.8.0_12.

\bin is not required.

how to set font size based on container size?

You may be able to do this with CSS3 using calculations, however it would most likely be safer to use JavaScript.

Here is an example: http://jsfiddle.net/8TrTU/

Using JS you can change the height of the text, then simply bind this same calculation to a resize event, during resize so it scales while the user is making adjustments, or however you are allowing resizing of your elements.

Should methods in a Java interface be declared with or without a public access modifier?

It's totally subjective. I omit the redundant public modifier as it seems like clutter. As mentioned by others - consistency is the key to this decision.

It's interesting to note that the C# language designers decided to enforce this. Declaring an interface method as public in C# is actually a compile error. Consistency is probably not important across languages though, so I guess this is not really directly relevant to Java.

Collections sort(List<T>,Comparator<? super T>) method example

This might be simplest way -

Collections.sort(listOfStudent,new Comparator<Student>(){
                     public int compare(Student s1,Student s2){
                           // Write your logic here.
                     }});

Using Java 8(lambda expression) -

listOfStudent.sort((s1, s2) -> s1.age - s2.age); 

What's the difference between ".equals" and "=="?

In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.

However, the equals method can be overridden - so two distinct objects can still be equal.

For example:

String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });

System.out.println(x == y); // false
System.out.println(x.equals(y)); // true

Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:

String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!

Here x and y are references to the same string, because y is a compile-time constant equal to "hello".

Attach Authorization header for all axios requests

If you want to call other api routes in the future and keep your token in the store then try using redux middleware.

The middleware could listen for the an api action and dispatch api requests through axios accordingly.

Here is a very basic example:

actions/api.js

export const CALL_API = 'CALL_API';

function onSuccess(payload) {
  return {
    type: 'SUCCESS',
    payload
  };
}

function onError(payload) {
  return {
    type: 'ERROR',
    payload,
    error: true
  };
}

export function apiLogin(credentials) {
  return {
    onSuccess,
    onError,
    type: CALL_API,
    params: { ...credentials },
    method: 'post',
    url: 'login'
  };
}

middleware/api.js

import axios from 'axios';
import { CALL_API } from '../actions/api';

export default ({ getState, dispatch }) => next => async action => {
  // Ignore anything that's not calling the api
  if (action.type !== CALL_API) {
    return next(action);
  }

  // Grab the token from state
  const { token } = getState().session;

  // Format the request and attach the token.
  const { method, onSuccess, onError, params, url } = action;

  const defaultOptions = {
    headers: {
      Authorization: token ? `Token ${token}` : '',
    }
  };

  const options = {
    ...defaultOptions,
    ...params
  };

  try {
    const response = await axios[method](url, options);
    dispatch(onSuccess(response.data));
  } catch (error) {
    dispatch(onError(error.data));
  }

  return next(action);
};

Vector of structs initialization

You cannot access elements of an empty vector by subscript.
Always check that the vector is not empty & the index is valid while using the [] operator on std::vector.
[] does not add elements if none exists, but it causes an Undefined Behavior if the index is invalid.

You should create a temporary object of your structure, fill it up and then add it to the vector, using vector::push_back()

subject subObj;
subObj.name = s1;
sub.push_back(subObj);

What should I do when 'svn cleanup' fails?

When I face this issue with TortoiseSVN (Windows), I go to Cygwin and run the 'svn cleanup' from there; it cleans up correctly for me, after which everything works from TortoiseSVN.

What is the MySQL VARCHAR max size?

Keep in mind that MySQL has a maximum row size limit

The internal representation of a MySQL table has a maximum row size limit of 65,535 bytes, not counting BLOB and TEXT types. BLOB and TEXT columns only contribute 9 to 12 bytes toward the row size limit because their contents are stored separately from the rest of the row. Read more about Limits on Table Column Count and Row Size.

Maximum size a single column can occupy, is different before and after MySQL 5.0.3

Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.

However, note that the limit is lower if you use a multi-byte character set like utf8 or utf8mb4.

Use TEXT types inorder to overcome row size limit.

The four TEXT types are TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. These correspond to the four BLOB types and have the same maximum lengths and storage requirements.

More details on BLOB and TEXT Types

Even more

Checkout more details on Data Type Storage Requirements which deals with storage requirements for all data types.

python tuple to dict

Even more concise if you are on python 2.7:

>>> t = ((1,'a'),(2,'b'))
>>> {y:x for x,y in t}
{'a':1, 'b':2}

Is there an embeddable Webkit component for Windows / C# development?

I've just release a pre-alpha version of CefSharp my .Net bindings for the Chromium Embedded Framework.

Check it out and give me your thoughts: https://github.com/chillitom/CefSharp (binary libs and example available in the downloads page)

update: Released a new version, includes the ability to bind C# objects into the DOM and more.

update 2: no-longer alpha, lib is used in real world projects including Facebook Messenger for Windows, Rdio's Windows client and Github for Windows

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

Searching in a ArrayList with custom objects for certain strings

Use Apache CollectionUtils:

CollectionUtils.find(myList, new Predicate() {
   public boolean evaluate(Object o) {
      return name.equals(((MyClass) o).getName());
   }
}

Python: How to remove empty lists from a list?

A few options:

filter(lambda x: len(x) > 0, list1)  # Doesn't work with number types
filter(None, list1)  # Filters out int(0)
filter(lambda x: x==0 or x, list1) # Retains int(0)

sample session:

Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
>>> filter(lambda x: len(x) > 0, list1)
['text', 'text2', 'moreText']
>>> list2 = [[], [], [], [], [], 'text', 'text2', [], 'moreText', 0.5, 1, -1, 0]
>>> filter(lambda x: x==0 or x, list2)
['text', 'text2', 'moreText', 0.5, 1, -1, 0]
>>> filter(None, list2)
['text', 'text2', 'moreText', 0.5, 1, -1]
>>>

How to sort a HashMap in Java

A proper answer.

HashMap<Integer, Object> map = new HashMap<Integer, Object>();

ArrayList<Integer> sortedKeys = new ArrayList<Integer>(map.keySet());
Collections.sort(sortedKeys, new Comparator<Integer>() {
  @Override
  public int compare(Integer a, Integer b) {
    return a.compareTo(b);
  }
});

for (Integer key: sortedKeys) {
  //map.get(key);
}

Note that HashMap itself cannot maintain sorting, as other answers have pointed out. It's a hash map, and hashed values are unsorted. You can thus either sort the keys when you need to and then access the values in order, as I demonstrated above, or you can find a different collection to store your data, like an ArrayList of Pairs/Tuples, such as the Pair found in Apache Commons:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html

How to fit a smooth curve to my data in R?

the qplot() function in the ggplot2 package is very simple to use and provides an elegant solution that includes confidence bands. For instance,

qplot(x,y, geom='smooth', span =0.5)

produces enter image description here

Mocking static methods with Mockito

Use JMockit framework. It worked for me. You don't have to write statements for mocking DBConenction.getConnection() method. Just the below code is enough.

@Mock below is mockit.Mock package

Connection jdbcConnection = Mockito.mock(Connection.class);

MockUp<DBConnection> mockUp = new MockUp<DBConnection>() {

            DBConnection singleton = new DBConnection();

            @Mock
            public DBConnection getInstance() { 
                return singleton;
            }

            @Mock
            public Connection getConnection() {
                return jdbcConnection;
            }
         };

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

I agree with the other answerers that in most cases (almost always) it is necessary to sanitize Your input.

But consider such code (it is for a REST controller):

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
            case 'GET':
                return $this->doGet($request, $object);
            case 'POST':
                return $this->doPost($request, $object);
            case 'PUT':
                return $this->doPut($request, $object);
            case 'DELETE':
                return $this->doDelete($request, $object);
            default:
                return $this->onBadRequest();
}

It would not be very useful to apply sanitizing here (although it would not break anything, either).

So, follow recommendations, but not blindly - rather understand why they are for :)

Wait some seconds without blocking UI execution

Omar's solution is decent* if you cannot upgrade your environment to .NET 4.5 in order to gain access to the async and await APIs. That said, there here is one important change that should be made in order to avoid poor performance. A slight delay should be added between calls to Application.DoEvents() in order to prevent excessive CPU usage. By adding

Thread.Sleep(1);

before the call to Application.DoEvents(), you can add such a delay (1 millisecond) and prevent the application from using all of the cpu cycles available to it.

private void WaitNSeconds(int seconds)
{
    if (seconds < 1) return;
    DateTime _desired = DateTime.Now.AddSeconds(seconds);
    while (DateTime.Now < _desired) {
         Thread.Sleep(1);
         System.Windows.Forms.Application.DoEvents();
    }
}

*See https://blog.codinghorror.com/is-doevents-evil/ for a more detailed discussion on the potential pitfalls of using Application.DoEvents().

How to set up subdomains on IIS 7

This one drove me crazy... basically you need two things:

1) Make sure your DNS is setup to point to your subdomain. This means to make sure you have an A Record in the DNS for your subdomain and point to the same IP.

2) You must add an additional website in IIS 7 named subdomain.example.com

  • Sites > Add Website
  • Site Name: subdomain.example.com
  • Physical Path: select the subdomain directory
  • Binding: same ip as example.com
  • Host name: subdomain.example.com

Implement division with bit-wise operator

Implement division without divison operator: You will need to include subtraction. But then it is just like you do it by hand (only in the basis of 2). The appended code provides a short function that does exactly this.

uint32_t udiv32(uint32_t n, uint32_t d) {
    // n is dividend, d is divisor
    // store the result in q: q = n / d
    uint32_t q = 0;

    // as long as the divisor fits into the remainder there is something to do
    while (n >= d) {
        uint32_t i = 0, d_t = d;
        // determine to which power of two the divisor still fits the dividend
        //
        // i.e.: we intend to subtract the divisor multiplied by powers of two
        // which in turn gives us a one in the binary representation 
        // of the result
        while (n >= (d_t << 1) && ++i)
            d_t <<= 1;
        // set the corresponding bit in the result
        q |= 1 << i;
        // subtract the multiple of the divisor to be left with the remainder
        n -= d_t;
        // repeat until the divisor does not fit into the remainder anymore
    }
    return q;
}

JavaScript: Create and destroy class instance through class method

You can only manually delete properties of objects. Thus:

var container = {};

container.instance = new class();

delete container.instance;

However, this won't work on any other pointers. Therefore:

var container = {};

container.instance = new class();

var pointer = container.instance;

delete pointer; // false ( ie attempt to delete failed )

Furthermore:

delete container.instance; // true ( ie attempt to delete succeeded, but... )

pointer; // class { destroy: function(){} }

So in practice, deletion is only useful for removing object properties themselves, and is not a reliable method for removing the code they point to from memory.

A manually specified destroy method could unbind any event listeners. Something like:

function class(){
  this.properties = { /**/ }

  function handler(){ /**/ }

  something.addEventListener( 'event', handler, false );

  this.destroy = function(){
    something.removeEventListener( 'event', handler );
  }
}

How to get a user's client IP address in ASP.NET?

In NuGet package install Microsoft.AspNetCore.HttpOverrides Then try:

public class ClientDeviceInfo
    {
        private readonly IHttpContextAccessor httpAccessor;

        public ClientDeviceInfo(IHttpContextAccessor httpAccessor)
        {
            this.httpAccessor = httpAccessor;
        }

        public string GetClientLocalIpAddress()
        {
            return httpAccessor.HttpContext.Connection.LocalIpAddress.ToString();
        }

        public string GetClientRemoteIpAddress()
        {
            return httpAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
        }

        public string GetClientLocalPort()
        {
            return httpAccessor.HttpContext.Connection.LocalPort.ToString();
        }

        public string GetClientRemotePort()
        {
            return httpAccessor.HttpContext.Connection.RemotePort.ToString();
        }
     }

Get Selected value of a Combobox

Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)

sub myhandler(eventsource)
  process(eventsource.value)
end sub

for each cell
  cell.setEventHandler(myHandler)

But i dont know the syntax for achieving this in VB/VBA, or if is even possible.

Visual studio code CSS indentation and formatting

After opening local bootstrap.min.css in visual studio code, it looked unindented. Tried the commad ALT+Shift+F but in vain.

Then installed

CSS Formatter extension.

Reloaded it and ALT+Shift+F indented my CSS file with charm.

Bingo !!!

How to use Bootstrap in an Angular project?

I was looking for same answer and finally I found this link. You can find explained three different ways how to add bootstrap css into your angular 2 project. It helped me.

Here is the link: http://codingthesmartway.com/using-bootstrap-with-angular/

How do I display a ratio in Excel in the format A:B?

Thanks ya'll. I used this:

=CONCATENATE((number1/GCD(number1,number2)),":",((number2/GCD(number1,number2))))

If you've got 2007 this works great.

Insert Picture into SQL Server 2005 Image Field using only SQL

CREATE TABLE Employees
(
    Id int,
    Name varchar(50) not null,
    Photo varbinary(max) not null
)


INSERT INTO Employees (Id, Name, Photo) 
SELECT 10, 'John', BulkColumn 
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture

How to install popper.js with Bootstrap 4?

Bootstrap 4 has two dependencies: jQuery 1.9.1 and popper.js 1.12.3. When you install Bootstrap 4, you need to install these two dependencies.

For Bootstrap 4.1

SQL: Two select statements in one query

select name, games, goals
from tblMadrid where name = 'ronaldo'
union
select name, games, goals
from tblBarcelona where name = 'messi'
ORDER  BY goals 

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

Reverse Singly Linked List Java

You can also try this

    LinkedListNode pointer = head;
    LinkedListNode prev = null, curr = null;

    /* Pointer variable loops through the LL */
    while(pointer != null)
    {
        /* Proceed the pointer variable. Before that, store the current pointer. */
        curr = pointer; //          
        pointer = pointer.next;         

        /* Reverse the link */
        curr.next = prev;

        /* Current becomes previous for the next iteration */
        prev = curr;            
    }

    System.out.println(prev.printForward());

if A vs if A is not None:

The former is more Pythonic (better ideomatic code), but will not execute the block if A is False (not None).

Make div stay at bottom of page's content all the time even when there are scrollbars

This is an intuitive solution using the viewport command that just sets the minimum height to the viewport height minus the footer height.

html,body{
height: 100%
}
#nonFooter{
min-height: calc(100vh - 30px)
}

#footer {
height:30px;
margin: 0;
clear: both;
width:100%;
}

How to make a simple popup box in Visual C#?

System.Windows.Forms.MessageBox.Show("My message here");

Make sure the System.Windows.Forms assembly is referenced your project.

Git log to get commits only for a specific branch

The following shell command should do what you want:

git log --all --not $(git rev-list --no-walk --exclude=refs/heads/mybranch --all)

Caveats

If you have mybranch checked out, the above command won't work. That's because the commits on mybranch are also reachable by HEAD, so Git doesn't consider the commits to be unique to mybranch. To get it to work when mybranch is checked out, you must also add an exclude for HEAD:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=HEAD \
    --all)

However, you should not exclude HEAD unless the mybranch is checked out, otherwise you risk showing commits that are not exclusive to mybranch.

Similarly, if you have a remote branch named origin/mybranch that corresponds to the local mybranch branch, you'll have to exclude it:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=refs/remotes/origin/mybranch \
    --all)

And if the remote branch is the default branch for the remote repository (usually only true for origin/master), you'll have to exclude origin/HEAD as well:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=refs/remotes/origin/mybranch \
    --exclude=refs/remotes/origin/HEAD \
    --all)

If you have the branch checked out, and there's a remote branch, and the remote branch is the default for the remote repository, then you end up excluding a lot:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=HEAD
    --exclude=refs/remotes/origin/mybranch \
    --exclude=refs/remotes/origin/HEAD \
    --all)

Explanation

The git rev-list command is a low-level (plumbing) command that walks the given revisions and dumps the SHA1 identifiers encountered. Think of it as equivalent to git log except it only shows the SHA1—no log message, no author name, no timestamp, none of that "fancy" stuff.

The --no-walk option, as the name implies, prevents git rev-list from walking the ancestry chain. So if you type git rev-list --no-walk mybranch it will only print one SHA1 identifier: the identifier of the tip commit of the mybranch branch.

The --exclude=refs/heads/mybranch --all arguments tell git rev-list to start from each reference except for refs/heads/mybranch.

So, when you run git rev-list --no-walk --exclude=refs/heads/mybranch --all, Git prints the SHA1 identifier of the tip commit of each ref except for refs/heads/mybranch. These commits and their ancestors are the commits you are not interested in—these are the commits you do not want to see.

The other commits are the ones you want to see, so we collect the output of git rev-list --no-walk --exclude=refs/heads/mybranch --all and tell Git to show everything but those commits and their ancestors.

The --no-walk argument is necessary for large repositories (and is an optimization for small repositories): Without it, Git would have to print, and the shell would have to collect (and store in memory) many more commit identifiers than necessary. With a large repository, the number of collected commits could easily exceed the shell's command-line argument limit.

Git bug?

I would have expected the following to work:

git log --all --not --exclude=refs/heads/mybranch --all

but it does not. I'm guessing this is a bug in Git, but maybe it's intentional.

How to display the function, procedure, triggers source code in postgresql?

additionally to @franc's answer you can use this from sql interface:

select 
    prosrc
from pg_trigger, pg_proc
where
 pg_proc.oid=pg_trigger.tgfoid
 and pg_trigger.tgname like '<name>'

(taken from here: http://www.postgresql.org/message-id/Pine.BSF.4.10.10009140858080.28013-100000@megazone23.bigpanda.com)

Is there a way of setting culture for a whole application? All current threads and new threads?

DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture are present in Framework 4.0 too, but they are Private. Using Reflection you can easily set them. This will affect all threads where CurrentCulture is not explicitly set (running threads too).

Public Sub SetDefaultThreadCurrentCulture(paCulture As CultureInfo)
    Thread.CurrentThread.CurrentCulture.GetType().GetProperty("DefaultThreadCurrentCulture").SetValue(Thread.CurrentThread.CurrentCulture, paCulture, Nothing)
    Thread.CurrentThread.CurrentCulture.GetType().GetProperty("DefaultThreadCurrentUICulture").SetValue(Thread.CurrentThread.CurrentCulture, paCulture, Nothing)
End Sub

Float a DIV on top of another DIV

What about:

.close-image{
    display:block;
    cursor:pointer;
    z-index:3;
    position:absolute;
    top:0;
    right:0;
}

Is that the desired result?

What's wrong with overridable method calls in constructors?

In the specific case of Wicket: This is the very reason why I asked the Wicket devs to add support for an explicit two phase component initialization process in the framework's lifecycle of constructing a component i.e.

  1. Construction - via constructor
  2. Initialization - via onInitilize (after construction when virtual methods work!)

There was quite an active debate about whether it was necessary or not (it fully is necessary IMHO) as this link demonstrates http://apache-wicket.1842946.n4.nabble.com/VOTE-WICKET-3218-Component-onInitialize-is-broken-for-Pages-td3341090i20.html)

The good news is that the excellent devs at Wicket did end up introducing two phase initialization (to make the most aweseome Java UI framework even more awesome!) so with Wicket you can do all your post construction initialization in the onInitialize method that is called by the framework automatically if you override it - at this point in the lifecycle of your component its constructor has completed its work so virtual methods work as expected.

symfony2 twig path with parameter url creation

In Twig:

{% for l in locations %}

<tr>
    <td>
        <input type="checkbox" class="filled-in" id="filled-in-box-{{ l.idLocation }}" />
        <label for="filled-in-box-{{ l.idLocation }}"></label>
    </td>
    <td>{{ l.loc }}</td>
    <td>{{ l.mun }}</td>
    <td>{{ l.pro }}</td>
    <td>{{ l.cou }}</td>
    {#<td>
        {% if l.active == 1  %}
            <span class="fa fa-check"></span>
        {% else %}
            <span class="fa fa-close"></span>
        {% endif %}
    </td>#}
    <td><a href="{{ url('admin_edit_location',{'id': l.idLocation}) }}" class="db-list-edit"><span class="fa fa-pencil-square-o"></span></a>
    </td>
</tr>{% endfor %}

The route admin_edit_location:

admin_edit_location:
  path: /edit_location/{id}
  defaults: { _controller: "AppBundle:Admin:editLocation" }
  methods: GET

And the controller

public function editLocationAction($id){
    // use $id 

    $em = $this->getDoctrine()->getManager();
    $location = $em->getRepository('BackendBundle:locations')->findOneBy(array(
    'id'    => $id
    ));
}

SQL Server 2005 Setting a variable to the result of a select query

You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.

Incidentally, since you are using a predicate like this:

CONVERT(...) = CONVERT(...)

that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.

Here is one way to make the original query somewhat better:

DECLARE @ooDate datetime
SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  FF.FaultDate >= @ooDate AND
  FF.FaultDate < DATEADD(day, 1, @ooDate) AND
  OFIO.OutageID = 1

This version could leverage in index that involved FaultDate, and achieves the same goal.

Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
  OFIO.OutageID = 1

Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.

Regards.

Highlight Bash/shell code in Markdown files

If I need only to highlight the first word as a command, I often use properties:

```properties
npm run build
```  

I obtain something like:

npm run build

html select scroll bar

One options will be to show the selected option above (or below) the select list like following:

HTML

<div id="selText"><span>&nbsp;</span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"   
  type="text/javascript"></script> 
<script type="text/javascript">
$(document).ready(function(){        
    $("select#mySelect").change(function(){
      //$("#selText").html($($(this).children("option:selected")[0]).text());
       var txt = $($(this).children("option:selected")[0]).text();
       $("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));
    });
});
</script>

PS:- Set height of div#selText otherwise it will keep shifting select list downward.

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

I was looking to do the same thing, and I have a work around that seems to be less complicated using the Frequency and Index functions. I use this part of the function from averaging over multiple sheets while excluding the all the 0's.

=(FREQUENCY(Start:End!B1,-0.000001)+INDEX(FREQUENCY(Start:End!B1,0),2))

Do the parentheses after the type name make a difference with new?

The rules for new are analogous to what happens when you initialize an object with automatic storage duration (although, because of vexing parse, the syntax can be slightly different).

If I say:

int my_int; // default-initialize ? indeterminate (non-class type)

Then my_int has an indeterminate value, since it is a non-class type. Alternatively, I can value-initialize my_int (which, for non-class types, zero-initializes) like this:

int my_int{}; // value-initialize ? zero-initialize (non-class type)

(Of course, I can't use () because that would be a function declaration, but int() works the same as int{} to construct a temporary.)

Whereas, for class types:

Thing my_thing; // default-initialize ? default ctor (class type)
Thing my_thing{}; // value-initialize ? default-initialize ? default ctor (class type)

The default constructor is called to create a Thing, no exceptions.

So, the rules are more or less:

  • Is it a class type?
    • YES: The default constructor is called, regardless of whether it is value-initialized (with {}) or default-initialized (without {}). (There is some additional prior zeroing behavior with value-initialization, but the default constructor is always given the final say.)
    • NO: Were {} used?
      • YES: The object is value-initialized, which, for non-class types, more or less just zero-initializes.
      • NO: The object is default-initialized, which, for non-class types, leaves it with an indeterminate value (it effectively isn't initialized).

These rules translate precisely to new syntax, with the added rule that () can be substituted for {} because new is never parsed as a function declaration. So:

int* my_new_int = new int; // default-initialize ? indeterminate (non-class type)
Thing* my_new_thing = new Thing; // default-initialize ? default ctor (class type)
int* my_new_zeroed_int = new int(); // value-initialize ? zero-initialize (non-class type)
     my_new_zeroed_int = new int{}; // ditto
       my_new_thing = new Thing(); // value-initialize ? default-initialize ? default ctor (class type)

(This answer incorporates conceptual changes in C++11 that the top answer currently does not; notably, a new scalar or POD instance that would end up an with indeterminate value is now technically now default-initialized (which, for POD types, technically calls a trivial default constructor). While this does not cause much practical change in behavior, it does simplify the rules somewhat.)

HTML email with Javascript

What you are trying to achieve should be done in the web browser because javascript simply doesn't work with html email design. The various email clients that are out there e.g. gmail, outlook, yahoo strip scripts put of the code for security reasons.

It is best to just use HTML and CSS to style your emails. Maybe you could have a call to action (cta) in your html email that sends the user to a web page with your expanding and collapsing content feature.

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

How to get start and end of previous month in VB

Try this

First_Day_Of_Previous_Month = New Date(Today.Year, Today.Month, 1).AddMonths(-1)

Last_Day_Of_Previous_Month = New Date(Today.Year, Today.Month, 1).AddDays(-1)

Post Build exited with code 1

She had a space in one of the folder names in her path, and no quotes around it.

MySQL - UPDATE multiple rows with different values in one query

I did it this way:

<update id="updateSettings" parameterType="PushSettings">
    <foreach collection="settings" item="setting">
        UPDATE push_setting SET status = #{setting.status}
        WHERE type = #{setting.type} AND user_id = #{userId};
    </foreach>
</update>

where PushSettings is

public class PushSettings {

    private List<PushSetting> settings;
    private String userId;
}

it works fine

How to get the integer value of day of week

Try this. It will work just fine:

int week = Convert.ToInt32(currentDateTime.DayOfWeek);

Pass Array Parameter in SqlCommand

I wanted to expand on the answer that Brian contributed to make this easily usable in other places.

/// <summary>
/// This will add an array of parameters to a SqlCommand. This is used for an IN statement.
/// Use the returned value for the IN part of your SQL call. (i.e. SELECT * FROM table WHERE field IN (returnValue))
/// </summary>
/// <param name="sqlCommand">The SqlCommand object to add parameters to.</param>
/// <param name="array">The array of strings that need to be added as parameters.</param>
/// <param name="paramName">What the parameter should be named.</param>
protected string AddArrayParameters(SqlCommand sqlCommand, string[] array, string paramName)
{
    /* An array cannot be simply added as a parameter to a SqlCommand so we need to loop through things and add it manually. 
     * Each item in the array will end up being it's own SqlParameter so the return value for this must be used as part of the
     * IN statement in the CommandText.
     */
    var parameters = new string[array.Length];
    for (int i = 0; i < array.Length; i++)
    {
        parameters[i] = string.Format("@{0}{1}", paramName, i);
        sqlCommand.Parameters.AddWithValue(parameters[i], array[i]);
    }

    return string.Join(", ", parameters);
}

You can use this new function as follows:

SqlCommand cmd = new SqlCommand();

string ageParameters = AddArrayParameters(cmd, agesArray, "Age");
sql = string.Format("SELECT * FROM TableA WHERE Age IN ({0})", ageParameters);

cmd.CommandText = sql;


Edit: Here is a generic variation that works with an array of values of any type and is usable as an extension method:

public static class Extensions
{
    public static void AddArrayParameters<T>(this SqlCommand cmd, string name, IEnumerable<T> values) 
    { 
        name = name.StartsWith("@") ? name : "@" + name;
        var names = string.Join(", ", values.Select((value, i) => { 
            var paramName = name + i; 
            cmd.Parameters.AddWithValue(paramName, value); 
            return paramName; 
        })); 
        cmd.CommandText = cmd.CommandText.Replace(name, names); 
    }
}

You can then use this extension method as follows:

var ageList = new List<int> { 1, 3, 5, 7, 9, 11 };
var cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM MyTable WHERE Age IN (@Age)";    
cmd.AddArrayParameters("Age", ageList);

Make sure you set the CommandText before calling AddArrayParameters.

Also make sure your parameter name won't partially match anything else in your statement (i.e. @AgeOfChild)

How do I assert an Iterable contains elements with a certain property?

Alternatively to hasProperty you can try hamcrest-more-matchers where matcher with extracting function. In your case it will look like:

import static com.github.seregamorph.hamcrest.MoreMatchers.where;

assertThat(myClass.getMyItems(), contains(
    where(MyItem::getName, is("foo")), 
    where(MyItem::getName, is("bar"))
));

The advantages of this approach are:

  • It is not always possible to verify by field if the value is computed in get-method
  • In case of mismatch there should be a failure message with diagnostics (pay attention to resolved method reference MyItem.getName:
Expected: iterable containing [Object that matches is "foo" after call
MyItem.getName, Object that matches is "bar" after call MyItem.getName]
     but: item 0: was "wrong-name"
  • It works in Java 8, Java 11 and Java 14

delete map[key] in go?

Use make (chan int) instead of nil. The first value has to be the same type that your map holds.

package main

import "fmt"

func main() {

    var sessions = map[string] chan int{}
    sessions["somekey"] = make(chan int)

    fmt.Printf ("%d\n", len(sessions)) // 1

    // Remove somekey's value from sessions
    delete(sessions, "somekey")

    fmt.Printf ("%d\n", len(sessions)) // 0
}

UPDATE: Corrected my answer.

Python convert set to string and vice versa

Use repr and eval:

>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])

Note that eval is not safe if the source of string is unknown, prefer ast.literal_eval for safer conversion:

>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])

help on repr:

repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

If you have just one query I don't know how to set timeout on T-SQL level.

However if you have a few queries (i.e. collecting data into temporary tables) inside stored procedure you can just control time of execution with GETDATE(), DATEDIFF() and a few INT variables storing time of execution of each part.

R - Markdown avoiding package loading messages

This is an old question, but here's another way to do it.

You can modify the R code itself instead of the chunk options, by wrapping the source call in suppressPackageStartupMessages(), suppressMessages(), and/or suppressWarnings(). E.g:

```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```

You can also put those functions around your library() calls inside the "source.R" script.

Compiling Java 7 code via Maven

try using a newer version of the maven compiler plugin:

    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
            <source>1.7</source>
            <target>1.7</target>
        </configuration>
    </plugin>

also, specifying source file encoding in maven is better done globally:

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

EDIT: As this answer is still getting attention i'd just like to point out that the latest values (as of latest edit) are 3.2 for maven compiler plugin and 1.8 for java, as questions about compiling java 8 code via maven are bound to appear soon :-)

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

I added the jenkins user to root group and restarted the jenkins and it started working.

sudo usermod -a -G root jenkins
sudo service jenkins restart

How can I create an editable dropdownlist in HTML?

I am not sure there is a way to do it automatically without javascript.

What you need is something which runs on the browser side to submit your form back to the server when they user makes a selection - hence, javascript.

Also, ensure you have an alternate means (i.e. a submit button) for those who have javascript turned off.

A good example: Combo-Box Viewer

I had even a more sophisticated combo-box yesterday, with this dhtmlxCombo , using ajax to retrieve pertinent values amongst large quantity of data.

How to use JavaScript variables in jQuery selectors?

var x = $(this).attr("name");
$("#" + x).hide();

A variable modified inside a while loop is not remembered

How about a very simple method

    +call your while loop in a function 
     - set your value inside (nonsense, but shows the example)
     - return your value inside 
    +capture your value outside
    +set outside
    +display outside


    #!/bin/bash
    # set -e
    # set -u
    # No idea why you need this, not using here

    foo=0
    bar="hello"

    if [[ "$bar" == "hello" ]]
    then
        foo=1
        echo "Setting  \$foo to $foo"
    fi

    echo "Variable \$foo after if statement: $foo"

    lines="first line\nsecond line\nthird line"

    function my_while_loop
    {

    echo -e $lines | while read line
    do
        if [[ "$line" == "second line" ]]
        then
        foo=2; return 2;
        echo "Variable \$foo updated to $foo inside if inside while loop"
        fi

        echo -e $lines | while read line
do
    if [[ "$line" == "second line" ]]
    then
    foo=2;          
    echo "Variable \$foo updated to $foo inside if inside while loop"
    return 2;
    fi

    # Code below won't be executed since we returned from function in 'if' statement
    # We aready reported the $foo var beint set to 2 anyway
    echo "Value of \$foo in while loop body: $foo"

done
}

    my_while_loop; foo="$?"

    echo "Variable \$foo after while loop: $foo"


    Output:
    Setting  $foo 1
    Variable $foo after if statement: 1
    Value of $foo in while loop body: 1
    Variable $foo after while loop: 2

    bash --version

    GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
    Copyright (C) 2007 Free Software Foundation, Inc.

Authentication issue when debugging in VS2013 - iis express

Open up the applicationHost.config file located in the C:\Users[userid]\Documents\IISExpress\config folder. Inside this file change the overrideModeDefault of anonymousAthentication and windowsAuthentication to "Allow"

 <sectionGroup name="security">
                <section name="access" overrideModeDefault="Deny" />
                <section name="applicationDependencies" overrideModeDefault="Deny" />
                <sectionGroup name="authentication">
                    <section name="anonymousAuthentication" overrideModeDefault="Allow" />
                    <section name="basicAuthentication" overrideModeDefault="Deny" />
                    <section name="clientCertificateMappingAuthentication" overrideModeDefault="Deny" />
                    <section name="digestAuthentication" overrideModeDefault="Deny" />
                    <section name="iisClientCertificateMappingAuthentication" overrideModeDefault="Deny" />
                    <section name="windowsAuthentication" overrideModeDefault="Allow" />
                </sectionGroup>

Next change lockItem to be "false" for AnonymousAuthenticationModule and WindowsAuthenticationModule

  <system.webServer>
            <modules>
                <!--
                <add name="HttpCacheModule" lockItem="true" />
-->
                <add name="DynamicCompressionModule" lockItem="true" />
                <add name="StaticCompressionModule" lockItem="true" />
                <add name="DefaultDocumentModule" lockItem="true" />
                <add name="DirectoryListingModule" lockItem="true" />
                <add name="IsapiFilterModule" lockItem="true" />
                <add name="ProtocolSupportModule" lockItem="true" />
                <add name="HttpRedirectionModule" lockItem="true" />
                <add name="ServerSideIncludeModule" lockItem="true" />
                <add name="StaticFileModule" lockItem="true" />
                <add name="AnonymousAuthenticationModule" lockItem="false" />
                <add name="CertificateMappingAuthenticationModule" lockItem="true" />
                <add name="UrlAuthorizationModule" lockItem="true" />
                <add name="BasicAuthenticationModule" lockItem="true" />
                <add name="WindowsAuthenticationModule" lockItem="false" />

Making these changes will allow the existing web config settings to override what is in the applicationHost file for IIS Express.

Submit form with Enter key without submit button?

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

How to print object array in JavaScript?

I use the below function to display a readout in firefox console log:

////        make printable string for console readout, recursively
var make_printable_object = function(ar_use)
{
////        internal arguments
var in_tab = arguments[1];
var st_return = arguments[2];
////        default vales when applicable
if (!in_tab) in_tab = 0;
if (!st_return) st_return = "";
////        add depth
var st_tab = "";
for (var i=0; i < in_tab; i++) st_tab = st_tab+"-~-~-";

////        traverse given depth and build string
for (var key in ar_use)
{
    ////        gather return type
    var st_returnType = typeof ar_use[key];
    ////        get current depth display
    var st_returnPrime = st_tab+ "["+key+"] ->"+ar_use[key]+"< is {"+st_returnType+"}";
    ////        remove linefeeds to avoid printout confusion
    st_returnPrime = st_returnPrime.replace(/(\r\n|\n|\r)/gm,"");
    ////        add line feed
    st_return = st_return+st_returnPrime+"\n";
    ////         stop at a depth of 15
    if (in_tab>15) return st_return;
    ////        if current value is an object call this function
    if ( (typeof ar_use[key] == "object") & (ar_use[key] != "null") & (ar_use[key] != null) ) st_return = make_printable_object(ar_use[key], in_tab+1, st_return);


}

////        return complete output
return st_return;

};

Example:

console.log( make_printable_object( some_object ) );

Alternatively, you can just replace:

st_return = st_return+st_returnPrime+"\n";

with

st_return = st_return+st_returnPrime+"<br/>";

to print out in a html page.

How to insert a column in a specific position in oracle without dropping and recreating the table?

Although this is somewhat old I would like to add a slightly improved version that really changes column order. Here are the steps (assuming we have a table TAB1 with columns COL1, COL2, COL3):

  1. Add new column to table TAB1:
alter table TAB1 add (NEW_COL number);
  1. "Copy" table to temp name while changing the column order AND rename the new column:
create table tempTAB1 as select NEW_COL as COL0, COL1, COL2, COL3 from TAB1;
  1. drop existing table:
drop table TAB1;
  1. rename temp tablename to just dropped tablename:
rename tempTAB1 to TAB1;

How to make HTML open a hyperlink in another window or tab?

You can also accomplish this by adding the following to your page's header:

<base target="_blank">

This will make ALL links on your page open in a new tab

CSS for the "down arrow" on a <select> element?

Try this

   <div style='position:relative;left:0px;top:0px;
        onMouseOver=document.getElementById('visible').style.visibility='visible' 
        id='hidden'>10
   <select style='position:absolute;left:0px;top:0px;cursor:pointer;visibility:hidden;'
        onMouseOut=document.getElementById('visible').style.visibility='hidden'
        onChange='this.form.submit()' 
        id='visible' multiple size='3'>";
   <option selected value=10>10</option>
   <option value=20>20</option>
   <option value=50>50</option>
   </select>
   </div>

How to set timeout on python's socket recv method?

Got a bit confused from the top answers so I've wrote a small gist with examples for better understanding.


Option #1 - socket.settimeout()

Will raise an exception in case the sock.recv() waits for more than the defined timeout.

import socket

sock = socket.create_connection(('neverssl.com', 80))
timeout_seconds = 2
sock.settimeout(timeout_seconds)
sock.send(b'GET / HTTP/1.1\r\nHost: neverssl.com\r\n\r\n')
data = sock.recv(4096)
data = sock.recv(4096) # <- will raise a socket.timeout exception here

Option #2 - select.select()

Waits until data is sent until the timeout is reached. I've tweaked Daniel's answer so it will raise an exception

import select
import socket

def recv_timeout(sock, bytes_to_read, timeout_seconds):
    sock.setblocking(0)
    ready = select.select([sock], [], [], timeout_seconds)
    if ready[0]:
        return sock.recv(bytes_to_read)

    raise socket.timeout()

sock = socket.create_connection(('neverssl.com', 80))
timeout_seconds = 2
sock.send(b'GET / HTTP/1.1\r\nHost: neverssl.com\r\n\r\n')
data = recv_timeout(sock, 4096, timeout_seconds)
data = recv_timeout(sock, 4096, timeout_seconds) # <- will raise a socket.timeout exception here

JSON and XML comparison

Processing speed may not be the only relevant matter, however, as that's the question, here are some numbers in a benchmark: JSON vs. XML: Some hard numbers about verbosity. For the speed, in this simple benchmark, XML presents a 21% overhead over JSON.

An important note about the verbosity, which is as the article says, the most common complain: this is not so much relevant in practice (neither XML nor JSON data are typically handled by humans, but by machines), even if for the matter of speed, it requires some reasonable more time to compress.

Also, in this benchmark, a big amount of data was processed, and a typical web application won't transmit data chunks of such sizes, as big as 90MB, and compression may not be beneficial (for small enough data chunks, a compressed chunk will be bigger than the uncompressed chunk), so not applicable.

Still, if no compression is involved, JSON, as obviously terser, will weight less over the transmission channel, especially if transmitted through a WebSocket connection, where the absence of the classic HTTP overhead may make the difference at the advantage of JSON, even more significant.

After transmission, data is to be consumed, and this count in the overall processing time. If big or complex enough data are to be transmitted, the lack of a schema automatically checked for by a validating XML parser, may require more check on JSON data; these checks would have to be executed in JavaScript, which is not known to be particularly fast, and so it may present an additional overhead over XML in such cases.

Anyway, only testing will provides the answer for your particular use-case (if speed is really the only matter, and not standard nor safety nor integrity…).

Update 1: worth to mention, is EXI, the binary XML format, which offers compression at less cost than using Gzip, and save processing otherwise needed to decompress compressed XML. EXI is to XML, what BSON is to JSON. Have a quick overview here, with some reference to efficiency in both space and time: EXI: The last binary standard?.

Update 2: there also exists a binary XML performance reports, conducted by the W3C, as efficiency and low memory and CPU footprint, is also a matter for the XML area too: Efficient XML Interchange Evaluation.

Update 2015-03-01

Worth to be noticed in this context, as HTTP overhead was raised as an issue: the IANA has registered the EXI encoding (the efficient binary XML mentioned above), as a a Content Coding for the HTTP protocol (alongside with compress, deflate and gzip). This means EXI is an option which can be expected to be understood by browsers among possibly other HTTP clients. See Hypertext Transfer Protocol Parameters (iana.org).

change text of button and disable button in iOS

Assuming that the button is a UIButton:

UIButton *button = …;
[button setEnabled:NO]; // disables
[button setTitle:@"Foo" forState:UIControlStateNormal]; // sets text

See the documentation for UIButton.

Calculating the position of points in a circle

PHP Solution:

class point{
    private $x = 0;
    private $y = 0;
    public function setX($xpos){
        $this->x = $xpos;
    }
    public function setY($ypos){
        $this->y = $ypos;
    }
    public function getX(){
        return $this->x;
    }
    public function getY(){
        return $this->y;
    }
    public function printX(){
        echo $this->x;
    }
    public function printY(){
        echo $this->y;
    }
}
function drawCirclePoints($points, $radius, &$center){
    $pointarray = array();
    $slice = (2*pi())/$points;
    for($i=0;$i<$points;$i++){
        $angle = $slice*$i;
        $newx = (int)($center->getX() + ($radius * cos($angle)));
        $newy = (int)($center->getY() + ($radius * sin($angle)));
        $point = new point();
        $point->setX($newx);
        $point->setY($newy);
        array_push($pointarray,$point);
    }
    return $pointarray;
}

What are some ways of accessing Microsoft SQL Server from Linux?

There is an abstraction lib available for PHP. Not sure what your client's box will support but if its Linux then certainly should support building a PHP query interface with this: http://adodb.sourceforge.net/ Hope that helps you.

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

One more reason...

I ran into an Ubuntu server where everything was customized and could not connect because of that same error.

This setting was inside /etc/ssh/sshd_config

PermitTunnel no

After turning into

PermitTunnel yes

I was able to connect remotely to my MySQL DB

Where is Maven Installed on Ubuntu

Ubuntu 11.10 doesn't have maven3 in repo.

Follow below step to install maven3 on ubuntu 11.10

sudo add-apt-repository ppa:natecarlson/maven3
sudo apt-get update && sudo apt-get install maven3

Open terminal: mvn3 -v

if you want mvn as a binary then execute below script:

sudo ln -s /usr/bin/mvn3 /usr/bin/mvn

I hope this will help you.

Thanks, Rajam

Configure Log4Net in web application

Another way to do this would be to add this line to the assembly info of the web application:

// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Similar to Shriek's.

what is reverse() in Django

There is a doc for that

https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls

it can be used to generate an URL for a given view

main advantage is that you do not hard code routes in your code.

PHPMailer AddAddress()

You need to call the AddAddress function once for each E-Mail address you want to send to. There are only two arguments for this function: recipient_email_address and recipient_name. The recipient name is optional and will not be used if not present.

$mailer->AddAddress('[email protected]', 'First Name');
$mailer->AddAddress('[email protected]', 'Second Name');
$mailer->AddAddress('[email protected]', 'Third Name');

You could use an array to store the recipients and then use a for loop. I hope it helps.

How to list npm user-installed packages?

You can get a list of all globally installed modules using:

ls `npm root -g`

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

What does localhost:8080 mean?

A TCP/IP connection is always made to an IP address (you can think of an IP-address as the address of a certain computer, even if that is not always the case) and a specific (logical, not physical) port on that address.

Usually one port is coupled to a specific process or "service" on the target computer. Some port numbers are standardized, like 80 for http, 25 for smtp and so on. Because of that standardization you usually don't need to put port numbers into your web adresses.

So if you say something like http://www.stackoverflow.com, the part "stackoverflow.com" resolves to an IP address (in my case 64.34.119.12) and because my browser knows the standard it tries to connect to port 80 on that address. Thus this is the same as http://www.stackoverflow.com:80.

But there is nothing that stops a process to listen for http requests on another port, like 12434, 4711 or 8080. Usually (as in your case) this is used for debugging purposes to not intermingle with another process (like IIS) already listening to port 80 on the same machine.

How to check if another instance of the application is running

You can try this

Process[] processes = Process.GetProcessesByName("processname");
foreach (Process p in processes)
{
    IntPtr pFoundWindow = p.MainWindowHandle;
    // Do something with the handle...
    //
}

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

IIS7 folder permissions for web application

If it's any help to anyone, give permission to "IIS_IUSRS" group.

Note that if you can't find "IIS_IUSRS", try prepending it with your server's name, like "MySexyServer\IIS_IUSRS".

Angular 4 - Observable catch error

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );

Converting string format to datetime in mm/dd/yyyy

I did like this

var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I had to use Debug.print instead of Print, which works in the Immediate window.

Sub SendEmail()
    'Dim objHTTP As New MSXML2.XMLHTTP
    'Set objHTTP = New MSXML2.XMLHTTP60
    'Dim objHTTP As New MSXML2.XMLHTTP60
    Dim objHTTP As New WinHttp.WinHttpRequest
    'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://localhost:8888/rest/mail/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

End Sub