Programs & Examples On #Openfire

Openfire is a XMPP (Jabber) server written in Java. It has facility for developers to create plugins that can extend the server's functionality.

cd into directory without having permission

@user812954's answer was quite helpful, except I had to do this this in two steps:

sudo su
cd directory

Then, to exit out of "super user" mode, just type exit.

Return Type for jdbcTemplate.queryForList(sql, object, classType)

List<Conversation> conversations = **jdbcTemplate**.**queryForList**(
            **SQL_QUERY**,
            new Object[] {userId, dateFrom, dateTo});  //placeholders values

Suppose the sql query is like

SQL_QUERY = "**select** info,count(*),IF(info is null , 'DATA' , 'NO DATA') **from** table where userId=? , dateFrom=? , dateTo=?";

**HERE userId=? , dateFrom=? , dateTo=?**

the question marks are place holders

**SQL_QUERY**,
            new Object[] {userId, dateFrom, dateTo});

It will go as an object array along with the sql query

What is the difference between SQL, PL-SQL and T-SQL?

  • SQL a language for talking to the database. It lets you select data, mutate and create database objects (like tables, views, etc.), change database settings.
  • PL-SQL a procedural programming language (with embedded SQL)
  • T-SQL (procedural) extensions for SQL used by SQL Server

How can I store JavaScript variable output into a PHP variable?

The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET parameter -

<script>
  var a="Hello";
  window.location.href = window.location.href+'?a='+a;
</script>

Your page will reload and now in your PHP, you'll have access to the $_GET['a'] variable.

<?php 
  $variable = $_GET['a'];
?>

How to change the default charset of a MySQL table?

The ALTER TABLE MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.

I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.

Make EditText ReadOnly

Try using

editText.setEnabled(false);
editText.setClickable(false);

Clicking at coordinates without identifying element

In Selenium Java, you can try it using Javascript:

_x000D_
_x000D_
WebDriver driver = new ChromeDriver();_x000D_
_x000D_
if (driver instanceof JavascriptExecutor) {_x000D_
 ((JavascriptExecutor) driver).executeScript("el = document.elementFromPoint(x-cordinate, y-cordinate); el.click();");_x000D_
}
_x000D_
_x000D_
_x000D_

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

I usually go with PNG, as it seems to have a few advantages over GIF. There used to be patent restrictions on GIF, but those have expired.

GIFs are suitable for sharp-edged line art (such as logos) with a limited number of colors. This takes advantage of the format's lossless compression, which favors flat areas of uniform color with well defined edges (in contrast to JPEG, which favors smooth gradients and softer images).

GIFs can be used for small animations and low-resolution film clips.

In view of the general limitation on the GIF image palette to 256 colors, it is not usually used as a format for digital photography. Digital photographers use image file formats capable of reproducing a greater range of colors, such as TIFF, RAW or the lossy JPEG, which is more suitable for compressing photographs.

The PNG format is a popular alternative to GIF images since it uses better compression techniques and does not have a limit of 256 colors, but PNGs do not support animations. The MNG and APNG formats, both derived from PNG, support animations, but are not widely used.

How to sort by dates excel?

  1. Select the whole column
  2. Right click -> Format cells... -> Number -> Category: Date -> OK
  3. Data -> Text to Columns -> select Delimited -> Next -> in your case selection of Delimiters doesn't matter -> Next -> select Date: DMY -> Finish

Now you should be able to sort by this column either Oldest to Newest or Newest to Oldest

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

    $(document).on('keyup keydown', function(e){shifted = e.shiftKey} );

How can I get the sha1 hash of a string in node.js?

Please read and strongly consider my advice in the comments of your post. That being said, if you still have a good reason to do this, check out this list of crypto modules for Node. It has modules for dealing with both sha1 and base64.

MySql difference between two timestamps in days?

SELECT DATEDIFF(max_date, min_date) as days from my table. This works even if the col max_date and min_date are in string data types.

Apache won't run in xampp

Take a look at this site:

http://www.lukebrowning.com/blog/nt-kernel-system-using-port-80/

In my case, it was the SQL Server Reporting Service, but others have seen IIS or the Web Deployment Agent Service.

Open a cmd window and run services.msc, find the service, and stop it. Then try to start Apache. If it works, disable the other service.

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

I solved it with my own function. If you want to update specified field in document you need to address it clearly.

Example:

{
    _id : ...,
    some_key: { 
        param1 : "val1",
        param2 : "val2",
        param3 : "val3"
    }
}

If you want to update param2 only, it's wrong to do:

db.collection.update(  { _id:...} , { $set: { some_key : new_info  } }  //WRONG

You must use:

db.collection.update(  { _id:...} , { $set: { some_key.param2 : new_info  } } 

So i wrote a function something like that:

function _update($id, $data, $options=array()){

    $temp = array();
    foreach($data as $key => $value)
    {
        $temp["some_key.".$key] = $value;
    } 

    $collection->update(
        array('_id' => $id),
        array('$set' => $temp)
    );

}

_update('1', array('param2' => 'some data'));

SQLAlchemy insert or update example

I try lots of ways and finally try this:

def db_persist(func):
    def persist(*args, **kwargs):
        func(*args, **kwargs)
        try:
            session.commit()
            logger.info("success calling db func: " + func.__name__)
            return True
        except SQLAlchemyError as e:
            logger.error(e.args)
            session.rollback()
            return False

    return persist

and :

@db_persist
def insert_or_update(table_object):
    return session.merge(table_object)

Using sed and grep/egrep to search and replace

try something using a for loop

 for i in `egrep -lR "YOURSEARCH" .` ; do echo  $i; sed 's/f/k/' <$i >/tmp/`basename $i`; mv /tmp/`basename $i` $i; done

not pretty, but should do.

Global Angular CLI version greater than local version

Just do these things

npm install --save-dev @angular/cli@latest
npm audit fix
npm audit fix --force

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

Python sys.argv lists and indexes

let's say on the command-line you have:

C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises
\google-python-exercises\hello.py John

to make it easier to read, let's just shorten this to:

C:\> hello.py John

argv represents all the items that come along via the command-line input, but counting starts at zero (0) not one (1): in this case, "hello.py" is element 0, "John" is element 1

in other words, sys.argv[0] == 'hello.py' and sys.argv[1] == 'John' ... but look, how many elements is this? 2, right! so even though the numbers are 0 and 1, there are 2 elements here.

len(sys.argv) >= 2 just checks whether you entered at least two elements. in this case, we entered exactly 2.

now let's translate your code into English:

define main() function:
    if there are at least 2 elements on the cmd-line:
        set 'name' to the second element located at index 1, e.g., John
    otherwise there is only 1 element... the program name, e.g., hello.py:
        set 'name' to "World" (since we did not get any useful user input)
    display 'Hello' followed by whatever i assigned to 'name'

so what does this mean? it means that if you enter:

  • "hello.py", the code outputs "Hello World" because you didn't give a name
  • "hello.py John", the code outputs "Hello John" because you did
  • "hello.py John Paul", the code still outputs "Hello John" because it does not save nor use sys.argv[2], which was "Paul" -- can you see in this case that len(sys.argv) == 3 because there are 3 elements in the sys.argv list?

Oracle SQL Developer: Unable to find a JVM

The solution that worked for me: If you have Sqldeveloper with java incorporated, you can use the \sqldeveloper\bin\sqldeveloper.bat to launch sqldeveloper as told here.

Loop and get key/value pair for JSON array using jQuery

The following should work for a JSON returned string. It will also work for an associative array of data.

for (var key in data)
     alert(key + ' is ' + data[key]);

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

Transport security is provided in iOS 9.0 or later, and in OS X v10.11 and later.

So by default only https calls only allowed in apps. To turn off App Transport Security add following lines in info.plist file...

<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
  </dict>

For more info:
https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33

SQL (MySQL) vs NoSQL (CouchDB)

One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Check if list is empty in C#

What about using the Count property.

 if(listOfObjects.Count != 0)
 {
     ShowGrid();
     HideError();
 }
 else
 {
     HideGrid();
     ShowError();
 }

PadLeft function in T-SQL

Something fairly ODBC compliant if needed might be the following:

select ifnull(repeat('0', 5 - (floor(log10(FIELD_NAME)) + 1)), '')
        + cast (FIELD as varchar(10))
  from TABLE_NAME

This bases on the fact that the amount of digits for a base-10 number can be found by the integral component of its log. From this we can subtract it from the desired padding width. Repeat will return null for values under 1 so we need ifnull.

How to vertically align a html radio button to it's label?

I know I'd selected the anwer by menuka devinda but looking at the comments below it I concurred and tried to come up with a better solution. I managed to come up with this and in my opinion it's a much more elegant solution:

input[type='radio'], label{   
    vertical-align: baseline;
    padding: 10px;
    margin: 10px;
 }

Thanks to everyone who offered an answer, your answer didn't go unnoticed. If you still got any other ideas feel free to add your own answer to this question.

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

PHP case-insensitive in_array function

  • in_array accepts these parameters : in_array(search,array,type)
  • if the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
  • so in order to make the search ignore the case, it would be enough to use it like this :

$a = array( 'one', 'two', 'three', 'four' );

$b = in_array( 'ONE', $a, false );

Is there a simple way to increment a datetime object one month in Python?

Question: Is there a simple way to do this in the current release of Python?

Answer: There is no simple (direct) way to do this in the current release of Python.

Reference: Please refer to docs.python.org/2/library/datetime.html, section 8.1.2. timedelta Objects. As we may understand from that, we cannot increment month directly since it is not a uniform time unit.

Plus: If you want first day -> first day and last day -> last day mapping you should handle that separately for different months.

Remove duplicated rows

Here's a very simple, fast dplyr/tidy solution:

Remove rows that are entirely the same:

library(dplyr)
iris %>% 
  distinct(.keep_all = TRUE)

Remove rows that are the same only in certain columns:

iris %>% 
  distinct(Sepal.Length, Sepal.Width, .keep_all = TRUE)

How to change the Push and Pop animations in a navigation based app

From the sample app, check out this variation. https://github.com/mpospese/MPFoldTransition/

#pragma mark - UINavigationController(MPFoldTransition)

@implementation UINavigationController(MPFoldTransition)

//- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
- (void)pushViewController:(UIViewController *)viewController foldStyle:(MPFoldStyle)style
{
    [MPFoldTransition transitionFromViewController:[self visibleViewController] 
                                  toViewController:viewController 
                                          duration:[MPFoldTransition defaultDuration]  
                                             style:style 
                                        completion:^(BOOL finished) {
                                            [self pushViewController:viewController animated:NO];
                                        }
     ];
}

- (UIViewController *)popViewControllerWithFoldStyle:(MPFoldStyle)style
{
    UIViewController *toController = [[self viewControllers] objectAtIndex:[[self viewControllers] count] - 2];

    [MPFoldTransition transitionFromViewController:[self visibleViewController] 
                                  toViewController:toController 
                                          duration:[MPFoldTransition defaultDuration] 
                                             style:style
                                        completion:^(BOOL finished) {
                                            [self popViewControllerAnimated:NO];
                                        }
     ];

    return toController;
}

moment.js, how to get day of week number

From the docs page, notice they have these helpful headers

http://momentjs.com/docs/#/get-set/weekday/
(I didn't see them at first)

With header sections for:

  • Date of Month
  • Day of Week
  • etc

.

  var now = moment();
  var day  = now.day();
  var date = now.date(); // Number

VBA - If a cell in column A is not blank the column B equals

Use the function IF :

=IF ( logical_test, value_if_true, value_if_false )

How to replace local branch with remote branch entirely in Git?

If you want to update branch that is not currently checked out you can do:

git fetch -f origin rbranch:lbranch

How merge two objects array in angularjs?

You can use angular.extend(dest, src1, src2,...);

In your case it would be :

angular.extend($scope.actions.data, data);

See documentation here :

https://docs.angularjs.org/api/ng/function/angular.extend

Otherwise, if you only get new values from the server, you can do the following

for (var i=0; i<data.length; i++){
    $scope.actions.data.push(data[i]);
}

What is "loose coupling?" Please provide examples

Loose coupling, in general, is 2 actors working independently of each other on the same workload. So if you had 2 web servers using the same back-end database, then you would say that those web servers are loosely coupled. Tight coupling would be exemplified by having 2 processors on one web server... those processors are tightly coupled.

Hope that's somewhat helpful.

Simulating ENTER keypress in bash script

You might find the yes command useful.

See man yes

Cannot enqueue Handshake after invoking quit

According to:

TL;DR You need to establish a new connection by calling the createConnection method after every disconnection.

and

Note: If you're serving web requests, then you shouldn't be ending connections on every request. Just create a connection on server startup and use the connection/client object to query all the time. You can listen on the error event to handle server disconnection and for reconnecting purposes. Full code here.


From:

It says:

Server disconnects

You may lose the connection to a MySQL server due to network problems, the server timing you out, or the server crashing. All of these events are considered fatal errors, and will have the err.code = 'PROTOCOL_CONNECTION_LOST'. See the Error Handling section for more information.

The best way to handle such unexpected disconnects is shown below:

function handleDisconnect(connection) {
  connection.on('error', function(err) {
    if (!err.fatal) {
      return;
    }

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
      throw err;
    }

    console.log('Re-connecting lost connection: ' + err.stack);

    connection = mysql.createConnection(connection.config);
    handleDisconnect(connection);
    connection.connect();
  });
}

handleDisconnect(connection);

As you can see in the example above, re-connecting a connection is done by establishing a new connection. Once terminated, an existing connection object cannot be re-connected by design.

With Pool, disconnected connections will be removed from the pool freeing up space for a new connection to be created on the next getConnection call.


I have tweaked the function such that every time a connection is needed, an initializer function adds the handlers automatically:

function initializeConnection(config) {
    function addDisconnectHandler(connection) {
        connection.on("error", function (error) {
            if (error instanceof Error) {
                if (error.code === "PROTOCOL_CONNECTION_LOST") {
                    console.error(error.stack);
                    console.log("Lost connection. Reconnecting...");

                    initializeConnection(connection.config);
                } else if (error.fatal) {
                    throw error;
                }
            }
        });
    }

    var connection = mysql.createConnection(config);

    // Add handlers.
    addDisconnectHandler(connection);

    connection.connect();
    return connection;
}

Initializing a connection:

var connection = initializeConnection({
    host: "localhost",
    user: "user",
    password: "password"
});

Minor suggestion: This may not apply to everyone but I did run into a minor issue relating to scope. If the OP feels this edit was unnecessary then he/she can choose to remove it. For me, I had to change a line in initializeConnection, which was var connection = mysql.createConnection(config); to simply just

connection = mysql.createConnection(config);

The reason being that if connection is a global variable in your program, then the issue before was that you were making a new connection variable when handling an error signal. But in my nodejs code, I kept using the same global connection variable to run queries on, so the new connection would be lost in the local scope of the initalizeConnection method. But in the modification, it ensures that the global connection variable is reset This may be relevant if you're experiencing an issue known as

Cannot enqueue Query after fatal error

after trying to perform a query after losing connection and then successfully reconnecting. This may have been a typo by the OP, but I just wanted to clarify.

Create a unique number with javascript time

Assumed that the solution proposed by @abarber it's a good solution because uses (new Date()).getTime() so it has a windows of milliseconds and sum a tick in case of collisions in this interval, we could consider to use built-in as we can clearly see here in action:

Fist we can see here how there can be collisions in the 1/1000 window frame using (new Date()).getTime():

console.log( (new Date()).getTime() ); console.log( (new Date()).getTime() )
VM1155:1 1469615396590
VM1155:1 1469615396591
console.log( (new Date()).getTime() ); console.log( (new Date()).getTime() )
VM1156:1 1469615398845
VM1156:1 1469615398846
console.log( (new Date()).getTime() ); console.log( (new Date()).getTime() )
VM1158:1 1469615403045
VM1158:1 1469615403045

Second we try the proposed solution that avoid collisions in the 1/1000 window:

console.log( window.mwUnique.getUniqueID() ); console.log( window.mwUnique.getUniqueID() ); 
VM1159:1 14696154132130
VM1159:1 14696154132131

That said we could consider to use functions like the node process.nextTick that is called in the event loop as a single tick and it's well explained here. Of course in the browser there is no process.nextTick so we have to figure how how to do that. This implementation will install a nextTick function in the browser using the most closer functions to the I/O in the browser that are setTimeout(fnc,0), setImmediate(fnc), window.requestAnimationFrame. As suggested here we could add the window.postMessage, but I leave this to the reader since it needs a addEventListener as well. I have modified the original module versions to keep it simpler here:

getUniqueID = (c => {
 if(typeof(nextTick)=='undefined')
nextTick = (function(window, prefixes, i, p, fnc) {
    while (!fnc && i < prefixes.length) {
        fnc = window[prefixes[i++] + 'equestAnimationFrame'];
    }
    return (fnc && fnc.bind(window)) || window.setImmediate || function(fnc) {window.setTimeout(fnc, 0);};
})(window, 'r webkitR mozR msR oR'.split(' '), 0);
 nextTick(() => {
   return c( (new Date()).getTime() )  
 })
})

So we have in the 1/1000 window:

getUniqueID(function(c) { console.log(c); });getUniqueID(function(c) { console.log(c); });
undefined
VM1160:1 1469615416965
VM1160:1 1469615416966

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You don't always want your instance variables to be fully accessible from outside of the class. There are plenty of cases where allowing read access to an instance variable makes sense, but writing to it might not (e.g. a model that retrieves data from a read-only source). There are cases where you want the opposite, but I can't think of any that aren't contrived off the top of my head.

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

What are you expecting? The default Tomcat homepage? If so, you'll need to configure Eclipse to take control over from Tomcat.

Doubleclick the Tomcat server entry in the Servers tab, you'll get the server configuration. At the left column, under Server Locations, select Use Tomcat installation (note, when it is grayed out, read the section leading text! ;) ). This way Eclipse will take full control over Tomcat, this way you'll also be able to access the default Tomcat homepage with the Tomcat Manager when running from inside Eclipse. I only don't see how that's useful while developing using Eclipse.

enter image description here

The port number is not the problem. You would otherwise have gotten an exception in Tomcat's startup log, and the browser would show a browser-specific "Connection timed out" error page and thus not a Tomcat-specific error page which could impossibly be served when Tomcat was not up and running.

CGContextDrawImage draws image upside down when passed UIImage.CGImage

Instead of

CGContextDrawImage(context, CGRectMake(0, 0, 145, 15), image.CGImage);

Use

[image drawInRect:CGRectMake(0, 0, 145, 15)];

In the middle of your begin/end CGcontext methods.

This will draw the image with the correct orientation into your current image context - I'm pretty sure this has something to do with the UIImage holding onto knowledge of the orientation while the CGContextDrawImage method gets the underlying raw image data with no understanding of orientation.

Random alpha-numeric string in JavaScript?

Random character:

String.fromCharCode(i); //where is an int

Random int:

Math.floor(Math.random()*100);

Put it all together:

function randomNum(hi){
    return Math.floor(Math.random()*hi);
} 
function randomChar(){
    return String.fromCharCode(randomNum(100));
}
function randomString(length){
   var str = "";
   for(var i = 0; i < length; ++i){
        str += randomChar();
   }
   return str;
}
var RandomString = randomString(32); //32 length string

Fiddle: http://jsfiddle.net/maniator/QZ9J2/

What is the difference between new/delete and malloc/free?

The most relevant difference is that the new operator allocates memory then calls the constructor, and delete calls the destructor then deallocates the memory.

Tomcat view catalina.out log file

locate catalina.out and find out where is your catalina out. Because it depends.

If there is several, look at their sizes: that with size 0 are not what you want.

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Render is

def render(request, *args, **kwargs):
    """ Simple wrapper for render_to_response. """
    kwargs['context_instance'] = RequestContext(request)
    return render_to_response(*args, **kwargs)

So there is really no difference between render_to_response except it wraps your context making the template pre-processors work.

Direct to template is a generic view.

There is really no sense in using it here because there is overhead over render_to_response in the form of view function.

Receive result from DialogFragment

Use myDialogFragment.setTargetFragment(this, MY_REQUEST_CODE) from the place where you show the dialog, and then when your dialog is finished, from it you can call getTargetFragment().onActivityResult(getTargetRequestCode(), ...), and implement onActivityResult() in the containing fragment.

It seems like an abuse of onActivityResult(), especially as it doesn't involve activities at all. But I've seen it recommended by official google people, and maybe even in the api demos. I think it's what g/setTargetFragment() were added for.

Updating a JSON object using Javascript

    var jsonObj = [{'Id':'1','Quantity':'2','Done':'0','state':'todo',
        'product_id':[315,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
        'Username':'Ray','FatherName':'Thompson'},  
          {'Id':'2','Quantity':'2','Done':'0','state':'todo',
          'product_id':[314,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
          'Username':'Steve','FatherName':'Johnson'},
          {'Id':'3','Quantity':'2','Done':'0','state':'todo',
          'product_id':[316,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
          'Username':'Albert','FatherName':'Einstein'}];

          for (var i = 0; i < jsonObj.length; ++i) {
            if (jsonObj[i]['product_id'][0] === 314) {


                this.onemorecartonsamenumber();


                jsonObj[i]['Done'] = ""+this.quantity_done+"";

                if(jsonObj[i]['Quantity'] === jsonObj[i]['Done']){
                  console.log('both are equal');
                  jsonObj[i]['state'] = 'packed';
                }else{
                  console.log('not equal');
                  jsonObj[i]['state'] = 'todo';
                }

                console.log('quantiy',jsonObj[i]['Quantity']);
                console.log('done',jsonObj[i]['Done']);


            }
        }

        console.log('final',jsonObj);
}

quantity_done: any = 0;

  onemorecartonsamenumber() {
    this.quantity_done += 1;
    console.log(this.quantity_done + 1);
  }

How to use 'find' to search for files created on a specific date?

With the -atime, -ctime, and -mtime switches to find, you can get close to what you want to achieve.

Creating csv file with php

Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows

I know I have added a lot of comments just for newbies :)

I have added an example so that you can summarize well.

$activeUsers = /** Query to get the active users */

/** Following is the Variable to store the Users data as 
    CSV string with newline character delimiter, 

    its good idea of check the delimiter based on operating system */

$userCSVData = "Name,Email,CreatedAt\n";

/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
    $userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file  */
$todayDate  = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName   = 'Active Users '.$todayDate.'.csv';
$filePath   = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file

/** Just in case if I run the script multiple time 
    I want to remove the old file and add new file.

    And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
    unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);

/** Now you can send email with attachments from the $filePath */

NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.

You have to add the following at the start of the above script.

ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

if you are using laravel then use this ways

public function getClientsListApi(Request $request){ print_r($request->all()); //for all request print_r($request->name); //for all name }

instead of

public function getClientsListApi(Request $request){ print_r($request); // it show error as above mention }

How can I shrink the drawable on a button?

You can use different sized drawables that are used with different screen densities/sizes, etc. so that your image looks right on all devices.

See here: http://developer.android.com/guide/practices/screens_support.html#support

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

Gustavomcls's solution to change com.google.* version to same version worked for me .

I change both dependancies to 9.2.1 in buid.gradle (Module:app)

compile 'com.google.firebase:firebase-ads:9.2.1'
compile 'com.google.android.gms:play-services:9.2.1'

SQL Server convert select a column and convert it to a string

You can do it like this:

Fiddle demo

declare @results varchar(500)

select @results = coalesce(@results + ',', '') +  convert(varchar(12),col)
from t
order by col

select @results as results

| RESULTS |
-----------
| 1,3,5,9 |

Python Pandas - Find difference between two data frames

Finding difference by index. Assuming df1 is a subset of df2 and the indexes are carried forward when subsetting

df1.loc[set(df1.index).symmetric_difference(set(df2.index))].dropna()

# Example

df1 = pd.DataFrame({"gender":np.random.choice(['m','f'],size=5), "subject":np.random.choice(["bio","phy","chem"],size=5)}, index = [1,2,3,4,5])

df2 =  df1.loc[[1,3,5]]

df1

 gender subject
1      f     bio
2      m    chem
3      f     phy
4      m     bio
5      f     bio

df2

  gender subject
1      f     bio
3      f     phy
5      f     bio

df3 = df1.loc[set(df1.index).symmetric_difference(set(df2.index))].dropna()

df3

  gender subject
2      m    chem
4      m     bio

SQL "between" not inclusive

cast(created_at as date)

That will work only in 2008 and newer versions of SQL Server

If you are using older version then use

convert(varchar, created_at, 101)

What causes a TCP/IP reset (RST) flag to be sent?

Run a packet sniffer (e.g., Wireshark) also on the peer to see whether it's the peer who's sending the RST or someone in the middle.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

FormsModule should be added at imports array not declarations array.

  • imports array is for importing modules such as BrowserModule, FormsModule, HttpModule
  • declarations array is for your Components, Pipes, Directives

refer below change:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Set port for php artisan.php serve

as this example you can change ip and port this works with me

php artisan serve --host=0.0.0.0 --port=8000

How to put a Scanner input into an array... for example a couple of numbers

double [] avg = new double[5];
for(int i=0; i<5; i++)
   avg[i] = scan.nextDouble();

mysql select from n last rows

Might be a very late answer, but this is good and simple.

select * from table_name order by id desc limit 5

This query will return a set of last 5 values(last 5 rows) you 've inserted in your table

Sending email with PHP from an SMTP server

<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "[email protected]");

$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = [email protected]";

$headers = "From: [email protected]";

mail("[email protected]", "Testing", $message, $headers);
echo "Check your email now....&lt;BR/>";
?>

or, for more details, read on.

Using NotNull Annotation in method argument

@Nullable and @NotNull do nothing on their own. They are supposed to act as Documentation tools.

The @Nullable Annotation reminds you about the necessity to introduce an NPE check when:

  1. Calling methods that can return null.
  2. Dereferencing variables (fields, local variables, parameters) that can be null.

The @NotNull Annotation is, actually, an explicit contract declaring the following:

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters) cannot should not hold null value.

For example, instead of writing:

/**
 * @param aX should not be null
 */
public void setX(final Object aX ) {
    // some code
}

You can use:

public void setX(@NotNull final Object aX ) {
    // some code
}

Additionally, @NotNull is often checked by ConstraintValidators (eg. in spring and hibernate).

The @NotNull annotation doesn't do any validation on its own because the annotation definition does not provide any ConstraintValidator type reference.

For more info see:

  1. Bean validation
  2. NotNull.java
  3. Constraint.java
  4. ConstraintValidator.java

How to call a function from another controller in angularjs?

If you would like to execute the parent controller's parentmethod function inside a child controller, call it:

$scope.$parent.parentmethod();

You can try it over here

Serialize form data to JSON

Found one possible helper:

https://github.com/theironcook/Backbone.ModelBinder

and for people who don't want to get in contact with forms at all: https://github.com/powmedia/backbone-forms

I will take a closer look at the first link and than give some feedback :)

How can I limit possible inputs in a HTML5 "number" element?

As stated by others, min/max is not the same as maxlength because people could still enter a float that would be larger than the maximum string length that you intended. To truly emulate the maxlength attribute, you can do something like this in a pinch (this is equivalent to maxlength="16"):

<input type="number" oninput="if(value.length>16)value=value.slice(0,16)">

Select query with date condition

Be careful, you're unwittingly asking "where the date is greater than one divided by nine, divided by two thousand and eight".

Put # signs around the date, like this #1/09/2008#

Sorting arrays in NumPy by column

In case someone wants to make use of sorting at a critical part of their programs here's a performance comparison for the different proposals:

import numpy as np
table = np.random.rand(5000, 10)

%timeit table.view('f8,f8,f8,f8,f8,f8,f8,f8,f8,f8').sort(order=['f9'], axis=0)
1000 loops, best of 3: 1.88 ms per loop

%timeit table[table[:,9].argsort()]
10000 loops, best of 3: 180 µs per loop

import pandas as pd
df = pd.DataFrame(table)
%timeit df.sort_values(9, ascending=True)
1000 loops, best of 3: 400 µs per loop

So, it looks like indexing with argsort is the quickest method so far...

How to get JS variable to retain value after page refresh?

You can do that by storing cookies on client side.

Transparent CSS background color

now you can use rgba in CSS properties like this:

.class {
    background: rgba(0,0,0,0.5);
}

0.5 is the transparency, change the values according to your design.

Live demo http://jsfiddle.net/EeAaB/

more info http://css-tricks.com/rgba-browser-support/

Is there a destructor for Java?

The closest equivalent to a destructor in Java is the finalize() method. The big difference to a traditional destructor is that you can't be sure when it'll be called, since that's the responsibility of the garbage collector. I'd strongly recommend carefully reading up on this before using it, since your typical RAIA patterns for file handles and so on won't work reliably with finalize().

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Google Maps API OVER QUERY LIMIT per second limit

The geocoder has quota and rate limits. From experience, you can geocode ~10 locations without hitting the query limit (the actual number probably depends on server loading). The best solution is to delay when you get OVER_QUERY_LIMIT errors, then retry. See these similar posts:

Make an image width 100% of parent div, but not bigger than its own width

I was also having the same problem, but I set the height value in my CSS to auto and that fixed my problem. Also, don't forget to do the display property.

  #image {
      height: auto;
      width: auto;
      max-height: 550px;
      max-width: 1200px;
      margin-left: auto;
      margin-right: auto;
      display: block;
 }  

Change header text of columns in a GridView

You should do that in GridView's RowDataBound event which is triggered for every GridViewRow after it was databound.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[0].Text = "Date";
    }
}

or you can set AutogenerateColumns to false and add the columns declaratively on aspx:

<asp:gridview id="GridView1" 
  onrowdatabound="GridView1_RowDataBound"
  autogeneratecolumns="False"
  emptydatatext="No data available." 
   runat="server">
    <Columns>
         <asp:BoundField DataField="DateField" HeaderText="Date" 
            SortExpression="DateField" />
    </Columns>
</asp:gridview>

Check if an HTML input element is empty or has no value entered by user

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}

java.net.ConnectException :connection timed out: connect?

If you're pointing the config at a domain (eg fabrikam.com), do an NSLOOKUP to ensure all the responding IPs are valid, and can be connected to on port 389:

NSLOOKUP fabrikam.com

Test-NetConnection <IP returned from NSLOOKUP> -port 389

Please add a @Pipe/@Directive/@Component annotation. Error

You have a typo in the import in your LoginComponent's file

import { Component } from '@angular/Core';

It's lowercase c, not uppercase

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

JavaScript - Get Portion of URL Path

window.location.href.split('/');

Will give you an array containing all the URL parts, which you can access like a normal array.

Or an ever more elegant solution suggested by @Dylan, with only the path parts:

window.location.pathname.split('/');

SQL Query - Using Order By in UNION

Sometimes you need to have the ORDER BY in each of the sections that need to be combined with UNION.

In this case

SELECT * FROM 
(
  SELECT table1.field1 FROM table1 ORDER BY table1.field1
) DUMMY_ALIAS1

UNION ALL

SELECT * FROM
( 
  SELECT table2.field1 FROM table2 ORDER BY table2.field1
) DUMMY_ALIAS2

How can I print variable and string on same line in Python?

use String formatting

print("If there was a birth every 7 seconds, there would be: {} births".format(births))
 # Will replace "{}" with births

if you doing a toy project use:

print('If there was a birth every 7 seconds, there would be:' births'births) 

or

print('If there was a birth every 7 seconds, there would be: %d births' %(births))
# Will replace %d with births

Changing button text onclick

<!DOCTYPE html>
<html>
    <head>
      <title>events2</title>
    </head>
    <body>
      <script>
        function fun() {
          document.getElementById("but").value = "onclickIChange";
        } 
      </script>
      <form>
        <input type="button" value="Button" onclick="fun()" id="but" name="but">
    </form>
  </body>
</html>

Regex to get the words after matching string

This might work out for you depending on which language you are using:

(?<=Object Name:).*

It's a positive lookbehind assertion. More information could be found here.

It won't work with JavaScript though. In your comment I read that you're using it for logstash. If you are using GROK parsing for logstash then it would work. You can verify it yourself here:

https://grokdebug.herokuapp.com/

Enter image description here

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

How to ping multiple servers and return IP address and Hostnames using batch script?

I worked on the code given earlier by Eitan-T and reworked to output to CSV file. Found the results in earlier code weren't always giving correct values as well so i've improved it.

testservers.txt

SOMESERVER
DUDSERVER

results.csv

HOSTNAME    LONGNAME                    IPADDRESS   STATE 
SOMESERVER  SOMESERVER.DOMAIN.SUF       10.1.1.1    UP 
DUDSERVER   UNRESOLVED                  UNRESOLVED  DOWN 

pingtest.bat

 @echo off
    setlocal enabledelayedexpansion
    set OUTPUT_FILE=result.csv

    >nul copy nul %OUTPUT_FILE%
    echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
    for /f %%i in (testservers.txt) do (
        set SERVER_ADDRESS_I=UNRESOLVED
        set SERVER_ADDRESS_L=UNRESOLVED
        for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
        if %%x==Pinging set SERVER_ADDRESS_L=%%y
        if %%x==Pinging set SERVER_ADDRESS_I=%%z
            if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
        )
        echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
        echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
    )

Disable firefox same origin policy

I realized my older answer is downvoted because I didn't specify how to disable FF's same origin policy specifically. Here I will give a more detailed answer:

Warning: This requires a re-compilation of FF, and the newly compiled version of Firefox will not be able to enable SOP again.

Check out Mozilla's Firefox's source code, find nsScriptSecurityManager.cpp in the src directory. I will use the one listed here as example: http://mxr.mozilla.org/aviarybranch/source/caps/src/nsScriptSecurityManager.cpp

Go to the function implementation nsScriptSecurityManager::CheckSameOriginURI, which is line 568 as of date 03/02/2016.

Make that function always return NS_OK.

This will disable SOP for good.

The browser addon answer by @Giacomo should be useful for most people and I have accepted that answer, however, for my personal research needs (TL;won't explain here) it is not enough and I figure other researchers may need to do what I did here to fully kill SOP.

Search for string and get count in vi editor

:%s/string/string/g will give the answer.

How do I debug Windows services in Visual Studio?

Unfortunately, if you're trying to debug something at the very start of a Windows Service operation, "attaching" to the running process won't work. I tried using Debugger.Break() within the OnStart procecdure, but with a 64-bit, Visual Studio 2010 compiled application, the break command just throws an error like this:

System error 1067 has occurred.

At that point, you need to set up an "Image File Execution" option in your registry for your executable. It takes five minutes to set up, and it works very well. Here's a Microsoft article where the details are:

How to: Launch the Debugger Automatically

Is it possible to print a variable's type in standard C++?

Copying from this answer: https://stackoverflow.com/a/56766138/11502722

I was able to get this somewhat working for C++ static_assert(). The wrinkle here is that static_assert() only accepts string literals; constexpr string_view will not work. You will need to accept extra text around the typename, but it works:

template<typename T>
constexpr void assertIfTestFailed()
{
#ifdef __clang__
    static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(__GNUC__)
    static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(_MSC_VER)
    static_assert(testFn<T>(), "Test failed on this used type: " __FUNCSIG__);
#else
    static_assert(testFn<T>(), "Test failed on this used type (see surrounding logged error for details).");
#endif
    }
}

MSVC Output:

error C2338: Test failed on this used type: void __cdecl assertIfTestFailed<class BadType>(void)
... continued trace of where the erroring code came from ...

How do I programmatically change file permissions?

Apache ant chmod (not very elegant, adding it for completeness) credit shared with @msorsky

    Chmod chmod = new Chmod();
    chmod.setProject(new Project());
    FileSet mySet = new FileSet();
    mySet.setDir(new File("/my/path"));
    mySet.setIncludes("**");
    chmod.addFileset(mySet);
    chmod.setPerm("+w");
    chmod.setType(new FileDirBoth());
    chmod.execute();

Using UPDATE in stored procedure with optional parameters

Try this.

ALTER PROCEDURE [dbo].[sp_ClientNotes_update]
    @id uniqueidentifier,
    @ordering smallint = NULL,
    @title nvarchar(20) = NULL,
    @content text = NULL
AS
BEGIN
    SET NOCOUNT ON;
    UPDATE tbl_ClientNotes
    SET ordering=ISNULL(@ordering,ordering), 
        title=ISNULL(@title,title), 
        content=ISNULL(@content, content)
    WHERE id=@id
END

It might also be worth adding an extra part to the WHERE clause, if you use transactional replication then it will send another update to the subscriber if all are NULL, to prevent this.

WHERE id=@id AND (@ordering IS NOT NULL OR
                  @title IS NOT NULL OR
                  @content IS NOT NULL)

Getting checkbox values on submit

foreach is the best way to get array of values.

here the example code: html code:

<form action="send.php" method="post">
    Red<input type="checkbox" name="color[]" id="color" value="red">
    Green<input type="checkbox" name="color[]" id="color" value="green">
    Blue<input type="checkbox" name="color[]" id="color" value="blue">
    Cyan<input type="checkbox" name="color[]" id="color" value="cyan">
    Magenta<input type="checkbox" name="color[]" id="color" value="Magenta">
    Yellow<input type="checkbox" name="color[]" id="color" value="yellow">
    Black<input type="checkbox" name="color[]" id="color" value="black">
    <input type="submit" value="submit">
</form>

phpcode:

<?php

$name = $POST['color'];



foreach ($name as $color){ 
    echo $color."<br />";
}

?>

How can I remove all text after a character in bash?

$ echo 'hello:world:again' |sed 's/:.*//'
hello

Extracting an attribute value with beautifulsoup

You could try to use the new powerful package called requests_html:

from requests_html import HTMLSession
session = HTMLSession()

r = session.get("https://www.bbc.co.uk/news/technology-54448223")
date = r.html.find('time', first = True) # finding a "tag" called "time"
print(date)  # you will have: <Element 'time' datetime='2020-10-07T11:41:22.000Z'>
# To get the text inside the "datetime" attribute use:
print(date.attrs['datetime']) # you will get '2020-10-07T11:41:22.000Z'

SQL DELETE with JOIN another table for WHERE condition

How about:

DELETE guide_category  
  WHERE id_guide_category IN ( 

        SELECT id_guide_category 
          FROM guide_category AS gc
     LEFT JOIN guide AS g 
            ON g.id_guide = gc.id_guide
         WHERE g.title IS NULL

  )

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

JSONDecodeError: Expecting value: line 1 column 1

in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input

How to remove the first and the last character of a string

You can use substring method

s = s.substring(0, s.length - 1) //removes last character

another alternative is slice method

How to change the status bar color in Android?

Android 5.0 Lollipop introduced Material Design theme which automatically colors the status bar based on the colorPrimaryDark value of the theme.

This is supported on device pre-lollipop thanks to the library support-v7-appcompat starting from version 21. Blogpost about support appcompat v21 from Chris Banes

enter image description here

Read more about the Material Theme on the official Android Developers website

Dynamically update values of a chartjs chart

You just need to change the chartObject.data.datasets value and call update() like this:

chartObject.data.datasets = newData.datasets;
chartObject.data.labels = newData.labels;
chartObject.update();

MySQL compare DATE string with string from DATETIME field

SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29';

it helps , you can convert the values as DATE before comparing.

How is CountDownLatch used in Java Multithreading?

From oracle documentation about CountDownLatch:

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset.

A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes.

A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown().

A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

public void await()
           throws InterruptedException

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.

If the current count is zero then this method returns immediately.

public void countDown()

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

If the current count is greater than zero then it is decremented. If the new count is zero then all waiting threads are re-enabled for thread scheduling purposes.

Explanation of your example.

  1. You have set count as 3 for latch variable

    CountDownLatch latch = new CountDownLatch(3);
    
  2. You have passed this shared latch to Worker thread : Processor

  3. Three Runnable instances of Processor have been submitted to ExecutorService executor
  4. Main thread ( App ) is waiting for count to become zero with below statement

     latch.await();  
    
  5. Processor thread sleeps for 3 seconds and then it decrements count value with latch.countDown()
  6. First Process instance will change latch count as 2 after it's completion due to latch.countDown().

  7. Second Process instance will change latch count as 1 after it's completion due to latch.countDown().

  8. Third Process instance will change latch count as 0 after it's completion due to latch.countDown().

  9. Zero count on latch causes main thread App to come out from await

  10. App program prints this output now : Completed

Using subprocess to run Python script on Windows

It looks like windows tries to run the script using its own EXE framework rather than call it like

python /the/script.py

Try,

subprocess.Popen(["python", "/the/script.py"])

Edit: "python" would need to be on your path.

How to close <img> tag properly?

Actually, only the first one is valid in HTML5

<img src='stackoverflow.png'>  

Only the last two are valid in XHTML

<img src='stackoverflow.png'></img>  
<img src='stackoverflow.png' />

(Though not stricly required, an alt attribute _usually_ should also be included).

That said, your HTML5 page will probably display as intended because browsers will rewrite or interpret your html to what it thinks you meant. That may mean it turns a tag, for example, from
<div /> into <div></div>. Or maybe it just ignores the final slash on <img ... />.
see 2016: Serve HTML5 as XHTML 5.0 for legacy validation.
see: 2011 discussion and additional links here, though over time some bits may have changed

Partly this is because browsers try very hard to error correct. Also, because there has much confusion about self-closing tags, and void tags. Finally, The spec has changed, or hasn't always been clear, and browsers try to be backwards compatible.

So, while you can probably get away with any of the three options,
only the first adheres to the HTML5 standard, and is guaranteed to pass a HTML5 validator.

A sound strategy might be to:

  • Write new code without the closing slash.
  • When re-factoring code, update nearby image tags, as you run across them.
  • Not overly worry about tags in legacy files that you do not touch, unless a particular need arises.

Here is a list of tags that should not be closed in HTML5:

 <br>    <hr>    <input>       
 <img>  <link>   <source>  
 <col>  <area>   <base>
 <meta> <embed>  <param>  
<track>  <wbr>   <keygen> (HTML 5.2 Draft removed)

Defining a `required` field in Bootstrap

Update 2018

Since the original answer HTML5 validation is now supported in all modern browsers. Now the easiest way to make a field required is simply using the required attibute.

<input type="email" class="form-control" id="exampleInputEmail1" required>

or in compliant HTML5:

<input type="email" class="form-control" id="exampleInputEmail1" required="true">

Read more on Bootstrap 4 validation


In Bootstrap 3, you can apply a "validation state" class to the parent element: http://getbootstrap.com/css/#forms-control-validation

For example has-error will show a red border around the input. However, this will have no impact on the actual validation of the field. You'd need to add some additional client (javascript) or server logic to make the field required.

Demo: http://bootply.com/90564


Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

you can easily achieve this by implementing the viewForHeaderInSection method in the tableview delegate class. this method expects a UIView as return object (which is your header view). i have done this same thing in my code

How to get Real IP from Visitor?

If the Proxy is which you trust, you can try: (Assume the Proxy IP is 151.101.2.10)

<?php

$trustProxyIPs = ['151.101.2.10'];

$clientIP  = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : NULL;

if (in_array($clientIP, $trustProxyIPs)) {

    $headers = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR'];

    foreach ($headers as $key => $header) {

        if (isset($_SERVER[$header]) && filter_var($_SERVER[$header], FILTER_VALIDATE_IP)) {

            $clientIP = $_SERVER[$header];

            break;
        }
    }
}

echo $clientIP;

This will prevent forged forward header by direct requested clients, and get real IP via trusted Proxies.

CSS Box Shadow - Top and Bottom Only

I've played around with it and I think I have a solution. The following example shows how to set Box-Shadow so that it will only show a shadow for the inset top and bottom of an element.

Legend: insetOption leftPosition topPosition blurStrength spreadStrength color

Description
The key to accomplishing this is to set the blur value to <= the negative of the spread value (ex. inset 0px 5px -?px 5px #000; the blur value should be -5 and lower) and to also keep the blur value > 0 when subtracted from the primary positioning value (ex. using the example from above, the blur value should be -9 and up, thus giving us an optimal value for the the blur to be between -5 and -9).

Solution

.styleName {   
/* for IE 8 and lower */
background-color:#888; filter: progid:DXImageTransform.Microsoft.dropShadow(color=#FFFFCC, offX=0, offY=0, positive=true);  

/* for IE 9 */ 
box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for webkit browsers */ 
-webkit-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for firefox 3.6+ */
-moz-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7);   
}

SQL Insert Query Using C#

I assume you have a connection to your database and you can not do the insert parameters using c #.

You are not adding the parameters in your query. It should look like:

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");

command.ExecuteNonQuery();

Updated:

using(SqlConnection connection = new SqlConnection(_connectionString))
{
    String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

    using(SqlCommand command = new SqlCommand(query, connection))
    {
        command.Parameters.AddWithValue("@id", "abc");
        command.Parameters.AddWithValue("@username", "abc");
        command.Parameters.AddWithValue("@password", "abc");
        command.Parameters.AddWithValue("@email", "abc");

        connection.Open();
        int result = command.ExecuteNonQuery();

        // Check Error
        if(result < 0)
            Console.WriteLine("Error inserting data into Database!");
    }
}

Uses of Action delegate in C#

I used the action delegate like this in a project once:

private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() { 
            {typeof(TextBox), c => ((TextBox)c).Clear()},
            {typeof(CheckBox), c => ((CheckBox)c).Checked = false},
            {typeof(ListBox), c => ((ListBox)c).Items.Clear()},
            {typeof(RadioButton), c => ((RadioButton)c).Checked = false},
            {typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},
            {typeof(Panel), c => ((Panel)c).Controls.ClearControls()}
    };

which all it does is store a action(method call) against a type of control so that you can clear all the controls on a form back to there defaults.

How to store NULL values in datetime fields in MySQL?

For what it is worth: I was experiencing a similar issue trying to update a MySQL table via Perl. The update would fail when an empty string value (translated from a null value from a read from another platform) was passed to the date column ('dtcol' in the code sample below). I was finally successful getting the data updated by using an IF statement embedded in my update statement:

    ...
    my $stmnt='update tbl set colA=?,dtcol=if(?="",null,?) where colC=?';
    my $status=$dbh->do($stmt,undef,$iref[1],$iref[2],$iref[2],$ref[0]);
    ...

How ViewBag in ASP.NET MVC works

ViewBag is used to pass data from Controller Action to view to render the data that being passed. Now you can pass data using between Controller Action and View either by using ViewBag or ViewData. ViewBag: It is type of Dynamic object, that means you can add new fields to viewbag dynamically and access these fields in the View. You need to initialize the object of viewbag at the time of creating new fields.

e.g: 1. Creating ViewBag: ViewBag.FirstName="John";

  1. Accessing View: @ViewBag.FirstName.

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

In most cases, yes.

Depending on the state your repository was in when you ran the command, the effects of git reset --hard can range from trivial to undo, to basically impossible.

Below I have listed a range of different possible scenarios, and how you might recover from them.

All my changes were committed, but now the commits are gone!

This situation usually occurs when you run git reset with an argument, as in git reset --hard HEAD~. Don't worry, this is easy to recover from!

If you just ran git reset and haven't done anything else since, you can get back to where you were with this one-liner:

git reset --hard @{1}

This resets your current branch whatever state it was in before the last time it was modified (in your case, the most recent modification to the branch would be the hard reset you are trying to undo).

If, however, you have made other modifications to your branch since the reset, the one-liner above won't work. Instead, you should run git reflog <branchname> to see a list of all recent changes made to your branch (including resets). That list will look something like this:

7c169bd master@{0}: reset: moving to HEAD~
3ae5027 master@{1}: commit: Changed file2
7c169bd master@{2}: commit: Some change
5eb37ca master@{3}: commit (initial): Initial commit

Find the operation in this list that you want to "undo". In the example above, it would be the first line, the one that says "reset: moving to HEAD~". Then copy the representation of the commit before (below) that operation. In our case, that would be master@{1} (or 3ae5027, they both represent the same commit), and run git reset --hard <commit> to reset your current branch back to that commit.

I staged my changes with git add, but never committed. Now my changes are gone!

This is a bit trickier to recover from. git does have copies of the files you added, but since these copies were never tied to any particular commit you can't restore the changes all at once. Instead, you have to locate the individual files in git's database and restore them manually. You can do this using git fsck.

For details on this, see Undo git reset --hard with uncommitted files in the staging area.

I had changes to files in my working directory that I never staged with git add, and never committed. Now my changes are gone!

Uh oh. I hate to tell you this, but you're probably out of luck. git doesn't store changes that you don't add or commit to it, and according to the documentation for git reset:

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

It's possible that you might be able to recover your changes with some sort of disk recovery utility or a professional data recovery service, but at this point that's probably more trouble than it's worth.

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Make the id parameter be a nullable int:

public ActionResult Edit(int? id, User collection)

And then add the validation:

if (Id == null) ...

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

On the other hand, if you are only working on java source and are getting these errors from stuff you don't touch in a large project that is working, you can just turn off the validations in Eclipse. The settings are under Preferences->Web->JSP Files->Validation

How can I force users to access my page over HTTPS instead of HTTP?

Ok.. Now there is tons of stuff on this now but no one really completes the "Secure" question. For me it is rediculous to use something that is insecure.

Unless you use it as bait.

$_SERVER propagation can be changed at the will of someone who knows how.

Also as Sazzad Tushar Khan and the thebigjc stated you can also use httaccess to do this and there are a lot of answers here containing it.

Just add:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

to the end of what you have in your .httaccess and thats that.

Still we are not as secure as we possibly can be with these 2 tools.

The rest is simple. If there are missing attributes ie...

if(empty($_SERVER["HTTPS"])){ // SOMETHING IS FISHY
}

if(strstr($_SERVER['HTTP_HOST'],"mywebsite.com") === FALSE){// Something is FISHY
}


Also say you have updated your httaccess file and you check:

if($_SERVER["HTTPS"] !== "on"){// Something is fishy
}

There are a lot more variables you can check ie..

HOST_URI (If there are static atributes about it to check)

HTTP_USER_AGENT (Same session different values)

So all Im saying is dont just settle for one or the other when the answer lies in a combination.

For more httaccess rewriting info see the docs-> http://httpd.apache.org/docs/2.0/misc/rewriteguide.html

Some Stacks here -> Force SSL/https using .htaccess and mod_rewrite
and
Getting the full URL of the current page (PHP)
to name a couple.

How to insert text at beginning of a multi-line selection in vi/Vim

To insert "ABC" at the begining of each line:

1) Go to command mode

2) :% norm I ABC

How to check if all elements of a list matches a condition?

Another way to use itertools.ifilter. This checks truthiness and process (using lambda)

Sample-

for x in itertools.ifilter(lambda x: x[2] == 0, my_list):
    print x

AJAX POST and Plus Sign ( + ) -- How to Encode?

Use encodeURIComponent() in JS and in PHP you should receive the correct values.

Note: When you access $_GET, $_POST or $_REQUEST in PHP, you are retrieving values that have already been decoded.

Example:

In your JS:

// url encode your string
var string = encodeURIComponent('+'); // "%2B"
// send it to your server
window.location = 'http://example.com/?string='+string; // http://example.com/?string=%2B

On your server:

echo $_GET['string']; // "+"

It is only the raw HTTP request that contains the url encoded data.

For a GET request you can retrieve this from the URI. $_SERVER['REQUEST_URI'] or $_SERVER['QUERY_STRING']. For a urlencoded POST, file_get_contents('php://stdin')

NB:

decode() only works for single byte encoded characters. It will not work for the full UTF-8 range.

eg:

text = "\u0100"; // A
// incorrect
escape(text); // %u0100 
// correct
encodeURIComponent(text); // "%C4%80"

Note: "%C4%80" is equivalent to: escape('\xc4\x80')

Which is the byte sequence (\xc4\x80) that represents A in UTF-8. So if you use encodeURIComponent() your server side must know that it is receiving UTF-8. Otherwise PHP will mangle the encoding.

Oracle "(+)" Operator

The (+) operator indicates an outer join. This means that Oracle will still return records from the other side of the join even when there is no match. For example if a and b are emp and dept and you can have employees unassigned to a department then the following statement will return details of all employees whether or not they've been assigned to a department.

select * from emp, dept where emp.dept_id=dept.dept_id(+)

So in short, removing the (+) may make a significance difference but you might not notice for a while depending on your data!

How to call a JavaScript function from PHP?

As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.

All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.

Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.

So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".

There are many ways to do this, but here are a couple.

Using just PHP:

echo '<script type="text/javascript">',
     'jsfunction();',
     '</script>'
;

Escaping from php mode to direct output mode:

<?php
    // some php stuff
?>
<script type="text/javascript">
    jsFunction();
</script>

You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.

Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.

Here's an example of what I think you're doing with jQuery's AJAX

$.get(
    'wait.php',
    {},
    function(returnedData) {
        document.getElementById("txt").innerHTML = returnedData;

        //  Ok, here's where you can call another function
        someOtherFunctionYouWantToCall();

        // But unless you really need to, you don't have to
        // We're already in the middle of a function execution
        // right here, so you might as well put your code here
    },
    'text'
);

function someOtherFunctionYouWantToCall() {
    // stuff
}

Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.

$.get(
    'wait.php',
    {},
    function(returnedData) {
        // Assumes returnedData has a javascript function name
        window[returnedData]();
    },
    'text'
);

* Or JSON or XML etc.

Convert Java String to sql.Timestamp

If you get time as string in format such as 1441963946053 you simply could do something as following:

//String timestamp;
Long miliseconds = Long.valueOf(timestamp);
Timestamp ti = new Timestamp(miliseconds);

How to select clear table contents without destroying the table?

I reworked Doug Glancy's solution to avoid rows deletion, which can lead to #Ref issue in formulae.

Sub ListReset(lst As ListObject)
'clears a listObject while leaving row 1 empty, with formulae
    With lst
        If .ShowAutoFilter Then .AutoFilter.ShowAllData
        On Error Resume Next
        With .DataBodyRange
            .Offset(1).Rows.Clear
            .Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
        End With
        On Error GoTo 0
        .Resize .Range.Rows("1:2")
    End With
End Sub

Execute jQuery function after another function completes

You can use below code

$.when( Typer() ).done(function() {
       playBGM();
});

What is the best free SQL GUI for Linux for various DBMS systems

For Oracle, I highly recommend the free Oracle SQL Developer

http://www.oracle.com/technology/products/database/sql_developer/index.html

The doucmentation states it also works with non-oracle databases - i've never tried that feature myself, but I do know that it works really well with Oracle

Find length (size) of an array in jquery

       var mode = [];
                $("input[name='mode[]']:checked").each(function(i) {
                    mode.push($(this).val());
                })
 if(mode.length == 0)
                {
                   alert('Please select mode!')
                };

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Code I use myself:

std::string prefix = "-param=";
std::string argument = argv[1];
if(argument.substr(0, prefix.size()) == prefix) {
    std::string argumentValue = argument.substr(prefix.size());
}

PHPExcel set border and format for all sheets in spreadsheet

You can set a default style for the entire workbook (all worksheets):

$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getTop()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getBottom()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getLeft()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getRight()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

or

  $styleArray = array(
      'borders' => array(
          'allborders' => array(
              'style' => PHPExcel_Style_Border::BORDER_THIN
          )
      )
  );
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);

And this can be used for all style properties, not just borders.

But column autosizing is structural rather than stylistic, and has to be set for each column on each worksheet individually.

EDIT

Note that default workbook style only applies to Excel5 Writer

Android studio- "SDK tools directory is missing"

I also faced the same problem, problem with me was on my first run I wasn't connected to Internet properly. After connecting to internet it required some updates to download, and then it ran without any problem

How can I return the current action in an ASP.NET MVC view?

Use the ViewContext and look at the RouteData collection to extract both the controller and action elements. But I think setting some data variable that indicates the application context (e.g., "editmode" or "error") rather than controller/action reduces the coupling between your views and controllers.

ComboBox- SelectionChanged event has old value, not new value

You can check SelectedIndex or SelectedValue or SelectedItem property in the SelectionChanged event of the Combobox control.

Check if one date is between two dates

Try this

var gdate='01-05-2014';
        date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
        if(parseInt(date) < parseInt(Date.now()))
        {
            alert('small');
        }else{
            alert('big');
        }

Fiddle

ssh : Permission denied (publickey,gssapi-with-mic)

Maybe you should assign the public key to the authorized_keys, the simple way to do this is using ssh-copy-id -i your-pub-key-file user@dest.

Sort Go map values by keys

This provides you the code example on sorting map. Basically this is what they provide:

var keys []int
for k := range myMap {
    keys = append(keys, k)
}
sort.Ints(keys)

// Benchmark1-8      2863149           374 ns/op         152 B/op          5 allocs/op

and this is what I would suggest using instead:

keys := make([]int, 0, len(myMap))
for k := range myMap {
    keys = append(keys, k)
}
sort.Ints(keys)

// Benchmark2-8      5320446           230 ns/op          80 B/op          2 allocs/op

Full code can be found in this Go Playground.

Cut Java String at a number of character

Use substring and concatenate:

if(str.length() > 50)
    strOut = str.substring(0,7) + "...";

How do I run a file on localhost?

i am working in VScode currently. i was wanting to run my html page just to see all my main elements.

1) first, in vs, right click desired html file and choose "copy path". do not choose relative.

2) finally, paste html path in address bar (i used chrome) and hit enter. your html page should display. hope this helps someone out.

How to upgrade docker-compose to latest version

I was trying to install docker-compose on "Ubuntu 16.04.5 LTS" but after installing it like this:

sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

I was getting:

-bash: /usr/local/bin/docker-compose: Permission denied

and while I was using it with sudo I was getting:

sudo: docker-compose: command not found

So here's the steps that I took and solved my problem:

sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose

Why do people say that Ruby is slow?

The answer is simple: people say ruby is slow because it is slow based on measured comparisons to other languages. Bear in mind, though, "slow" is relative. Often, ruby and other "slow" languages are plenty fast enough.

View RDD contents in Python Spark?

If you want to see the contents of RDD then yes collect is one option, but it fetches all the data to driver so there can be a problem

<rdd.name>.take(<num of elements you want to fetch>)

Better if you want to see just a sample

Running foreach and trying to print, I dont recommend this because if you are running this on cluster then the print logs would be local to the executor and it would print for the data accessible to that executor. print statement is not changing the state hence it is not logically wrong. To get all the logs you will have to do something like

**Pseudocode**
collect
foreach print

But this may result in job failure as collecting all the data on driver may crash it. I would suggest using take command or if u want to analyze it then use sample collect on driver or write to file and then analyze it.

UnsatisfiedDependencyException: Error creating bean with name

Just add @Service annotation to top of the service class

How to completely uninstall python 2.7.13 on Ubuntu 16.04

caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed.

To completely uninstall Python2.x.x and everything depends on it. use this command:

sudo apt purge python2.x-minimal

As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed.

Thanks, I hope it will be helpful for you.

Serialize an object to XML

Extension class:

using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace MyProj.Extensions
{
    public static class XmlExtension
    {
        public static string Serialize<T>(this T value)
        {
            if (value == null) return string.Empty;

            var xmlSerializer = new XmlSerializer(typeof(T));

            using (var stringWriter = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(stringWriter,new XmlWriterSettings{Indent = true}))
                {
                    xmlSerializer.Serialize(xmlWriter, value);
                    return stringWriter.ToString();
                }    
            }
        }
    }
}

Usage:

Foo foo = new Foo{MyProperty="I have been serialized"};

string xml = foo.Serialize();

Just reference the namespace holding your extension method in the file you would like to use it in and it'll work (in my example it would be: using MyProj.Extensions;)

Note that if you want to make the extension method specific to only a particular class(eg., Foo), you can replace the T argument in the extension method, eg.

public static string Serialize(this Foo value){...}

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

Get the full URL in PHP

You can use http_build_url with no arguments to get the full URL of the current page:

$url = http_build_url();

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:

_x000D_
_x000D_
   _x000D_
var dateformat = /^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/;
_x000D_
_x000D_
_x000D_

Self-references in object literals / initializers

You could do it like this

var a, b
var foo = {
    a: a = 5,
    b: b = 6,
    c: a + b
}

That method has proven useful to me when I had to refer to the object that a function was originally declared on. The following is a minimal example of how I used it:

function createMyObject() {
    var count = 0, self
    return {
        a: self = {
            log: function() {
                console.log(count++)
                return self
            }
        }
    }
}

By defining self as the object that contains the print function you allow the function to refer to that object. This means you will not have to 'bind' the print function to an object if you need to pass it somewhere else.

If you would, instead, use this as illustrated below

function createMyObject() {
    var count = 0
    return {
        a: {
            log: function() {
                console.log(count++)
                return this
            }
        }
    }
}

Then the following code will log 0, 1, 2 and then give an error

var o = createMyObject()
var log = o.a.log
o.a.log().log() // this refers to the o.a object so the chaining works
log().log() // this refers to the window object so the chaining fails!

By using the self method you guarantee that print will always return the same object regardless of the context in which the function is ran. The code above will run just fine and log 0, 1, 2 and 3 when using the self version of createMyObject().

How different is Scrum practice from Agile Practice?

Scrum is a very specific set of practices. Agile describes a family of practices, everything from Extreme Programming to Scrum and almost anything else that uses short iterations can claim Agile. That may not have originally been the case when the term was coined, but it certainly is by now.

Stop and Start a service via batch or cmd file?

Using the return codes from net start and net stop seems like the best method to me. Try a look at this: Net Start return codes.

Trusting all certificates with okHttp

I made an extension function for Kotlin. Paste it where ever you like and import it while creating OkHttpClient.

fun OkHttpClient.Builder.ignoreAllSSLErrors(): OkHttpClient.Builder {
    val naiveTrustManager = object : X509TrustManager {
        override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
        override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
        override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
    }

    val insecureSocketFactory = SSLContext.getInstance("TLSv1.2").apply {
        val trustAllCerts = arrayOf<TrustManager>(naiveTrustManager)
        init(null, trustAllCerts, SecureRandom())
    }.socketFactory

    sslSocketFactory(insecureSocketFactory, naiveTrustManager)
    hostnameVerifier(HostnameVerifier { _, _ -> true })
    return this
}

use it like this:

val okHttpClient = OkHttpClient.Builder().apply {
    // ...
    if (BuildConfig.DEBUG) //if it is a debug build ignore ssl errors
        ignoreAllSSLErrors()
    //...
}.build()

Use xml.etree.ElementTree to print nicely formatted xml files

You can use the function toprettyxml() from xml.dom.minidom in order to do that:

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

The idea is to print your Element in a string, parse it using minidom and convert it again in XML using the toprettyxml function.

Source: http://pymotw.com/2/xml/etree/ElementTree/create.html

When to use NSInteger vs. int

OS X is "LP64". This means that:

int is always 32-bits.

long long is always 64-bits.

NSInteger and long are always pointer-sized. That means they're 32-bits on 32-bit systems, and 64 bits on 64-bit systems.

The reason NSInteger exists is because many legacy APIs incorrectly used int instead of long to hold pointer-sized variables, which meant that the APIs had to change from int to long in their 64-bit versions. In other words, an API would have different function signatures depending on whether you're compiling for 32-bit or 64-bit architectures. NSInteger intends to mask this problem with these legacy APIs.

In your new code, use int if you need a 32-bit variable, long long if you need a 64-bit integer, and long or NSInteger if you need a pointer-sized variable.

javaw.exe cannot find path

Make sure to download these from here:

enter image description here

Also create PATH enviroment variable on you computer like this (if it doesn't exist already):

  1. Right click on My Computer/Computer
  2. Properties
  3. Advanced system settings (or just Advanced)
  4. Enviroment variables
  5. If PATH variable doesn't exist among "User variables" click New (Variable name: PATH, Variable value : C:\Program Files\Java\jdk1.8.0\bin; <-- please check out the right version, this may differ as Oracle keeps updating Java). ; in the end enables assignment of multiple values to PATH variable.
  6. Click OK! Done

enter image description here

To be sure that everything works, open CMD Prompt and type: java -version to check for Java version and javac to be sure that compiler responds.

enter image description here

I hope this helps. Good luck!

Sending JSON object to Web API

var model = JSON.stringify({ 
    'ID': 0, 
    'ProductID': $('#ID').val(), 
    'PartNumber': $('#part-number').val(),
    'VendorID': $('#Vendors').val()
})

$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "/api/PartSourceAPI/",
    data: model,
    success: function (data) {
        alert('success');
    },
    error: function (error) {
        jsonValue = jQuery.parseJSON(error.responseText);
        jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
    }
});

var model = JSON.stringify({      'ID': 0,     ...': 5,      'PartNumber': 6,     'VendorID': 7 }) // output is "{"ID":0,"ProductID":5,"PartNumber":6,"VendorID":7}"

your data is something like this "{"model": "ID":0,"ProductID":6,"PartNumber":7,"VendorID":8}}" web api controller cannot bind it to Your model

How do you decompile a swf file

This can also be done freely online: http://www.showmycode.com/

EDIT A quick Google search turned up this list, which probably has all the tools you could possibly want (look at the comments as well): http://bruce-lab.blogspot.co.il/2010/08/freeswfdecompilers.html

How do I get the current date in Cocoa

// you can get current date/time with the following code:

    NSDate* date = [NSDate date];
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];
    formatter.timeZone = destinationTimeZone;
    [formatter setDateStyle:NSDateFormatterLongStyle];
    [formatter setDateFormat:@"MM/dd/yyyy hh:mma"];
    NSString* dateString = [formatter stringFromDate:date];

Sequel Pro Alternative for Windows

You can try DBVisualizer some features are not free, but you can get an evaluate license...

How to make child process die after parent exits?

Install a trap handler to catch SIGINT, which kills off your child process if it's still alive, though other posters are correct that it won't catch SIGKILL.

Open a .lockfile with exclusive access and have the child poll on it trying to open it - if the open succeeds, the child process should exit

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE.

By starting out with smallest set to Integer.MAX_VALUE and largest set to Integer.MIN_VALUE, they don't have to worry later about the special case where smallest and largest don't have a value yet. If the data I'm looking through has a 10 as the first value, then numbers[i]<smallest will be true (because 10 is < Integer.MAX_VALUE) and we'll update smallest to be 10. Similarly, numbers[i]>largest will be true because 10 is > Integer.MIN_VALUE and we'll update largest. And so on.

Of course, when doing this, you must ensure that you have at least one value in the data you're looking at. Otherwise, you end up with apocryphal numbers in smallest and largest.


Note the point Onome Sotu makes in the comments:

...if the first item in the array is larger than the rest, then the largest item will always be Integer.MIN_VALUE because of the else-if statement.

Which is true; here's a simpler example demonstrating the problem (live copy):

public class Example
{
    public static void main(String[] args) throws Exception {
        int[] values = {5, 1, 2};
        int smallest = Integer.MAX_VALUE;
        int largest  = Integer.MIN_VALUE;
        for (int value : values) {
            if (value < smallest) {
                smallest = value;
            } else if (value > largest) {
                largest = value;
            }
        }
        System.out.println(smallest + ", " + largest); // 1, 2 -- WRONG
    }
}

To fix it, either:

  1. Don't use else, or

  2. Start with smallest and largest equal to the first element, and then loop the remaining elements, keeping the else if.

Here's an example of that second one (live copy):

public class Example
{
    public static void main(String[] args) throws Exception {
        int[] values = {5, 1, 2};
        int smallest = values[0];
        int largest  = values[0];
        for (int n = 1; n < values.length; ++n) {
            int value = values[n];
            if (value < smallest) {
                smallest = value;
            } else if (value > largest) {
                largest = value;
            }
        }
        System.out.println(smallest + ", " + largest); // 1, 5
    }
}

How to read large text file on windows?

I hate to promote my own stuff (well, not really), but PowerPad can open very large files.

Otherwise, I'd recommend a hex editor.

Where am I? - Get country

Using GPS with latitude and longitude, we can get the Country code.

If we use telephony, it won't work if we are not using sim card and in locale, based on language, it show the country code in wrong way.

MainActivity.java:

    GPSTracker gpsTrack;
    public static double latitude = 0;
    public static double longitude = 0;

    gpsTrack = new GPSTracker(TabHomeActivity.this);

        if (gpsTrack.canGetLocation()) {
            latitude = gpsParty.getLatitude();
            longitude = gpsParty.getLongitude();

            Log.e("GPSLat", "" + latitude);
            Log.e("GPSLong", "" + longitude);

        } else {
            gpsTrack.showSettingsAlert();

            Log.e("ShowAlert", "ShowAlert");

        }

        countryCode = getAddress(TabHomeActivity.this, latitude, longitude);

        Log.e("countryCode", ""+countryCode);

   public String getAddress(Context ctx, double latitude, double longitude) {
    String region_code = null;
    try {
        Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);


            region_code = address.getCountryCode();


        }
    } catch (IOException e) {
        Log.e("tag", e.getMessage());
    }

    return region_code;
}

GPSTracker.java:

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }



    public void showSettingsAlert() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        mContext.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

Log:

E/countryCode: IN

Edit: Use Fused Location Provider to get latitude and longitude update for better result.

Get WooCommerce product categories from WordPress

Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:

$sub_cats = get_categories( $args2 );
    if($sub_cats) {
        foreach($sub_cats as $sub_category) {
            echo  $sub_category->name ;
        }

    }

with:

$sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                }
            }

or if you also wish a counter for each subcategory, replace with this:

$sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                    echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
                }
            }

Upload artifacts to Nexus, without Maven

You can also use the direct deploy method using curl. You don't need a pom for your file for it but it will not be generated as well so if you want one, you will have to upload it separately.

Here is the command:

version=1.2.3
artefact="myartefact"
repoId=yourrepository
groupId=org.myorg
REPO_URL=http://localhost:8081/nexus

curl -u nexususername:nexuspassword --upload-file filename.tgz $REPO_URL/content/repositories/$repoId/$groupId/$artefact/$version/$artefact-$version.tgz

PHP Echo a large block of text

Check out heredoc. Example:

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

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

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

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

$(document).ready equivalent without jQuery

Most minimal and 100% working

I have picked the answer from PlainJS and it's working fine for me. It extends DOMContentLoaded so that it can be accepted at all the browsers.


This function is the equivalent of jQuery's $(document).ready() method:

document.addEventListener('DOMContentLoaded', function(){
    // do something
});

However, in contrast to jQuery, this code will only run properly in modern browsers (IE > 8) and it won't in case the document is already rendered at the time this script gets inserted (e.g. via Ajax). Therefore, we need to extend this a little bit:

function run() {
    // do something
}

// in case the document is already rendered
if (document.readyState!='loading') run();
// modern browsers
else if (document.addEventListener) 
document.addEventListener('DOMContentLoaded', run);
// IE <= 8
else document.attachEvent('onreadystatechange', function(){
    if (document.readyState=='complete') run();
});

This covers basically all possibilities and is a viable replacement for the jQuery helper.

How do SO_REUSEADDR and SO_REUSEPORT differ?

Welcome to the wonderful world of portability... or rather the lack of it. Before we start analyzing these two options in detail and take a deeper look how different operating systems handle them, it should be noted that the BSD socket implementation is the mother of all socket implementations. Basically all other systems copied the BSD socket implementation at some point in time (or at least its interfaces) and then started evolving it on their own. Of course the BSD socket implementation was evolved as well at the same time and thus systems that copied it later got features that were lacking in systems that copied it earlier. Understanding the BSD socket implementation is the key to understanding all other socket implementations, so you should read about it even if you don't care to ever write code for a BSD system.

There are a couple of basics you should know before we look at these two options. A TCP/UDP connection is identified by a tuple of five values:

{<protocol>, <src addr>, <src port>, <dest addr>, <dest port>}

Any unique combination of these values identifies a connection. As a result, no two connections can have the same five values, otherwise the system would not be able to distinguish these connections any longer.

The protocol of a socket is set when a socket is created with the socket() function. The source address and port are set with the bind() function. The destination address and port are set with the connect() function. Since UDP is a connectionless protocol, UDP sockets can be used without connecting them. Yet it is allowed to connect them and in some cases very advantageous for your code and general application design. In connectionless mode, UDP sockets that were not explicitly bound when data is sent over them for the first time are usually automatically bound by the system, as an unbound UDP socket cannot receive any (reply) data. Same is true for an unbound TCP socket, it is automatically bound before it will be connected.

If you explicitly bind a socket, it is possible to bind it to port 0, which means "any port". Since a socket cannot really be bound to all existing ports, the system will have to choose a specific port itself in that case (usually from a predefined, OS specific range of source ports). A similar wildcard exists for the source address, which can be "any address" (0.0.0.0 in case of IPv4 and :: in case of IPv6). Unlike in case of ports, a socket can really be bound to "any address" which means "all source IP addresses of all local interfaces". If the socket is connected later on, the system has to choose a specific source IP address, since a socket cannot be connected and at the same time be bound to any local IP address. Depending on the destination address and the content of the routing table, the system will pick an appropriate source address and replace the "any" binding with a binding to the chosen source IP address.

By default, no two sockets can be bound to the same combination of source address and source port. As long as the source port is different, the source address is actually irrelevant. Binding socketA to ipA:portA and socketB to ipB:portB is always possible if ipA != ipB holds true, even when portA == portB. E.g. socketA belongs to a FTP server program and is bound to 192.168.0.1:21 and socketB belongs to another FTP server program and is bound to 10.0.0.1:21, both bindings will succeed. Keep in mind, though, that a socket may be locally bound to "any address". If a socket is bound to 0.0.0.0:21, it is bound to all existing local addresses at the same time and in that case no other socket can be bound to port 21, regardless which specific IP address it tries to bind to, as 0.0.0.0 conflicts with all existing local IP addresses.

Anything said so far is pretty much equal for all major operating system. Things start to get OS specific when address reuse comes into play. We start with BSD, since as I said above, it is the mother of all socket implementations.

BSD

SO_REUSEADDR

If SO_REUSEADDR is enabled on a socket prior to binding it, the socket can be successfully bound unless there is a conflict with another socket bound to exactly the same combination of source address and port. Now you may wonder how is that any different than before? The keyword is "exactly". SO_REUSEADDR mainly changes the way how wildcard addresses ("any IP address") are treated when searching for conflicts.

Without SO_REUSEADDR, binding socketA to 0.0.0.0:21 and then binding socketB to 192.168.0.1:21 will fail (with error EADDRINUSE), since 0.0.0.0 means "any local IP address", thus all local IP addresses are considered in use by this socket and this includes 192.168.0.1, too. With SO_REUSEADDR it will succeed, since 0.0.0.0 and 192.168.0.1 are not exactly the same address, one is a wildcard for all local addresses and the other one is a very specific local address. Note that the statement above is true regardless in which order socketA and socketB are bound; without SO_REUSEADDR it will always fail, with SO_REUSEADDR it will always succeed.

To give you a better overview, let's make a table here and list all possible combinations:

SO_REUSEADDR       socketA        socketB       Result
---------------------------------------------------------------------
  ON/OFF       192.168.0.1:21   192.168.0.1:21    Error (EADDRINUSE)
  ON/OFF       192.168.0.1:21      10.0.0.1:21    OK
  ON/OFF          10.0.0.1:21   192.168.0.1:21    OK
   OFF             0.0.0.0:21   192.168.1.0:21    Error (EADDRINUSE)
   OFF         192.168.1.0:21       0.0.0.0:21    Error (EADDRINUSE)
   ON              0.0.0.0:21   192.168.1.0:21    OK
   ON          192.168.1.0:21       0.0.0.0:21    OK
  ON/OFF           0.0.0.0:21       0.0.0.0:21    Error (EADDRINUSE)

The table above assumes that socketA has already been successfully bound to the address given for socketA, then socketB is created, either gets SO_REUSEADDR set or not, and finally is bound to the address given for socketB. Result is the result of the bind operation for socketB. If the first column says ON/OFF, the value of SO_REUSEADDR is irrelevant to the result.

Okay, SO_REUSEADDR has an effect on wildcard addresses, good to know. Yet that isn't it's only effect it has. There is another well known effect which is also the reason why most people use SO_REUSEADDR in server programs in the first place. For the other important use of this option we have to take a deeper look on how the TCP protocol works.

A socket has a send buffer and if a call to the send() function succeeds, it does not mean that the requested data has actually really been sent out, it only means the data has been added to the send buffer. For UDP sockets, the data is usually sent pretty soon, if not immediately, but for TCP sockets, there can be a relatively long delay between adding data to the send buffer and having the TCP implementation really send that data. As a result, when you close a TCP socket, there may still be pending data in the send buffer, which has not been sent yet but your code considers it as sent, since the send() call succeeded. If the TCP implementation was closing the socket immediately on your request, all of this data would be lost and your code wouldn't even know about that. TCP is said to be a reliable protocol and losing data just like that is not very reliable. That's why a socket that still has data to send will go into a state called TIME_WAIT when you close it. In that state it will wait until all pending data has been successfully sent or until a timeout is hit, in which case the socket is closed forcefully.

At most, the amount of time the kernel will wait before it closes the socket, regardless if it still has data in flight or not, is called the Linger Time. The Linger Time is globally configurable on most systems and by default rather long (two minutes is a common value you will find on many systems). It is also configurable per socket using the socket option SO_LINGER which can be used to make the timeout shorter or longer, and even to disable it completely. Disabling it completely is a very bad idea, though, since closing a TCP socket gracefully is a slightly complex process and involves sending forth and back a couple of packets (as well as resending those packets in case they got lost) and this whole close process is also limited by the Linger Time. If you disable lingering, your socket may not only lose data in flight, it is also always closed forcefully instead of gracefully, which is usually not recommended. The details about how a TCP connection is closed gracefully are beyond the scope of this answer, if you want to learn more about, I recommend you have a look at this page. And even if you disabled lingering with SO_LINGER, if your process dies without explicitly closing the socket, BSD (and possibly other systems) will linger nonetheless, ignoring what you have configured. This will happen for example if your code just calls exit() (pretty common for tiny, simple server programs) or the process is killed by a signal (which includes the possibility that it simply crashes because of an illegal memory access). So there is nothing you can do to make sure a socket will never linger under all circumstances.

The question is, how does the system treat a socket in state TIME_WAIT? If SO_REUSEADDR is not set, a socket in state TIME_WAIT is considered to still be bound to the source address and port and any attempt to bind a new socket to the same address and port will fail until the socket has really been closed, which may take as long as the configured Linger Time. So don't expect that you can rebind the source address of a socket immediately after closing it. In most cases this will fail. However, if SO_REUSEADDR is set for the socket you are trying to bind, another socket bound to the same address and port in state TIME_WAIT is simply ignored, after all its already "half dead", and your socket can bind to exactly the same address without any problem. In that case it plays no role that the other socket may have exactly the same address and port. Note that binding a socket to exactly the same address and port as a dying socket in TIME_WAIT state can have unexpected, and usually undesired, side effects in case the other socket is still "at work", but that is beyond the scope of this answer and fortunately those side effects are rather rare in practice.

There is one final thing you should know about SO_REUSEADDR. Everything written above will work as long as the socket you want to bind to has address reuse enabled. It is not necessary that the other socket, the one which is already bound or is in a TIME_WAIT state, also had this flag set when it was bound. The code that decides if the bind will succeed or fail only inspects the SO_REUSEADDR flag of the socket fed into the bind() call, for all other sockets inspected, this flag is not even looked at.

SO_REUSEPORT

SO_REUSEPORT is what most people would expect SO_REUSEADDR to be. Basically, SO_REUSEPORT allows you to bind an arbitrary number of sockets to exactly the same source address and port as long as all prior bound sockets also had SO_REUSEPORT set before they were bound. If the first socket that is bound to an address and port does not have SO_REUSEPORT set, no other socket can be bound to exactly the same address and port, regardless if this other socket has SO_REUSEPORT set or not, until the first socket releases its binding again. Unlike in case of SO_REUESADDR the code handling SO_REUSEPORT will not only verify that the currently bound socket has SO_REUSEPORT set but it will also verify that the socket with a conflicting address and port had SO_REUSEPORT set when it was bound.

SO_REUSEPORT does not imply SO_REUSEADDR. This means if a socket did not have SO_REUSEPORT set when it was bound and another socket has SO_REUSEPORT set when it is bound to exactly the same address and port, the bind fails, which is expected, but it also fails if the other socket is already dying and is in TIME_WAIT state. To be able to bind a socket to the same addresses and port as another socket in TIME_WAIT state requires either SO_REUSEADDR to be set on that socket or SO_REUSEPORT must have been set on both sockets prior to binding them. Of course it is allowed to set both, SO_REUSEPORT and SO_REUSEADDR, on a socket.

There is not much more to say about SO_REUSEPORT other than that it was added later than SO_REUSEADDR, that's why you will not find it in many socket implementations of other systems, which "forked" the BSD code before this option was added, and that there was no way to bind two sockets to exactly the same socket address in BSD prior to this option.

Connect() Returning EADDRINUSE?

Most people know that bind() may fail with the error EADDRINUSE, however, when you start playing around with address reuse, you may run into the strange situation that connect() fails with that error as well. How can this be? How can a remote address, after all that's what connect adds to a socket, be already in use? Connecting multiple sockets to exactly the same remote address has never been a problem before, so what's going wrong here?

As I said on the very top of my reply, a connection is defined by a tuple of five values, remember? And I also said, that these five values must be unique otherwise the system cannot distinguish two connections any longer, right? Well, with address reuse, you can bind two sockets of the same protocol to the same source address and port. That means three of those five values are already the same for these two sockets. If you now try to connect both of these sockets also to the same destination address and port, you would create two connected sockets, whose tuples are absolutely identical. This cannot work, at least not for TCP connections (UDP connections are no real connections anyway). If data arrived for either one of the two connections, the system could not tell which connection the data belongs to. At least the destination address or destination port must be different for either connection, so that the system has no problem to identify to which connection incoming data belongs to.

So if you bind two sockets of the same protocol to the same source address and port and try to connect them both to the same destination address and port, connect() will actually fail with the error EADDRINUSE for the second socket you try to connect, which means that a socket with an identical tuple of five values is already connected.

Multicast Addresses

Most people ignore the fact that multicast addresses exist, but they do exist. While unicast addresses are used for one-to-one communication, multicast addresses are used for one-to-many communication. Most people got aware of multicast addresses when they learned about IPv6 but multicast addresses also existed in IPv4, even though this feature was never widely used on the public Internet.

The meaning of SO_REUSEADDR changes for multicast addresses as it allows multiple sockets to be bound to exactly the same combination of source multicast address and port. In other words, for multicast addresses SO_REUSEADDR behaves exactly as SO_REUSEPORT for unicast addresses. Actually, the code treats SO_REUSEADDR and SO_REUSEPORT identically for multicast addresses, that means you could say that SO_REUSEADDR implies SO_REUSEPORT for all multicast addresses and the other way round.


FreeBSD/OpenBSD/NetBSD

All these are rather late forks of the original BSD code, that's why they all three offer the same options as BSD and they also behave the same way as in BSD.


macOS (MacOS X)

At its core, macOS is simply a BSD-style UNIX named "Darwin", based on a rather late fork of the BSD code (BSD 4.3), which was then later on even re-synchronized with the (at that time current) FreeBSD 5 code base for the Mac OS 10.3 release, so that Apple could gain full POSIX compliance (macOS is POSIX certified). Despite having a microkernel at its core ("Mach"), the rest of the kernel ("XNU") is basically just a BSD kernel, and that's why macOS offers the same options as BSD and they also behave the same way as in BSD.

iOS / watchOS / tvOS

iOS is just a macOS fork with a slightly modified and trimmed kernel, somewhat stripped down user space toolset and a slightly different default framework set. watchOS and tvOS are iOS forks, that are stripped down even further (especially watchOS). To my best knowledge they all behave exactly as macOS does.


Linux

Linux < 3.9

Prior to Linux 3.9, only the option SO_REUSEADDR existed. This option behaves generally the same as in BSD with two important exceptions:

  1. As long as a listening (server) TCP socket is bound to a specific port, the SO_REUSEADDR option is entirely ignored for all sockets targeting that port. Binding a second socket to the same port is only possible if it was also possible in BSD without having SO_REUSEADDR set. E.g. you cannot bind to a wildcard address and then to a more specific one or the other way round, both is possible in BSD if you set SO_REUSEADDR. What you can do is you can bind to the same port and two different non-wildcard addresses, as that's always allowed. In this aspect Linux is more restrictive than BSD.

  2. The second exception is that for client sockets, this option behaves exactly like SO_REUSEPORT in BSD, as long as both had this flag set before they were bound. The reason for allowing that was simply that it is important to be able to bind multiple sockets to exactly to the same UDP socket address for various protocols and as there used to be no SO_REUSEPORT prior to 3.9, the behavior of SO_REUSEADDR was altered accordingly to fill that gap. In that aspect Linux is less restrictive than BSD.

Linux >= 3.9

Linux 3.9 added the option SO_REUSEPORT to Linux as well. This option behaves exactly like the option in BSD and allows binding to exactly the same address and port number as long as all sockets have this option set prior to binding them.

Yet, there are still two differences to SO_REUSEPORT on other systems:

  1. To prevent "port hijacking", there is one special limitation: All sockets that want to share the same address and port combination must belong to processes that share the same effective user ID! So one user cannot "steal" ports of another user. This is some special magic to somewhat compensate for the missing SO_EXCLBIND/SO_EXCLUSIVEADDRUSE flags.

  2. Additionally the kernel performs some "special magic" for SO_REUSEPORT sockets that isn't found in other operating systems: For UDP sockets, it tries to distribute datagrams evenly, for TCP listening sockets, it tries to distribute incoming connect requests (those accepted by calling accept()) evenly across all the sockets that share the same address and port combination. Thus an application can easily open the same port in multiple child processes and then use SO_REUSEPORT to get a very inexpensive load balancing.


Android

Even though the whole Android system is somewhat different from most Linux distributions, at its core works a slightly modified Linux kernel, thus everything that applies to Linux should apply to Android as well.


Windows

Windows only knows the SO_REUSEADDR option, there is no SO_REUSEPORT. Setting SO_REUSEADDR on a socket in Windows behaves like setting SO_REUSEPORT and SO_REUSEADDR on a socket in BSD, with one exception:

Prior to Windows 2003, a socket with SO_REUSEADDR could always been bound to exactly the same source address and port as an already bound socket, even if the other socket did not have this option set when it was bound. This behavior allowed an application "to steal" the connected port of another application. Needless to say that this has major security implications!

Microsoft realized that and added another important socket option: SO_EXCLUSIVEADDRUSE. Setting SO_EXCLUSIVEADDRUSE on a socket makes sure that if the binding succeeds, the combination of source address and port is owned exclusively by this socket and no other socket can bind to them, not even if it has SO_REUSEADDR set.

This default behavior was changed first in Windows 2003, Microsoft calls that "Enhanced Socket Security" (funny name for a behavior that is default on all other major operating systems). For more details just visit this page. There are three tables: The first one shows the classic behavior (still in use when using compatibility modes!), the second one shows the behavior of Windows 2003 and up when the bind() calls are made by the same user, and the third one when the bind() calls are made by different users.


Solaris

Solaris is the successor of SunOS. SunOS was originally based on a fork of BSD, SunOS 5 and later was based on a fork of SVR4, however SVR4 is a merge of BSD, System V, and Xenix, so up to some degree Solaris is also a BSD fork, and a rather early one. As a result Solaris only knows SO_REUSEADDR, there is no SO_REUSEPORT. The SO_REUSEADDR behaves pretty much the same as it does in BSD. As far as I know there is no way to get the same behavior as SO_REUSEPORT in Solaris, that means it is not possible to bind two sockets to exactly the same address and port.

Similar to Windows, Solaris has an option to give a socket an exclusive binding. This option is named SO_EXCLBIND. If this option is set on a socket prior to binding it, setting SO_REUSEADDR on another socket has no effect if the two sockets are tested for an address conflict. E.g. if socketA is bound to a wildcard address and socketB has SO_REUSEADDR enabled and is bound to a non-wildcard address and the same port as socketA, this bind will normally succeed, unless socketA had SO_EXCLBIND enabled, in which case it will fail regardless the SO_REUSEADDR flag of socketB.


Other Systems

In case your system is not listed above, I wrote a little test program that you can use to find out how your system handles these two options. Also if you think my results are wrong, please first run that program before posting any comments and possibly making false claims.

All that the code requires to build is a bit POSIX API (for the network parts) and a C99 compiler (actually most non-C99 compiler will work as well as long as they offer inttypes.h and stdbool.h; e.g. gcc supported both long before offering full C99 support).

All that the program needs to run is that at least one interface in your system (other than the local interface) has an IP address assigned and that a default route is set which uses that interface. The program will gather that IP address and use it as the second "specific address".

It tests all possible combinations you can think of:

  • TCP and UDP protocol
  • Normal sockets, listen (server) sockets, multicast sockets
  • SO_REUSEADDR set on socket1, socket2, or both sockets
  • SO_REUSEPORT set on socket1, socket2, or both sockets
  • All address combinations you can make out of 0.0.0.0 (wildcard), 127.0.0.1 (specific address), and the second specific address found at your primary interface (for multicast it's just 224.1.2.3 in all tests)

and prints the results in a nice table. It will also work on systems that don't know SO_REUSEPORT, in which case this option is simply not tested.

What the program cannot easily test is how SO_REUSEADDR acts on sockets in TIME_WAIT state as it's very tricky to force and keep a socket in that state. Fortunately most operating systems seems to simply behave like BSD here and most of the time programmers can simply ignore the existence of that state.

Here's the code (I cannot include it here, answers have a size limit and the code would push this reply over the limit).

Custom events in jQuery?

I had a similar question, but was actually looking for a different answer; I'm looking to create a custom event. For example instead of always saying this:

$('#myInput').keydown(function(ev) {
    if (ev.which == 13) {
        ev.preventDefault();
        // Do some stuff that handles the enter key
    }
});

I want to abbreviate it to this:

$('#myInput').enterKey(function() {
    // Do some stuff that handles the enter key
});

trigger and bind don't tell the whole story - this is a JQuery plugin. http://docs.jquery.com/Plugins/Authoring

The "enterKey" function gets attached as a property to jQuery.fn - this is the code required:

(function($){
    $('body').on('keydown', 'input', function(ev) {
        if (ev.which == 13) {
            var enterEv = $.extend({}, ev, { type: 'enterKey' });
            return $(ev.target).trigger(enterEv);
        }
    });

    $.fn.enterKey = function(selector, data, fn) {
        return this.on('enterKey', selector, data, fn);
    };
})(jQuery);

http://jsfiddle.net/b9chris/CkvuJ/4/

A nicety of the above is you can handle keyboard input gracefully on link listeners like:

$('a.button').on('click enterKey', function(ev) {
    ev.preventDefault();
    ...
});

Edits: Updated to properly pass the right this context to the handler, and to return any return value back from the handler to jQuery (for example in case you were looking to cancel the event and bubbling). Updated to pass a proper jQuery event object to handlers, including key code and ability to cancel event.

Old jsfiddle: http://jsfiddle.net/b9chris/VwEb9/24/

Changing the git user inside Visual Studio Code

Generally VSCode uses the github credentials from system's credential manager, it doesn't store anywhere in the settings. As question says Changing the git user inside Visual Studio Code, is not inside rather outside.

Search for or Go to credential manager (Windows control panel) -> Windows Credentials -> Update the GitHub password from the list.

Writing a new line to file in PHP (line feed)

PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:

Using this will save you extra coding on cross platform developments.

IE.

$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);

If you looped through this twice you would see in 'somefile':

some data
some data

MySQL Workbench Dark Theme

Edit: Advise: This answer is old and a better solution can be found in this same page. This answer referred to MySQL Workbench 6.3 and is outdated. If you are using a new version (8.0 as today) look for @VSingh comment in this very page.


Original answer:

Just a copy of Gaston's answer, but with Monokai theme colors.

<!-- 
    dark-gray:         #282828;
    brown-gray:        #49483E;
    gray:              #888888;
    light-gray:        #CCCCCC;
    ghost-white:       #F8F8F0;
    light-ghost-white: #F8F8F2;
    yellow:            #E6DB74;
    blue:              #66D9EF;
    pink:              #F92672;
    purple:            #AE81FF;
    brown:             #75715E;
    orange:            #FD971F;
    light-orange:      #FFD569;
    green:             #A6E22E;
    sea-green:         #529B2F; 
-->
<style id="32" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- STYLE_DEFAULT       !BACKGROUND!   -->
<style id="33" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- STYLE_LINENUMBER                   -->
<style id= "0" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_DEFAULT                  -->
<style id= "1" fore-color="#999999" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_COMMENT                  -->
<style id= "2" fore-color="#999999" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_COMMENTLINE              -->
<style id= "3" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_VARIABLE                 -->
<style id= "4" fore-color="#66D9EF" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_SYSTEMVARIABLE           -->
<style id= "5" fore-color="#66D9EF" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE      -->
<style id= "6" fore-color="#AE81FF" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_NUMBER                   -->
<style id= "7" fore-color="#F92672" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_MAJORKEYWORD             -->
<style id= "8" fore-color="#F92672" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_KEYWORD                  -->
<style id= "9" fore-color="#9B859D" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_DATABASEOBJECT           -->
<style id="10" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_PROCEDUREKEYWORD         -->
<style id="11" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_STRING                   -->
<style id="12" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_SQSTRING                 -->
<style id="13" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_DQSTRING                 -->
<style id="14" fore-color="#F92672" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_OPERATOR                 -->
<style id="15" fore-color="#9B859D" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_FUNCTION                 -->
<style id="16" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_IDENTIFIER               -->
<style id="17" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_QUOTEDIDENTIFIER         -->
<style id="18" fore-color="#529B2F" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_USER1                    -->
<style id="19" fore-color="#529B2F" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_USER2                    -->
<style id="20" fore-color="#529B2F" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_USER3                    -->
<style id="21" fore-color="#66D9EF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_HIDDENCOMMAND            -->
<style id="22" fore-color="#909090" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_PLACEHOLDER              -->
<!-- All styles again in their variant in a hidden command -->
<style id="65" fore-color="#999999" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_COMMENT                  -->
<style id="66" fore-color="#999999" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_COMMENTLINE              -->
<style id="67" fore-color="#DDDDDD" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_VARIABLE                 -->
<style id="68" fore-color="#66D9EF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_SYSTEMVARIABLE           -->
<style id="69" fore-color="#66D9EF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE      -->
<style id="70" fore-color="#AE81FF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_NUMBER                   -->
<style id="71" fore-color="#F92672" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_MAJORKEYWORD             -->
<style id="72" fore-color="#F92672" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_KEYWORD                  -->
<style id="73" fore-color="#9B859D" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_DATABASEOBJECT           -->
<style id="74" fore-color="#DDDDDD" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_PROCEDUREKEYWORD         -->
<style id="75" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_STRING                   -->
<style id="76" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_SQSTRING                 -->
<style id="77" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_DQSTRING                 -->
<style id="78" fore-color="#F92672" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_OPERATOR                 -->
<style id="79" fore-color="#9B859D" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_FUNCTION                 -->
<style id="80" fore-color="#DDDDDD" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_IDENTIFIER               -->
<style id="81" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_QUOTEDIDENTIFIER         -->
<style id="82" fore-color="#529B2F" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_USER1                    -->
<style id="83" fore-color="#529B2F" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_USER2                    -->
<style id="84" fore-color="#529B2F" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_USER3                    -->
<style id="85" fore-color="#66D9EF" back-color="#888888" bold="No" />   <!-- SCE_MYSQL_HIDDENCOMMAND            -->
<style id="86" fore-color="#AAAAAA" back-color="#888888" bold="No" />   <!-- SCE_MYSQL_PLACEHOLDER              -->

WPF binding to Listbox selectedItem

First off, you need to implement INotifyPropertyChanged interface in your view model and raise the PropertyChanged event in the setter of the Rule property. Otherwise no control that binds to the SelectedRule property will "know" when it has been changed.

Then, your XAML

<TextBlock Text="{Binding Path=SelectedRule.Name}" />

is perfectly valid if this TextBlock is outside the ListBox's ItemTemplate and has the same DataContext as the ListBox.

Return value of x = os.system(..)

os.system('command') returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

Refer my answer for more detail in What is the return value of os.system() in Python?

Does Java have a path joining method?

One way is to get system properties that give you the path separator for the operating system, this tutorial explains how. You can then use a standard string join using the file.separator.

Get most recent row for given ID

SELECT * FROM (SELECT * FROM tb1 ORDER BY signin DESC) GROUP BY id;

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

To prevent this, make sure every BEGIN TRANSACTION has COMMIT

The following will say successful but will leave uncommitted transactions:

BEGIN TRANSACTION
BEGIN TRANSACTION
<SQL_CODE?
COMMIT

Closing query windows with uncommitted transactions will prompt you to commit your transactions. This will generally resolve the Error 1222 message.

javax.net.ssl.SSLException: Received fatal alert: protocol_version

On Java 1.8 default TLS protocol is v1.2. On Java 1.6 and 1.7 default is obsoleted TLS1.0. I get this error on Java 1.8, because url use old TLS1.0 (like Your - You see ClientHello, TLSv1). To resolve this error You need to use override defaults for Java 1.8.

System.setProperty("https.protocols", "TLSv1");

More info on the Oracle blog.

JOIN queries vs multiple queries

This is way too vague to give you an answer relevant to your specific case. It depends on a lot of things. Jeff Atwood (founder of this site) actually wrote about this. For the most part, though, if you have the right indexes and you properly do your JOINs it is usually going to be faster to do 1 trip than several.

RegEx for Javascript to allow only alphanumeric

If you wanted to return a replaced result, then this would work:

var a = 'Test123*** TEST';
var b = a.replace(/[^a-z0-9]/gi,'');
console.log(b);

This would return:

Test123TEST

Note that the gi is necessary because it means global (not just on the first match), and case-insensitive, which is why I have a-z instead of a-zA-Z. And the ^ inside the brackets means "anything not in these brackets".

WARNING: Alphanumeric is great if that's exactly what you want. But if you're using this in an international market on like a person's name or geographical area, then you need to account for unicode characters, which this won't do. For instance, if you have a name like "Âlvarö", it would make it "lvar".

How to change text color of simple list item

The simplest way to do this without needing to create anything extra would be to just modify the simple list TextView:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, strings) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setTextColor({YourColorHere});
                return textView;
            }
        };

How to initialize var?

A var cannot be set to null since it needs to be statically typed.

var foo = null;
// compiler goes: "Huh, what's that type of foo?"

However, you can use this construct to work around the issue:

var foo = (string)null;
// compiler goes: "Ah, it's a string. Nice."

I don't know for sure, but from what I heard you can also use dynamic instead of var. This does not require static typing.

dynamic foo = null;
foo = "hi";

Also, since it was not clear to me from the question if you meant the varkeyword or variables in general: Only references (to classes) and nullable types can be set to null. For instance, you can do this:

string s = null; // reference
SomeClass c = null; // reference
int? i = null; // nullable

But you cannot do this:

int i = null; // integers cannot contain null

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
       foreach($row['rooms'] as $k) {
             echo $k['boards']['board_id'];
             echo $k['boards']['price'];
       }
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

What is the difference between primary, unique and foreign key constraints, and indexes?

Primary Key: identify uniquely every row it can not be null. it can not be a duplicate.

Foreign Key: create relationship between two tables. can be null. can be a duplicate  

Python object deleting itself

Indeed, Python does garbage collection through reference counting. As soon as the last reference to an object falls out of scope, it is deleted. In your example:

a = A()
a.kill()

I don't believe there's any way for variable 'a' to implicitly set itself to None.

How to round an image with Glide library?

According to this answer, the easiest way in both languages is:

Kotlin:

Glide.with(context).load(uri).apply(RequestOptions().circleCrop()).into(imageView)

Java:

Glide.with(context).load(uri).apply(new RequestOptions().circleCrop()).into(imageView)

This works on Glide 4.X.X

How can I use UIColorFromRGB in Swift?

The simplest way to add color programmatically is by using ColorLiteral.

Just add the property ColorLiteral as shown in the example, Xcode will prompt you with a whole list of colors which you can choose. The advantage of doing so is lesser code, add HEX values or RGB. You will also get the recently used colors from the storyboard.

Example: self.view.backgroundColor = ColorLiteralenter image description here

When should you use constexpr capability in C++11?

It can enable some new optimisations. const traditionally is a hint for the type system, and cannot be used for optimisation (e.g. a const member function can const_cast and modify the object anyway, legally, so const cannot be trusted for optimisation).

constexpr means the expression really is constant, provided the inputs to the function are const. Consider:

class MyInterface {
public:
    int GetNumber() const = 0;
};

If this is exposed in some other module, the compiler can't trust that GetNumber() won't return different values each time it's called - even consecutively with no non-const calls in between - because const could have been cast away in the implementation. (Obviously any programmer who did this ought to be shot, but the language permits it, therefore the compiler must abide by the rules.)

Adding constexpr:

class MyInterface {
public:
    constexpr int GetNumber() const = 0;
};

The compiler can now apply an optimisation where the return value of GetNumber() is cached and eliminate additional calls to GetNumber(), because constexpr is a stronger guarantee that the return value won't change.

How to exit from the application and show the home screen?

System.exit(0);

Is probably what you are looking for. It will close the entire application and take you to the home Screen.

error: Unable to find vcvarsall.bat

Look in the setup.py file of the package you are trying to install. If it is an older package it may be importing distutils.core.setup() rather than setuptools.setup().

I ran in to this (in 2015) with a combination of these factors:

  1. The Microsoft Visual C++ Compiler for Python 2.7 from http://aka.ms/vcpython27

  2. An older package that uses distutils.core.setup()

  3. Trying to do python setup.py build rather than using pip.

If you use a recent version of pip, it will force (monkeypatch) the package to use setuptools, even if its setup.py calls for distutils. However, if you are not using pip, and instead are just doing python setup.py build, the build process will use distutils.core.setup(), which does not know about the compiler install location.


Solution

Step 1: Open the appropriate Visual C++ 2008 Command Prompt

Open the Start menu or Start screen, and search for "Visual C++ 2008 32-bit Command Prompt" (if your python is 32-bit) or "Visual C++ 2008 64-bit Command Prompt" (if your python is 64-bit). Run it. The command prompt should say Visual C++ 2008 ... in the title bar.

Step 2: Set environment variables

Set these environment variables in the command prompt you just opened.

SET DISTUTILS_USE_SDK=1
SET MSSdk=1

Reference http://bugs.python.org/issue23246

Step 3: Build and install

cd to the package you want to build, and run python setup.py build, then python setup.py install. If you want to install in to a virtualenv, activate it before you build.

Is this how you define a function in jQuery?

The following example show you how to define a function in jQuery. You will see a button “Click here”, when you click on it, we call our function “myFunction()”.

  $(document).ready(function(){
    $.myFunction = function(){ 
      alert('You have successfully defined the function!'); 
    }
    $(".btn").click(function(){
      $.myFunction();
    });
  });

You can see an example here: How to define a function in jQuery?

Force uninstall of Visual Studio

Microsoft now has this:

https://github.com/Microsoft/VisualStudioUninstaller/releases

I allowed a windows 10 update to go through that completely f****d VS2015 so I am trying this before having to resort to a rebuild. WT*. :-(

https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/3487794-create-a-remove-all-remnants-of-visual-studio-fro

Finding Variable Type in JavaScript

For builtin JS types you can use:

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
}

Here we use 'toString' method from 'Object' class which works different than the same method of another types.

Examples:

// Primitives
getTypeName(42);        // "Number"
getTypeName("hi");      // "String"
getTypeName(true);      // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null);      // "Null"
getTypeName(undefined); // "Undefined"

// Non-primitives
getTypeName({});            // "Object"
getTypeName([]);            // "Array"
getTypeName(new Date);      // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/);           // "RegExp"
getTypeName(new Error);     // "Error"

If you need a class name you can use:

instance.constructor.name

Examples:

({}).constructor.name       // "Object"
[].constructor.name         // "Array"
(new Date).constructor.name // "Date"

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"

But this feature was added in ES2015.

How do I bind to list of checkbox values with AngularJS?

Using this example of the @Umur Kontaci, I think in using to catch selected data throughout another object/array, like a edit page.

Catch options at the database

enter image description here

Toggle a some option

enter image description here

As example, all colors json in below:

{
    "colors": [
        {
            "id": 1,
            "title": "Preto - #000000"
        },
        {
            "id": 2,
            "title": "Azul - #005AB1"
        },
        {
            "id": 3,
            "title": "Azul Marinho - #001A66"
        },
        {
            "id": 4,
            "title": "Amarelo - #FFF100"
        },
        {
            "id": 5,
            "title": "Vermelho - #E92717"
        },
        {
            "id": 6,
            "title": "Verde - #008D2F"
        },
        {
            "id": 7,
            "title": "Cinza - #8A8A8A"
        },
        {
            "id": 8,
            "title": "Prata - #C8C9CF"
        },
        {
            "id": 9,
            "title": "Rosa - #EF586B"
        },
        {
            "id": 10,
            "title": "Nude - #E4CAA6"
        },
        {
            "id": 11,
            "title": "Laranja - #F68700"
        },
        {
            "id": 12,
            "title": "Branco - #FFFFFF"
        },
        {
            "id": 13,
            "title": "Marrom - #764715"
        },
        {
            "id": 14,
            "title": "Dourado - #D9A300"
        },
        {
            "id": 15,
            "title": "Bordo - #57001B"
        },
        {
            "id": 16,
            "title": "Roxo - #3A0858"
        },
        {
            "id": 18,
            "title": "Estampado "
        },
        {
            "id": 17,
            "title": "Bege - #E5CC9D"
        }
    ]
}

And 2 types of data object, array with one object and object containing two/more object data:

  • Two items selected catched at the database:

    [{"id":12,"title":"Branco - #FFFFFF"},{"id":16,"title":"Roxo - #3A0858"}]
    
  • One item selected catched at the database:

    {"id":12,"title":"Branco - #FFFFFF"}
    

And here, my javascript code:

/**
 * Add this code after catch data of database.
 */

vm.checkedColors = [];
var _colorObj = vm.formData.color_ids;
var _color_ids = [];

if (angular.isObject(_colorObj)) {
    // vm.checkedColors.push(_colorObj);
    _color_ids.push(_colorObj);
} else if (angular.isArray(_colorObj)) {
    angular.forEach(_colorObj, function (value, key) {
        // vm.checkedColors.push(key + ':' + value);
        _color_ids.push(key + ':' + value);
    });
}

angular.forEach(vm.productColors, function (object) {
    angular.forEach(_color_ids, function (color) {
        if (color.id === object.id) {
            vm.checkedColors.push(object);
        }
    });
});

/**
 * Add this code in your js function initialized in this HTML page
 */
vm.toggleColor = function (color) {
    console.log('toggleColor is: ', color);

    if (vm.checkedColors.indexOf(color) === -1) {
        vm.checkedColors.push(color);
    } else {
        vm.checkedColors.splice(vm.checkedColors.indexOf(color), 1);
    }
    vm.formData.color_ids = vm.checkedColors;
};

My Html code:

<div class="checkbox" ng-repeat="color in productColors">
    <label>
        <input type="checkbox"
               ng-checked="checkedColors.indexOf(color) != -1"
               ng-click="toggleColor(color)"/>
        <% color.title %>
    </label>
</div>

<p>checkedColors Output:</p>
<pre><% checkedColors %></pre>

[Edit] Refactored code below:

function makeCheckedOptions(objectOptions, optionObj) {
    var checkedOptions = [];
    var savedOptions = [];

    if (angular.isObject(optionObj)) {
        savedOptions.push(optionObj);
    } else if (angular.isArray(optionObj)) {
        angular.forEach(optionObj, function (value, key) {
            savedOptions.push(key + ':' + value);
        });
    }

    angular.forEach(objectOptions, function (object) {
        angular.forEach(savedOptions, function (color) {
            if (color.id === object.id) {
                checkedOptions.push(object);
            }
        });
    });

    return checkedOptions;
}

And call new method as below:

vm.checkedColors = makeCheckedOptions(productColors, vm.formData.color_ids);

That's it!

"Auth Failed" error with EGit and GitHub

For existing ssh keys, I think that it's a bug in Eclipse Juno 3.8.

What I did:

1) Load the existing key by going to: Window > Preferences > "Search ssh" > Key Management Tab > Load Existing Key > Select the private key which you already have

2) Save that key by clicking the button Save Private Key. Let's name it id_dsa_github

3) Now check if push and pull are working or not. It should be.

4) Now in the general tab, remove the private key id_dsa_github and add your previous private key by clicking the button Add private key

Now you are good to go. It's taking at least one time to do all the things from EGit to register, I guess.

Self Join to get employee manager name

   SELECT b.Emp_id, b.Emp_name,e.emp_id as managerID, e.emp_name as managerName
    FROM Employee b
    JOIN Employee e ON b.Emp_ID = e.emp_mgr_id

Try this, it's a JOIN on itself to get the manager :)

How to get Current Timestamp from Carbon in Laravel 5

It may be a little late, but you could use the helper function time() to get the current timestamp. I tried this function and it did the job, no need for classes :).

You can find this in the official documentation at https://laravel.com/docs/5.0/templates

Regards.

Google Maps API 3 - Custom marker color for default (dot) marker

Combine a symbol-based marker whose path draws the outline, with a '?' character for the center. You can substitute the dot with other text ('A', 'B', etc.) as desired.

This function returns options for a marker with the a given text (if any), text color, and fill color. It uses the text color for the outline.

function createSymbolMarkerOptions(text, textColor, fillColor) {
    return {
        icon: {
            path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
            fillColor: fillColor,
            fillOpacity: 1,
            strokeColor: textColor,
            strokeWeight: 1.8,
            labelOrigin: { x: 0, y: -30 }
        },
        label: {
            text: text || '?',
            color: textColor
        }
    };
}

Sending and receiving data over a network using TcpClient

First, I recommend that you use WCF, .NET Remoting, or some other higher-level communication abstraction. The learning curve for "simple" sockets is nearly as high as WCF, because there are so many non-obvious pitfalls when using TCP/IP directly.

If you decide to continue down the TCP/IP path, then review my .NET TCP/IP FAQ, particularly the sections on message framing and application protocol specifications.

Also, use asynchronous socket APIs. The synchronous APIs do not scale and in some error situations may cause deadlocks. The synchronous APIs make for pretty little example code, but real-world production-quality code uses the asynchronous APIs.

scp from remote host to local host

You need the ip of the other pc and do:

scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop

it will ask you for 'user's password on the other pc.

How to convert SecureString to System.String?

Use the System.Runtime.InteropServices.Marshal class:

String SecureStringToString(SecureString value) {
  IntPtr valuePtr = IntPtr.Zero;
  try {
    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
    return Marshal.PtrToStringUni(valuePtr);
  } finally {
    Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  }
}

If you want to avoid creating a managed string object, you can access the raw data using Marshal.ReadInt16(IntPtr, Int32):

void HandleSecureString(SecureString value) {
  IntPtr valuePtr = IntPtr.Zero;
  try {
    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
    for (int i=0; i < value.Length; i++) {
      short unicodeChar = Marshal.ReadInt16(valuePtr, i*2);
      // handle unicodeChar
    }
  } finally {
    Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  }
}