Programs & Examples On #Geektool

GeekTool is an application for Mac OS 10.6+. It lets you display various kinds of information on your desktop via 3 default plug-ins:

Better way to revert to a previous SVN revision of a file?

If you use the Eclipse IDE with the SVN plugin you can do as follows:

  1. Right-click the files that you want to revert (or the folder they were contained in, if you deleted them by mistake and you want to add them back)
  2. Select "Team > Switch"
  3. Choose the "Revision" radion button, and enter the revision number you'd like to revert to. Click OK
  4. Go to the Synchronize perspective
  5. Select all the files you want to revert
  6. Right-click on the selection and do "Override and Commit..."

This will revert the files to the revision that you want. Just keep in mind that SVN will see the changes as a new commit. That is, the change gets a new revision number, and there is no link between the old revision and the new one. You should specify in the commit comments that you are reverting those files to a specific revision.

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

This situation occurred to me when I uninstalled a method and tried to reinstall it. My very same interpreter, which worked before, suddenly stopped working. And this error occurred.

I tried restarting my PC, reinstalling Pycharm, invalidating caches, nothing worked.

Then I went here to reinstall the interpreter: https://www.python.org/downloads/

When you install it, there's an option to fix the python.exe interpreter. Click that. My IDE went back to normal working conditions.

How to deploy a war file in Tomcat 7

Manual steps - Windows

  1. Copy the .war file (E.g.: prj.war) to %CATALINA_HOME%\webapps ( E.g.: C:\tomcat\webapps )

  2. Run %CATALINA_HOME%\bin\startup.bat

  3. Your .war file will be extracted automatically to a folder that has the same name (without extension) (E.g.: prj)

  4. Go to %CATALINA_HOME%\conf\server.xml and take the port for the HTTP protocol. <Connector port="8080" ... />. The default value is 8080.

  5. Access the following URL:

    [<protocol>://]localhost:<port>/folder/resourceName

    (E.g.: localhost:8080/folder/resourceName)

Don't try to access the URL without the resourceName because it won't work if there is no file like index.html, or if there is no url pattern like "/" or "/*" in web.xml.

The available main paths are here: [<protocol>://]localhost:<port>/manager/html (E.g.: http://localhost:8080/manager/html) and they have true on the "Running" column.


Using the UI manager:

  1. Go to [<protocol>://]localhost:<port>/manager/html/ (usually localhost:8080/manager/html/)

    This is also achievable from [<protocol>://]localhost:<port> > Manager App)

    If you get:

    403 Access Denied

    go to %CATALINA_HOME%\conf\tomcat-users.xml and check that you have enabled a line like this:

    <user username="tomcat" password="tomcat" roles="tomcat,role1,manager-gui"/>
    
  2. In the Deploy section, WAR file to deploy subsection, click on Browse....

    Deploy browse

  3. Select the .war file (E.g.: prj.war) > click on Deploy.

  4. In the Applications section, you can see the name of your project (E.g.: prj).

Looking to understand the iOS UIViewController lifecycle

All these commands are called automatically at the appropriate times by iOS when you load/present/hide the view controller. It's important to note that these methods are attached to UIViewController and not to UIViews themselves. You won't get any of these features just using a UIView.

There's great documentation on Apple's site here. Putting in simply though:

  • ViewDidLoad - Called when you create the class and load from xib. Great for initial setup and one-time-only work.

  • ViewWillAppear - Called right before your view appears, good for hiding/showing fields or any operations that you want to happen every time before the view is visible. Because you might be going back and forth between views, this will be called every time your view is about to appear on the screen.

  • ViewDidAppear - Called after the view appears - great place to start an animations or the loading of external data from an API.

  • ViewWillDisappear/DidDisappear - Same idea as ViewWillAppear/ViewDidAppear.

  • ViewDidUnload/ViewDidDispose - In Objective-C, this is where you do your clean-up and release of stuff, but this is handled automatically so not much you really need to do here.

RabbitMQ / AMQP: single queue, multiple consumers for same message?

As I assess your case is:

  • I have a queue of messages (your source for receiving messages, lets name it q111)

  • I have multiple consumers, which I would like to do different things with the same message.

Your problem here is while 3 messages are received by this queue, message 1 is consumed by a consumer A, other consumers B and C consumes message 2 and 3. Where as you are in need of a setup where rabbitmq passes on the same copies of all these three messages(1,2,3) to all three connected consumers (A,B,C) simultaneously.

While many configurations can be made to achieve this, a simple way is to use the following two step concept:

  • Use a dynamic rabbitmq-shovel to pickup messages from the desired queue(q111) and publish to a fanout exchange (exchange exclusively created and dedicated for this purpose).
  • Now re-configure your consumers A,B & C (who were listening to queue(q111)) to listen from this Fanout exchange directly using a exclusive & anonymous queue for each consumer.

Note: While using this concept don't consume directly from the source queue(q111), as messages already consumed wont be shovelled to your Fanout exchange.

If you think this does not satisfies your exact requirement... feel free to post your suggestions :-)

Array.Add vs +=

When using the $array.Add()-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.

$array += $element creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array-variable

You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:

    $a += 200

Source: about_Arrays

+= is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:

$arr = 1..3    #Array
$arr += (4..5) #Combine with another array in a single write-operation

$arr.Count
5

If that's not possible, consider using a more efficient collection like List or ArrayList (see the other answer).

How to make an installer for my C# application?

  1. Add a new install project to your solution.
  2. Add targets from all projects you want to be installed.
  3. Configure pre-requirements and choose "Check for .NET 3.5 and SQL Express" option. Choose the location from where missing components must be installed.
  4. Configure your installer settings - company name, version, copyright, etc.
  5. Build and go!

Console app arguments, how arguments are passed to Main method

All answers are awesome and explained everything very well

but I just want to point out different way for passing args to main method

in visual studio

  1. right click on Project then choose Properties
  2. go to Debug tab then on the Start Options section provide the app with your args

like this image

Properties window

and happy knowing secrets

Make Frequency Histogram for Factor Variables

You could also use lattice::histogram()

bodyParser is deprecated express 4

If you're using express > 4.16, you can use express.json() and express.urlencoded()

The express.json() and express.urlencoded() middleware have been added to provide request body parsing support out-of-the-box. This uses the expressjs/body-parser module module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers.

Source Express 4.16.0 - Release date: 2017-09-28

With this,

const bodyParser  = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

becomes,

const express = require('express');

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

Get parent of current directory from Python script

import os def parent_directory(): # Create a relative path to the parent # of the current working directory path = os.getcwd() parent = os.path.dirname(path)

relative_parent = os.path.join(path, parent)

# Return the absolute path of the parent directory
return relative_parent

print(parent_directory())

Should I use != or <> for not equal in T-SQL?

I understand that the C syntax != is in SQL Server due to its Unix heritage (back in the Sybase SQL Server days, pre Microsoft SQL Server 6.5).

Is it possible to capture the stdout from the sh DSL command in the pipeline

I had the same issue and tried almost everything then found after I came to know I was trying it in the wrong block. I was trying it in steps block whereas it needs to be in the environment block.

        stage('Release') {
                    environment {
                            my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
                                }
                    steps {                                 
                            println my_var
                            }
                }

What is the difference between #include <filename> and #include "filename"?

"" will search ./ first. then search the default include path. you can use command like this to print the default include path:

 gcc -v -o a a.c

here are some examples to make thing more clear: the code a.c works

// a.c
#include "stdio.h"
int main() {
        int a = 3;
        printf("a = %d\n", a);
        return 0;

}

the code of b.c works too

\\ b.c
#include <stdio.h>
int main() {
        int a = 3;
        printf("a = %d\n", a);
        return 0;

}

but when I create a new file named stdio.h in current directory

// stdio.h
inline int foo()
{
        return 10;
}

a.c will generate compile error, but b.c still works

and "", <> can be used together with the same file name. since the search path priority is different. so d.c also works

// d.c
#include <stdio.h>
#include "stdio.h"
int main()
{
        int a = 0;

        a = foo();

        printf("a=%d\n", a);

        return 0;
}

~

Javascript: How to remove the last character from a div or a string?

Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup

$("#div").html($("#input").val());

How to edit default dark theme for Visual Studio Code?

Any color theme can be changed in this settings section on VS Code version 1.12 or higher:

 // Overrides colors from the currently selected color theme.
  "workbench.colorCustomizations": {}

See https://code.visualstudio.com/docs/getstarted/themes#_customize-a-color-theme

Available values to edit: https://code.visualstudio.com/docs/getstarted/theme-color-reference

EDIT: To change syntax colors, see here: https://code.visualstudio.com/docs/extensions/themes-snippets-colorizers#_syntax-highlighting-colors and here: https://www.sublimetext.com/docs/3/scope_naming.html

How to delete and recreate from scratch an existing EF Code First database

How about ..

static void Main(string[] args)
{
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ExampleContext>());  
    // C
    // o
    // d
    // i
    // n
    // g
}

I picked this up from Programming Entity Framework: Code First, Pg 28 First Edition.

How to combine 2 plots (ggplot) into one plot?

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +
      geom_smooth(size=1)

How to detect Ctrl+V, Ctrl+C using JavaScript?

I wrote a jQuery plugin, which catches keystrokes. It can be used to enable multiple language script input in html forms without the OS (except the fonts). Its about 300 lines of code, maybe you like to take a look:

Generally, be careful with such kind of alterations. I wrote the plugin for a client because other solutions weren't available.

How do I set a value in CKEditor with Javascript?

Sets the editor data. The data must be provided in the raw format (HTML). CKEDITOR.instances.editor1.setData( 'Put your Data.' ); refer this page

Entity Framework - Include Multiple Levels of Properties

The EFCore examples on MSDN show that you can do some quite complex things with Include and ThenInclude.

This is a good example of how complex you can get (this is all one chained statement!):

viewModel.Instructors = await _context.Instructors

      .Include(i => i.OfficeAssignment)

      .Include(i => i.CourseAssignments)
        .ThenInclude(i => i.Course)
            .ThenInclude(i => i.Enrollments)
                .ThenInclude(i => i.Student)

      .Include(i => i.CourseAssignments)
        .ThenInclude(i => i.Course)
            .ThenInclude(i => i.Department)

      .AsNoTracking()
      .OrderBy(i => i.LastName)
      .ToListAsync();

You can have multiple Include calls - even after ThenInclude and it kind of 'resets' you back to the level of the top level entity (Instructors).

You can even repeat the same 'first level' collection (CourseAssignments) multiple times followed by separate ThenIncludes commands to get to different child entities.

Note your actual query must be tagged onto the end of the Include or ThenIncludes chain. The following does NOT work:

var query = _context.Instructors.AsQueryable();
query.Include(i => i.OfficeAssignment);

var first10Instructors = query.Take(10).ToArray();

Would strongly recommend you set up logging and make sure your queries aren't out of control if you're including more than one or two things. It's important to see how it actually works - and you'll notice each separate 'include' is typically a new query to avoid massive joins returning redundant data.

AsNoTracking can greatly speed things up if you're not intending on actually editing the entities and resaving.


EFCore 5 made some changes to the way queries for multiple sets of entities are sent to the server. There are new options for Split Queries which can make certain queries of this type far more efficient with fewer joins, but make sure to understand the limitations.

CSS file not refreshing in browser

If you're using ASP.NET web forms, make sure that you are using the right theme:

enter image description here

I just spent about an hour trying to solve this!

Regular Expression to get a string between parentheses in Javascript

Simple: (?<value>(?<=\().*(?=\)))

I hope I've helped.

Which @NotNull Java annotation should I use?

According to the Java 7 features list JSR-308 type annotations are deferred to Java 8. JSR-305 annotations are not even mentioned.

There is a bit of info on the state of JSR-305 in an appendix of the latest JSR-308 draft. This includes the observation that JSR-305 annotations seem to be abandoned. The JSR-305 page also shows it as "inactive".

In the mean time, the pragmatic answer is to use the annotation types that are supported by the most widely used tools ... and be prepared to change them if the situation changes.


In fact, JSR-308 does not define any annotation types/classes, and it looks like they think it is out of scope. (And they are right, given the existence of JSR-305).

However, if JSR-308 really looks like making it into Java 8, it wouldn't surprise me if interest in JSR-305 revived. AFAIK, the JSR-305 team hasn't formally abandoned their work. They have just been quiet for 2+ years.

It is interesting that Bill Pugh (the tech lead for JSR-305) is one of the guy behind FindBugs.

How to run python script on terminal (ubuntu)?

First create the file you want, with any editor like vi r gedit. And save with. Py extension.In that the first line should be

!/usr/bin/env python

What does character set and collation mean exactly?

A character encoding is a way to encode characters so that they fit in memory. That is, if the charset is ISO-8859-15, the euro symbol, €, will be encoded as 0xa4, and in UTF-8, it will be 0xe282ac.

The collation is how to compare characters, in latin9, there are letters as e é è ê f, if sorted by their binary representation, it will go e f é ê è but if the collation is set to, for example, French, you'll have them in the order you thought they would be, which is all of e é è ê are equal, and then f.

javax.naming.NoInitialContextException - Java

If working on EJB client library:

You need to mention the argument for getting the initial context.

InitialContext ctx = new InitialContext();

If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");

InitialContext ctx = new InitialContext(props);

URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.

The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.

How to emit an event from parent to child?

Within the parent, you can reference the child using @ViewChild. When needed (i.e. when the event would be fired), you can just execute a method in the child from the parent using the @ViewChild reference.

Updating state on props change in React Form

// store the startTime prop in local state
const [startTime, setStartTime] = useState(props.startTime)
// 
useEffect(() => {
  if (props.startTime !== startTime) {
    setStartTime(props.startTime);
  }
}, [props.startTime]);

Can this method be migrated to class components?

Hibernate Error executing DDL via JDBC Statement

I have got this error when trying to create JPA entity with the name "User" (in Postgres) that is reserved. So the way it is resolved is to change the table name by @Table annotation:

@Entity
@Table(name="users")
public class User {..}

Or change the table name manually.

How to split a string into an array of characters in Python?

I explored another two ways to accomplish this task. It may be helpful for someone.

The first one is easy:

In [25]: a = []
In [26]: s = 'foobar'
In [27]: a += s
In [28]: a
Out[28]: ['f', 'o', 'o', 'b', 'a', 'r']

And the second one use map and lambda function. It may be appropriate for more complex tasks:

In [36]: s = 'foobar12'
In [37]: a = map(lambda c: c, s)
In [38]: a
Out[38]: ['f', 'o', 'o', 'b', 'a', 'r', '1', '2']

For example

# isdigit, isspace or another facilities such as regexp may be used
In [40]: a = map(lambda c: c if c.isalpha() else '', s)
In [41]: a
Out[41]: ['f', 'o', 'o', 'b', 'a', 'r', '', '']

See python docs for more methods

What is the difference between json.load() and json.loads() functions

In python3.7.7, the definition of json.load is as below according to cpython source code:

def load(fp, *, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):

    return loads(fp.read(),
        cls=cls, object_hook=object_hook,
        parse_float=parse_float, parse_int=parse_int,
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

json.load actually calls json.loads and use fp.read() as the first argument.

So if your code is:

with open (file) as fp:
    s = fp.read()
    json.loads(s)

It's the same to do this:

with open (file) as fp:
    json.load(fp)

But if you need to specify the bytes reading from the file as like fp.read(10) or the string/bytes you want to deserialize is not from file, you should use json.loads()

As for json.loads(), it not only deserialize string but also bytes. If s is bytes or bytearray, it will be decoded to string first. You can also find it in the source code.

def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
    containing a JSON document) to a Python object.

    ...

    """
    if isinstance(s, str):
        if s.startswith('\ufeff'):
            raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
                                  s, 0)
    else:
        if not isinstance(s, (bytes, bytearray)):
            raise TypeError(f'the JSON object must be str, bytes or bytearray, '
                            f'not {s.__class__.__name__}')
        s = s.decode(detect_encoding(s), 'surrogatepass')

NuGet: 'X' already has a dependency defined for 'Y'

In a project using vs 2010, I was only able to solve the problem by installing an older version of the package that I needed via Package Manager Console.

This command worked:

PM> Install-Package EPPlus -Version 4.5.3.1

This command did not work:

PM> Install-Package EPPlus -Version 4.5.3.2

bash, extract string before a colon

This has been asked so many times so that a user with over 1000 points ask for this is some strange
But just to show just another way to do it:

echo "/some/random/file.csv:some string" | awk '{sub(/:.*/,x)}1'
/some/random/file.csv

select2 changing items dynamically

Try using the trigger property for this:

$('select').select2().trigger('change');

What is the use of ObservableCollection in .net?

ObservableCollection is a collection that allows code outside the collection be aware of when changes to the collection (add, move, remove) occur. It is used heavily in WPF and Silverlight but its use is not limited to there. Code can add event handlers to see when the collection has changed and then react through the event handler to do some additional processing. This may be changing a UI or performing some other operation.

The code below doesn't really do anything but demonstrates how you'd attach a handler in a class and then use the event args to react in some way to the changes. WPF already has many operations like refreshing the UI built in so you get them for free when using ObservableCollections

class Handler
{
    private ObservableCollection<string> collection;

    public Handler()
    {
        collection = new ObservableCollection<string>();
        collection.CollectionChanged += HandleChange;
    }

    private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
    {
        foreach (var x in e.NewItems)
        {
            // do something
        }

        foreach (var y in e.OldItems)
        {
            //do something
        }
        if (e.Action == NotifyCollectionChangedAction.Move)
        {
            //do something
        }
    }
}

Rotating x axis labels in R for barplot

use optional parameter las=2 .

barplot(mytable,main="Car makes",ylab="Freqency",xlab="make",las=2)

enter image description here

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

How can I find out a file's MIME type (Content-Type)?

one of the other tool (besides file) you can use is xdg-mime

eg xdg-mime query filetype <file>

if you have yum,

yum install xdg-utils.noarch

An example comparison of xdg-mime and file on a Subrip(subtitles) file

$ xdg-mime query filetype subtitles.srt
application/x-subrip

$ file --mime-type subtitles.srt
subtitles.srt: text/plain

in the above file only show it as plain text.

WebDriver - wait for element using Java

You can use Explicit wait or Fluent Wait

Example of Explicit Wait -

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));     

Example of Fluent Wait -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                            
.withTimeout(20, TimeUnit.SECONDS)          
.pollingEvery(5, TimeUnit.SECONDS)          
.ignoring(NoSuchElementException.class);    

  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {       
public WebElement apply(WebDriver driver) { 
return driver.findElement(By.id("about_me"));     
 }  
});  

Check this TUTORIAL for more details.

splitting a number into the integer and decimal parts

This variant allows getting desired precision:

>>> a = 1234.5678
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e0)
(1234, 0.0)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e1)
(1234, 0.5)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e15)
(1234, 0.5678)

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

Spring lets you define multiple contexts in a parent-child hierarchy.

The applicationContext.xml defines the beans for the "root webapp context", i.e. the context associated with the webapp.

The spring-servlet.xml (or whatever else you call it) defines the beans for one servlet's app context. There can be many of these in a webapp, one per Spring servlet (e.g. spring1-servlet.xml for servlet spring1, spring2-servlet.xml for servlet spring2).

Beans in spring-servlet.xml can reference beans in applicationContext.xml, but not vice versa.

All Spring MVC controllers must go in the spring-servlet.xml context.

In most simple cases, the applicationContext.xml context is unnecessary. It is generally used to contain beans that are shared between all servlets in a webapp. If you only have one servlet, then there's not really much point, unless you have a specific use for it.

Is there a program to decompile Delphi?

I don't think there are any machine code decompilers that produce Pascal code. Most "Delphi decompilers" parse form and RTTI data, but do not actually decompile the machine code. I can only recommend using something like DeDe (or similar software) to extract symbol information in combination with a C decompiler, then translate the decompiled C code to Delphi (there are many source code converters out there).

Visual Studio 2015 installer hangs during install?

I had also same issue, I am using Windows 10 Fall creator Edition, Set were getting stuck at some time 0% and some time 44% when it reached WIN 10SDK_10. .. file

After some research and getting into my logs files and processors in task processor i found some Power shell processor were running, I just kill the process which was not responding for long time and my setup get start working and showing progress.... that's it

I don't Know If it works for your peoples But it works in my case.

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:

#!/bin/bash

export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost

You might be interested in How to run the sftp command with a password from Bash script?

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

For Rect-Native developers. I encounter this error while renderingItem in FlatList. I had two Text components. I was using them like below

renderItem = { ({item}) => 
     <Text style = {styles.item}>{item.key}</Text>
     <Text style = {styles.item}>{item.user}</Text>
}

But after I put these tow Inside View Components it worked for me.

renderItem = { ({item}) => 
   <View style={styles.flatview}>
      <Text style = {styles.item}>{item.key}</Text>
      <Text style = {styles.item}>{item.user}</Text>
   </View>
 }

You might be using other components but putting them into View may be worked for you.

How to find out the server IP address (using JavaScript) that the browser is connected to?

You cannot get this in general. From Javascript, you can only get the HTTP header, which may or may not have an IP address (typically only has the host name). Part of the browser's program is to abstract the TCP/IP address away and only allow you to deal with a host name.

Using crontab to execute script every minute and another every 24 hours

every minute:

* * * * * /path/to/php /var/www/html/a.php

every 24hours (every midnight):

0 0 * * * /path/to/php /var/www/html/reset.php

See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

How to connect android emulator to the internet

Make sure Airplane mode is OFF. I kept trying to connect to the internet for a long time before realising what was wrong.

How is using OnClickListener interface different via XML and Java code?

These are exactly the same. android:onClick was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an OnClickListener on the Button, which calls your DoIt method.

Here is what using a android:onClick="DoIt" does internally:

Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DoIt(v);
    }
});

The only thing you trade off by using android:onClick, as usual with XML configuration, is that it becomes a bit more difficult to add dynamic content (programatically, you could decide to add one listener or another depending on your variables). But this is easily defeated by adding your test within the DoIt method.

Deleting Elements in an Array if Element is a Certain value VBA

When creating the array, why not just skip over the 0s and save yourself the time of having to worry about them later? As mentioned above, arrays are not well-suited for deletion.

Rails 3 migrations: Adding reference column?

If you are using the Rails 4.x you can now generate migrations with references, like this:

rails generate migration AddUserRefToProducts user:references

like you can see on rails guides

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

wmic can call an uninstaller. I haven't tried this, but I think it might work.

wmic /node:computername /user:adminuser /password:password product where name="name of application" call uninstall

If you don't know exactly what the program calls itself, do

wmic product get name | sort

and look for it. You can also uninstall using SQL-ish wildcards.

wmic /node:computername /user:adminuser /password:password product where "name like '%j2se%'" call uninstall

... for example would perform a case-insensitive search for *j2se* and uninstall "J2SE Runtime Environment 5.0 Update 12". (Note that in the example above, %j2se% is not an environment variable, but simply the word "j2se" with a SQL-ish wildcard on each end. If your search string could conflict with an environment or script variable, use double percents to specify literal percent signs, like %%j2se%%.)

If wmic prompts for y/n confirmation before completing the uninstall, try this:

echo y | wmic /node:computername /user:adminuser /password:password product where name="whatever" call uninstall

... to pass a y to it before it even asks.

I haven't tested this, but it's worth a shot anyway. If it works on one computer, then you can just loop through a text file containing all the computer names within your organization using a for loop, or put it in a domain policy logon script.

Preprocessing in scikit learn - single sample - Depreciation warning

Just listen to what the warning is telling you:

Reshape your data either X.reshape(-1, 1) if your data has a single feature/column and X.reshape(1, -1) if it contains a single sample.

For your example type(if you have more than one feature/column):

temp = temp.reshape(1,-1) 

For one feature/column:

temp = temp.reshape(-1,1)

Log all requests from the python-requests module

I'm using a logger_config.yaml file to configure my logging, and to get those logs to show up, all I had to do was to add a disable_existing_loggers: False to the end of it.

My logging setup is rather extensive and confusing, so I don't even know a good way to explain it here, but if someone's also using a YAML file to configure their logging, this might help.

https://docs.python.org/3/howto/logging.html#configuring-logging

Opening popup windows in HTML

Something like this?

<a href="#" onClick="MyWindow=window.open('http://www.google.com','MyWindow','width=600,height=300'); return false;">Click Here</a>

Setting Windows PowerShell environment variables

Most answers aren't addressing UAC. This covers UAC issues.

First install PowerShell Community Extensions: choco install pscx via http://chocolatey.org/ (you may have to restart your shell environment).

Then enable pscx

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser #allows scripts to run from the interwebs, such as pcsx

Then use Invoke-Elevated

Invoke-Elevated {Add-PathVariable $args[0] -Target Machine} -ArgumentList $MY_NEW_DIR

How to execute a java .class from the command line

If you have in your java source

package mypackage;

and your class is hello.java with

public class hello {

and in that hello.java you have

 public static void main(String[] args) {

Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then

java -cp . mypackage.hello

Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also

Thanks Stack overflow for a wealth of info.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

In the other question I suggested autoexnt. That is also possible in this situation. Just set the service to run manually (ie not automatic at startup). When you want to run your batch, modify the autoexnt.bat file to call the batch file you want, and start the autoexnt service.

The batchfile to start this, can look like this (untested):

echo call c:\path\to\batch.cmd %* > c:\windows\system32\autoexnt.bat
net start autoexnt

Note that batch files started this way run as the system user, which means you do not have access to network shares automatically. But you can use net use to connect to a remote server.

You have to download the Windows 2003 Resource Kit to get it. The Resource Kit can also be installed on other versions of windows, like Windows XP.

Docker and securing passwords

Definitely it is a concern. Dockerfiles are commonly checked in to repositories and shared with other people. An alternative is to provide any credentials (usernames, passwords, tokens, anything sensitive) as environment variables at runtime. This is possible via the -e argument (for individual vars on the CLI) or --env-file argument (for multiple variables in a file) to docker run. Read this for using environmental with docker-compose.

Using --env-file is definitely a safer option since this protects against the secrets showing up in ps or in logs if one uses set -x.

However, env vars are not particularly secure either. They are visible via docker inspect, and hence they are available to any user that can run docker commands. (Of course, any user that has access to docker on the host also has root anyway.)

My preferred pattern is to use a wrapper script as the ENTRYPOINT or CMD. The wrapper script can first import secrets from an outside location in to the container at run time, then execute the application, providing the secrets. The exact mechanics of this vary based on your run time environment. In AWS, you can use a combination of IAM roles, the Key Management Service, and S3 to store encrypted secrets in an S3 bucket. Something like HashiCorp Vault or credstash is another option.

AFAIK there is no optimal pattern for using sensitive data as part of the build process. In fact, I have an SO question on this topic. You can use docker-squash to remove layers from an image. But there's no native functionality in Docker for this purpose.

You may find shykes comments on config in containers useful.

Truncate (not round off) decimal numbers in javascript

Here is simple but working function to truncate number upto 2 decimal places.

           function truncateNumber(num) {
                var num1 = "";
                var num2 = "";
                var num1 = num.split('.')[0];
                num2 = num.split('.')[1];
                var decimalNum = num2.substring(0, 2);
                var strNum = num1 +"."+ decimalNum;
                var finalNum = parseFloat(strNum);
                return finalNum;
            }

Set UILabel line spacing

From Interface Builder:

enter image description here

Programmatically:

SWift 4

Using label extension

extension UILabel {

    func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {

        guard let labelText = self.text else { return }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.lineHeightMultiple = lineHeightMultiple

        let attributedString:NSMutableAttributedString
        if let labelattributedText = self.attributedText {
            attributedString = NSMutableAttributedString(attributedString: labelattributedText)
        } else {
            attributedString = NSMutableAttributedString(string: labelText)
        }

        // Line spacing attribute
        attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))

        self.attributedText = attributedString
    }
}

Now call extension function

let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"

// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) .  // try values 1.0 to 5.0

// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0


Or using label instance (Just copy & execute this code to see result)

let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40

// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))

// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))

label.attributedText = attrString

Swift 3

let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString

What is the difference between user variables and system variables?

System environment variables are globally accessed by all users.
User environment variables are specific only to the currently logged-in user.

What is the command for cut copy paste a file from one directory to other directory

E:>move "blogger code.txt" d:/"blogger code.txt"

    1 file(s) moved.

"blogger code.txt" is a file name

The file move from E: drive to D: drive

Setting TIME_WAIT TCP

I have been load testing a server application (on linux) by using a test program with 20 threads.

In 959,000 connect / close cycles I had 44,000 failed connections and many thousands of sockets in TIME_WAIT.

I set SO_LINGER to 0 before the close call and in subsequent runs of the test program had no connect failures and less than 20 sockets in TIME_WAIT.

Converting Integer to Long

Simply:

Integer i = 7;
Long l = new Long(i);

Have border wrap around text

The easiest way to do it is to make the display an inline block

<div id='page' style='width: 600px'>
  <h1 style='border:2px black solid; font-size:42px; display: inline-block;'>Title</h1>
</div>

if you do this it should work

Make git automatically remove trailing whitespace before committing

On Mac OS (or, likely, any BSD), the sed command parameters have to be slightly different. Try this:

#!/bin/sh

if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
   against=HEAD
else
   # Initial commit: diff against an empty tree object
   against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | sed -E 's/:[0-9]+:.*//' | uniq` ; do
    # Fix them!
    sed -i '' -E 's/[[:space:]]*$//' "$FILE"
    git add "$FILE"
done

Save this file as .git/hooks/pre-commit -- or look for the one that's already there, and paste the bottom chunk somewhere inside it. And remember to chmod a+x it too.

Or for global use (via Git commit hooks - global settings) you can put it in $GIT_PREFIX/git-core/templates/hooks (where GIT_PREFIX is /usr or /usr/local or /usr/share or /opt/local/share) and run git init inside your existing repos.

According to git help init:

Running git init in an existing repository is safe. It will not overwrite things that are already there. The primary reason for rerunning git init is to pick up newly added templates.

Why do people say that Ruby is slow?

I would say Ruby is slow because not much effort has been spent in making the interpreter faster. Same applies to Python. Smalltalk is just as dynamic as Ruby or Python but performs better by a magnitude, see http://benchmarksgame.alioth.debian.org. Since Smalltalk was more or less replaced by Java and C# (that is at least 10 years ago) no more performance optimization work had been done for it and Smalltalk is still ways faster than Ruby and Python. The people at Xerox Parc and at OTI/IBM had the money to pay the people that work on making Smalltalk faster. What I don't understand is why Google doesn't spend the money for making Python faster as they are a big Python shop. Instead they spend money on development of languages like Go...

How to Split Image Into Multiple Pieces in Python

I tried the solutions above, but sometimes you just gotta do it yourself. Might be off by a pixel in some cases but works fine in general.

import matplotlib.pyplot as plt
import numpy as np
def image_to_tiles(im, number_of_tiles = 4, plot=False):
    """
    Function that splits SINGLE channel images into tiles
    :param im: image: single channel image (NxN matrix)
    :param number_of_tiles: squared number
    :param plot:
    :return tiles:
    """
    n_slices = np.sqrt(number_of_tiles)
    assert int(n_slices + 0.5) ** 2 == number_of_tiles, "Number of tiles is not a perfect square"

    n_slices = n_slices.astype(np.int)
    [w, h] = cropped_npy.shape

    r = np.linspace(0, w, n_slices+1)
    r_tuples = [(np.int(r[i]), np.int(r[i+1])) for i in range(0, len(r)-1)]
    q = np.linspace(0, h, n_slices+1)
    q_tuples = [(np.int(q[i]), np.int(q[i+1])) for i in range(0, len(q)-1)]

    tiles = []
    for row in range(n_slices):
        for column in range(n_slices):
            [x1, y1, x2, y2] = *r_tuples[row], *q_tuples[column] 
            tiles.append(im[x1:y1, x2:y2])

    if plot:
        fig, axes = plt.subplots(n_slices, n_slices, figsize=(10,10))
        c = 0
        for row in range(n_slices):
            for column in range(n_slices):
                axes[row,column].imshow(tiles[c])
                axes[row,column].axis('off')
                c+=1

    return tiles

Hope it helps.

Where can I get a list of Countries, States and Cities?

This may be a sideways answer, but if you download Virtuemart (A Joomla component), it has a countries table and all the related states all set up for you included in the installation SQL. They're called jos_virtuemart_countries and jos_virtuemart_states. It also includes the 2 and 3 character country codes. I'd attach it to my answer, but don't see a way of doing it.

How to list all functions in a Python module?

If you want to get the list of all the functions defined in the current file, you can do it that way:

# Get this script's name.
import os
script_name = os.path.basename(__file__).rstrip(".py")

# Import it from its path so that you can use it as a Python object.
import importlib.util
spec = importlib.util.spec_from_file_location(script_name, __file__)
x = importlib.util.module_from_spec(spec)
spec.loader.exec_module(x)

# List the functions defined in it.
from inspect import getmembers, isfunction
list_of_functions = getmembers(x, isfunction)

As an application example, I use that for calling all the functions defined in my unit testing scripts.

This is a combination of codes adapted from the answers of Thomas Wouters and adrian here, and from Sebastian Rittau on a different question.

Why do I need to configure the SQL dialect of a data source?

Dialect property is used by hibernate in following ways

  1. To generate Optimized SQL queries.
  2. If you have more than one DB then to talk with particular DB you want.
  3. To set default values for hibernate configuration file properties based on the DB software we use even though they are not specifed in configuration file.

How do I remove the height style from a DIV using jQuery?

$('div#someDiv').removeAttr("height");

How to avoid HTTP error 429 (Too Many Requests) python

Receiving a status 429 is not an error, it is the other server "kindly" asking you to please stop spamming requests. Obviously, your rate of requests has been too high and the server is not willing to accept this.

You should not seek to "dodge" this, or even try to circumvent server security settings by trying to spoof your IP, you should simply respect the server's answer by not sending too many requests.

If everything is set up properly, you will also have received a "Retry-after" header along with the 429 response. This header specifies the number of seconds you should wait before making another call. The proper way to deal with this "problem" is to read this header and to sleep your process for that many seconds.

You can find more information on status 429 here: http://tools.ietf.org/html/rfc6585#page-3

What's the difference between lists and tuples?

The most important difference is time ! When you do not want to change the data inside the list better to use tuple ! Here is the example why use tuple !

import timeit
print(timeit.timeit(stmt='[1,2,3,4,5,6,7,8,9,10]', number=1000000)) #created list
print(timeit.timeit(stmt='(1,2,3,4,5,6,7,8,9,10)', number=1000000)) # created tuple 

In this example we executed both statements 1 million times

Output :

0.136621
0.013722200000000018

Any one can clearly notice the time difference.

Fatal error: Call to a member function query() on null

put this line in parent construct : $this->load->database();

function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..

Convert python datetime to timestamp in milliseconds

You need to parse your time format using strptime.

>>> import time
>>> from datetime import datetime
>>> ts, ms = '20.12.2016 09:38:42,76'.split(',')
>>> ts
'20.12.2016 09:38:42'
>>> ms
'76'
>>> dt = datetime.strptime(ts, '%d.%m.%Y %H:%M:%S')
>>> time.mktime(dt.timetuple())*1000 + int(ms)*10
1482223122760.0

Difference between CR LF, LF and CR line break types?

Systems based on ASCII or a compatible character set use either LF (Line feed, 0x0A, 10 in decimal) or CR (Carriage return, 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A); These characters are based on printer commands: The line feed indicated that one line of paper should feed out of the printer, and a carriage return indicated that the printer carriage should return to the beginning of the current line.

Here is the details.

Test if number is odd or even

PHP is converting null and an empty string automatically to a zero. That happens with modulo as well. Therefor will the code

$number % 2 == 0 or !($number & 1)

with value $number = '' or $number = null result in true. I test it therefor somewhat more extended:

function testEven($pArg){
    if(is_int($pArg) === true){
        $p = ($pArg % 2);
        if($p === 0){
            print "The input '".$pArg."' is even.<br>";
        }else{
            print "The input '".$pArg."' is odd.<br>";
        }
    }else{
        print "The input '".$pArg."' is not a number.<br>";
    }
}

The print is there for testing purposes, hence in practice it becomes:
function testEven($pArg){
    if(is_int($pArg)=== true){
        return $pArg%2;
    }
    return false;
}

This function returns 1 for any odd number, 0 for any even number and false when it is not a number. I always write === true or === false to let myself (and other programmers) know that the test is as intended.

How to search through all Git and Mercurial commits in the repository for a certain string?

Building on rq's answer, I found this line does what I want:

git grep "search for something" $(git log -g --pretty=format:%h -S"search for something")

Which will report the commit ID, filename, and display the matching line, like this:

91ba969:testFile:this is a test

... Does anyone agree that this would be a nice option to be included in the standard git grep command?

How do I base64 encode a string efficiently using Excel VBA?

You can use the MSXML Base64 encoding functionality as described at www.nonhostile.com/howto-encode-decode-base64-vb6.asp:

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)      

  Dim objXML As MSXML2.DOMDocument
  Dim objNode As MSXML2.IXMLDOMElement

  Set objXML = New MSXML2.DOMDocument 
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.Text 

  Set objNode = Nothing
  Set objXML = Nothing
End Function

Difference between thread's context class loader and normal classloader

Adding to @David Roussel answer, classes may be loaded by multiple class loaders.

Lets understand how class loader works.

From javin paul blog in javarevisited :

enter image description here

enter image description here

ClassLoader follows three principles.

Delegation principle

A class is loaded in Java, when its needed. Suppose you have an application specific class called Abc.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader

  • Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents.

  • Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property

  • System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.

  • Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader class.

NOTE: Except Bootstrap class loader, which is implemented in native language mostly in C, all Java class loaders are implemented using java.lang.ClassLoader.

Visibility Principle

According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true.

Uniqueness Principle

According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again

how to remove key+value from hash in javascript

Another option may be this John Resig remove method. can better fit what you need. if you know the index in the array.

How to remove all subviews of a view in Swift?

One-liner:

while view.subviews.count > 0  { (view.subviews[0] as? NSView)?.removeFromSuperview() } 

Detect element content changes with jQuery

I wrote a snippet that will check for the change of an element on an event.

So if you are using third party javascript code or something and you need to know when something appears or changes when you have clicked then you can.

For the below snippet, lets say you need to know when a table content changes after you clicked a button.

$('.button').live('click', function() {

            var tableHtml = $('#table > tbody').html();
            var timeout = window.setInterval(function(){

                if (tableHtml != $('#table > tbody').
                    console.log('no change');
                } else {
                    console.log('table changed!');
                    clearInterval(timeout);
                }

            }, 10);
        });

Pseudo Code:

  • Once you click a button
  • the html of the element you are expecting to change is captured
  • we then continually check the html of the element
  • when we find the html to be different we stop the checking

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)

To quote the most relevant bits:

[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.

The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”

Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.

The full post explains this in more detail. At RTM, the MSDN docs on this should be better.

Center text output from Graphics.DrawString()

You can use an instance of the StringFormat object passed into the DrawString method to center the text.

See Graphics.DrawString Method and StringFormat Class.

Emulator error: This AVD's configuration is missing a kernel file

I had the same problem. In my case it turned out I had installed another version of the sdk alongside the version provided by Android Studio. Changing my ANDROID_SDK_ROOT environment variable to the original value fixed it for me.

Text not wrapping in p tag

This is a little late for this question but others might benefit. I had a similar problem but had an added requirement for the text to correctly wrap in all device sizes. So in my case this worked. Need to setup the view port.

 .p
   {
   white-space: normal;
    overflow-wrap: break-word;
    width: 96vw;
   }

Variable is accessed within inner class. Needs to be declared final

You can declare the variable final, or make it an instance (or global) variable. If you declare it final, you won't be able to change it later.

Any variable defined in a method and accessed by an anonymous inner class must be final. Otherwise, you could use that variable in the inner class, unaware that if the variable changes in the inner class, and then it is used later in the enclosing scope, the changes made in the inner class did not persist in the enclosing scope. Basically, what happens in the inner class stays in the inner class.

I wrote a more in-depth explanation here. It also explains why instance and global variables do not need to be declared final.

How to display Toast in Android?

Simple Way

toast("Your Message")

OR

toast(R.string.some_message)

Just add two methods in your BaseActivity. Or create new BaseActivity if you are not already using.

public class BaseActivity extends AppCompatActivity {
    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void toast(@StringRes int msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}

and extend all your activities by BaseActivity.

public class MainActivity extends BaseActivity

Parsing time string in Python

It has discussed many times in SO. In short, "%z" is not supported because platform not support it. My solution is a new one, just skip the time zone.:

    datetime.datetime.strptime(re.sub(r"[+-]([0-9])+", "", "Tue May 08 15:14:45 +0800 2012"),"%a %b %d %H:%M:%S %Y")

Difference between adjustResize and adjustPan in android?

From the Android Developer Site link

"adjustResize"

The activity's main window is always resized to make room for the soft keyboard on screen.

"adjustPan"

The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desirable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.

according to your comment, use following in your activity manifest

<activity android:windowSoftInputMode="adjustResize"> </activity>

How to convert wstring into string?

Besides just converting the types, you should also be conscious about the string's actual format.

When compiling for Multi-byte Character set Visual Studio and the Win API assumes UTF8 (Actually windows encoding which is Windows-28591 ).
When compiling for Unicode Character set Visual studio and the Win API assumes UTF16.

So, you must convert the string from UTF16 to UTF8 format as well, and not just convert to std::string.
This will become necessary when working with multi-character formats like some non-latin languages.

The idea is to decide that std::wstring always represents UTF16.
And std::string always represents UTF8.

This isn't enforced by the compiler, it's more of a good policy to have. Note the string prefixes I use to define UTF16 (L) and UTF8 (u8).

To convert between the 2 types, you should use: std::codecvt_utf8_utf16< wchar_t>

#include <string>

#include <codecvt>

int main()
{

    std::string original8 = u8"???";

    std::wstring original16 = L"???";

    //C++11 format converter
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;

    //convert to UTF8 and std::string
    std::string utf8NativeString = convert.to_bytes(original16);

    std::wstring utf16NativeString = convert.from_bytes(original8);

    assert(utf8NativeString == original8);
    assert(utf16NativeString == original16);

    return 0;
}

Can't bind to 'ngModel' since it isn't a known property of 'input'

For my scenario, I had to import both [CommonModule] and [FormsModule] to my module

import { NgModule } from '@angular/core' 
import { CommonModule } from '@angular/common'; 
import { FormsModule } from '@angular/forms'; 

import { MyComponent } from './mycomponent'

@NgModule({
    imports: [
        CommonModule,
        FormsModule
    ],
    declarations: [
        MyComponent 
    ]
 }) 
export class MyModule { }

How do I get the height and width of the Android Navigation Bar programmatically?

Simple One-line Solution

As suggested in many of above answers, for example

Simply getting navigation bar height may not be enough. We need to consider whether 1. navigation bar exists, 2. is it on the bottom, or right or left, 3. is app open in multi-window mode.

Fortunately you can easily bypass all the long coding by simply setting android:fitsSystemWindows="true" in your root layout. Android system will automatically take care of adding necessary padding to the root layout to make sure that the child views don't get into the navigation bar or statusbar regions.

There is a simple one line solution

android:fitsSystemWindows="true"

or programatically

findViewById(R.id.your_root_view).setFitsSystemWindows(true);

you may also get root view by

findViewById(android.R.id.content).getRootView();
or
getWindow().getDecorView().findViewById(android.R.id.content)

For more details on getting root-view refer - https://stackoverflow.com/a/4488149/9640177

Simple Random Samples from a Sql database

Maybe you could do

SELECT * FROM table LIMIT 10000 OFFSET FLOOR(RAND() * 190000)

Use .corr to get the correlation between two columns

Without actual data it is hard to answer the question but I guess you are looking for something like this:

Top15['Citable docs per Capita'].corr(Top15['Energy Supply per Capita'])

That calculates the correlation between your two columns 'Citable docs per Capita' and 'Energy Supply per Capita'.

To give an example:

import pandas as pd

df = pd.DataFrame({'A': range(4), 'B': [2*i for i in range(4)]})

   A  B
0  0  0
1  1  2
2  2  4
3  3  6

Then

df['A'].corr(df['B'])

gives 1 as expected.

Now, if you change a value, e.g.

df.loc[2, 'B'] = 4.5

   A    B
0  0  0.0
1  1  2.0
2  2  4.5
3  3  6.0

the command

df['A'].corr(df['B'])

returns

0.99586

which is still close to 1, as expected.

If you apply .corr directly to your dataframe, it will return all pairwise correlations between your columns; that's why you then observe 1s at the diagonal of your matrix (each column is perfectly correlated with itself).

df.corr()

will therefore return

          A         B
A  1.000000  0.995862
B  0.995862  1.000000

In the graphic you show, only the upper left corner of the correlation matrix is represented (I assume).

There can be cases, where you get NaNs in your solution - check this post for an example.

If you want to filter entries above/below a certain threshold, you can check this question. If you want to plot a heatmap of the correlation coefficients, you can check this answer and if you then run into the issue with overlapping axis-labels check the following post.

RestSharp JSON Parameter Posting

You don't have to serialize the body yourself. Just do

request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new { A = "foo", B = "bar" }); // Anonymous type object is converted to Json body

If you just want POST params instead (which would still map to your model and is a lot more efficient since there's no serialization to JSON) do this:

request.AddParameter("A", "foo");
request.AddParameter("B", "bar");

HTML: Select multiple as dropdown

Because you're using multiple. Despite it still technically being a dropdown, it doesn't look or act like a standard dropdown. Rather, it populates a list box and lets them select multiple options.

Size determines how many options appear before they have to click down or up to see the other options.

I have a feeling what you want to achieve is only going to be possible with a JavaScript plugin.

Some examples:

jQuery multiselect drop down menu

http://labs.abeautifulsite.net/archived/jquery-multiSelect/demo/

Can (domain name) subdomains have an underscore "_" in it?

Here my 2 cents from Java world:

From a Spark Scala console, with Java 8:

scala> new java.net.URI("spark://spark_master").getHost
res10: String = null

scala> new java.net.URI("spark://spark-master").getHost
res11: String = spark-master

scala> new java.net.URI("spark://spark_master.google.fr").getHost
res12: String = null

scala> new java.net.URI("spark://spark.master.google.fr").getHost
res13: String = spark.master.google.fr

scala> new java.net.URI("spark://spark-master.google.fr:3434").getHost
res14: String = spark-master.google.fr

scala> new java.net.URI("spark://spark-master.goo_gle.fr:3434").getHost
res15: String = null

It's definitely a bad idea ^^

Convert Date/Time for given Timezone - java

Joda-Time

The java.util.Date/Calendar classes are a mess and should be avoided.

Update: The Joda-Time project is in maintenance mode. The team advises migration to the java.time classes.

Here's your answer using the Joda-Time 2.3 library. Very easy.

As noted in the example code, I suggest you use named time zones wherever possible so that your programming can handle Daylight Saving Time (DST) and other anomalies.

If you had placed a T in the middle of your string instead of a space, you could skip the first two lines of code, dealing with a formatter to parse the string. The DateTime constructor can take a string in ISO 8601 format.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

// Parse string as a date-time in UTC (no time zone offset).
DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss" );
DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( "2011-10-06 03:35:05" );

// Adjust for 13 hour offset from UTC/GMT.
DateTimeZone offsetThirteen = DateTimeZone.forOffsetHours( 13 );
DateTime thirteenDateTime = dateTimeInUTC.toDateTime( offsetThirteen );

// Hard-coded offsets should be avoided. Better to use a desired time zone for handling Daylight Saving Time (DST) and other anomalies.
// Time Zone list… http://joda-time.sourceforge.net/timezones.html
DateTimeZone timeZoneTongatapu = DateTimeZone.forID( "Pacific/Tongatapu" );
DateTime tongatapuDateTime = dateTimeInUTC.toDateTime( timeZoneTongatapu );

Dump those values…

System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "thirteenDateTime: " + thirteenDateTime );
System.out.println( "tongatapuDateTime: " + tongatapuDateTime );

When run…

dateTimeInUTC: 2011-10-06T03:35:05.000Z
thirteenDateTime: 2011-10-06T16:35:05.000+13:00
tongatapuDateTime: 2011-10-06T16:35:05.000+13:00

Is there a Subversion command to reset the working copy?

To revert tracked files

svn revert . -R

To clean untracked files

svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

The -rf may/should look scary at first, but once understood it will not be for these reasons:

  1. Only wholly-untracked directories will match the pattern passed to rm
  2. The -rf is required, else these directories will not be removed

To revert then clean (the OP question)

svn revert . -R && svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

For consistent ease of use

Add permanent alias to your .bash_aliases

alias svn.HardReset='read -p "destroy all local changes?[y/N]" && [[ $REPLY =~ ^[yY] ]] && svn revert . -R && rm -rf $(awk -f <(echo "/^?/{print \$2}") <(svn status) ;)'

How to change my Git username in terminal?

  1. In your terminal, navigate to the repo you want to make the changes in.
  2. Execute git config --list to check current username & email in your local repo.
  3. Change username & email as desired. Make it a global change or specific to the local repo:

git config [--global] user.name "Full Name"

git config [--global] user.email "[email protected]"

Per repo basis you could also edit .git/config manually instead.

  1. Done!

When performing step 2 if you see credential.helper=manager you need to open the credential manager of your computer (Win or Mac) and update the credentials there

Manually type in a value in a "Select" / Drop-down HTML list?

I faced the same basic problem: trying to combine the functionality of a textbox and a select box which are fundamentally different things in the html spec.

The good news is that selectize.js does exactly this:

Selectize is the hybrid of a textbox and box. It's jQuery-based and it's useful for tagging, contact lists, country selectors, and so on.

Show Curl POST Request Headers? Is there a way to do this?

You can see the information regarding the transfer by doing:

curl_setopt($curl_exect, CURLINFO_HEADER_OUT, true);

before the request, and

$information = curl_getinfo($curl_exect);

after the request

View: http://www.php.net/manual/en/function.curl-getinfo.php

You can also use the CURLOPT_HEADER in your curl_setopt

curl_setopt($curl_exect, CURLOPT_HEADER, true);

$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);

return $httpcode == 200;

These are just some methods of using the headers.

Microsoft.ACE.OLEDB.12.0 provider is not registered

See my post on a similar Stack Exchange thread https://stackoverflow.com/a/21455677/1368849

I had version 15, not 12 installed, which I found out by running this PowerShell code...

(New-Object system.data.oledb.oledbenumerator).GetElements() | select SOURCES_NAME, SOURCES_DESCRIPTION

...which gave me this result (I've removed other data sources for brevity)...

SOURCES_NAME              SOURCES_DESCRIPTION                                                                       
------------              -------------------                                                                       
Microsoft.ACE.OLEDB.15.0  Microsoft Office 15.0 Access Database Engine OLE DB Provider

Convert a RGB Color Value to a Hexadecimal String

A one liner but without String.format for all RGB colors:

Color your_color = new Color(128,128,128);

String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);

You can add a .toUpperCase()if you want to switch to capital letters. Note, that this is valid (as asked in the question) for all RGB colors.

When you have ARGB colors you can use:

Color your_color = new Color(128,128,128,128);

String buf = Integer.toHexString(your_color.getRGB());
String hex = "#"+buf.substring(buf.length()-6);

A one liner is theoretically also possible but would require to call toHexString twice. I benchmarked the ARGB solution and compared it with String.format():

enter image description here

Add string in a certain position in Python

As strings are immutable another way to do this would be to turn the string into a list, which can then be indexed and modified without any slicing trickery. However, to get the list back to a string you'd have to use .join() using an empty string.

>>> hash = '355879ACB6'
>>> hashlist = list(hash)
>>> hashlist.insert(4, '-')
>>> ''.join(hashlist)
'3558-79ACB6'

I am not sure how this compares as far as performance, but I do feel it's easier on the eyes than the other solutions. ;-)

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

Just for completeness. There is another situation causing this error:

missing META-INF/services/javax.persistence.spi.PersistenceProvider file.

For Hibernate, it's located in hibernate-entitymanager-XXX.jar, so, if hibernate-entitymanager-XXX.jar is not in your classpath, you will got this error too.

This error message is so misleading, and it costs me hours to get it correct.

See JPA 2.0 using Hibernate as provider - Exception: No Persistence provider for EntityManager.

CSS property to pad text inside of div

The CSS property you are looking for is padding. The problem with padding is that it adds to the width of the original element, so if you have a div with a width of 300px, and add 10px of padding to it, the width will now be 320px (10px on the left and 10px on the right).

To prevent this you can add box-sizing: border-box; to the div, this makes it maintain the designated width, even if you add padding. So your CSS would look like this:

div {
    box-sizing: border-box;
    padding: 10px;
}

you can read more about box-sizing and it's overall browser support here:

http://www.paulirish.com/2012/box-sizing-border-box-ftw/

Practical uses for the "internal" keyword in C#

Keep in mind that any class defined as public will automatically show up in the intellisense when someone looks at your project namespace. From an API perspective, it is important to only show users of your project the classes that they can use. Use the internal keyword to hide things they shouldn't see.

If your Big_Important_Class for Project A is intended for use outside your project, then you should not mark it internal.

However, in many projects, you'll often have classes that are really only intended for use inside a project. For example, you may have a class that holds the arguments to a parameterized thread invocation. In these cases, you should mark them as internal if for no other reason than to protect yourself from an unintended API change down the road.

openssl s_client -cert: Proving a client certificate was sent to the server

In order to verify a client certificate is being sent to the server, you need to analyze the output from the combination of the -state and -debug flags.

First as a baseline, try running

$ openssl s_client -connect host:443 -state -debug

You'll get a ton of output, but the lines we are interested in look like this:

SSL_connect:SSLv3 read server done A
write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
0000 - 16 03 01 00 07 0b 00 00-03                        .........
000c - <SPACES/NULS>
SSL_connect:SSLv3 write client certificate A

What's happening here:

  • The -state flag is responsible for displaying the end of the previous section:

    SSL_connect:SSLv3 read server done A  
    

    This is only important for helping you find your place in the output.

  • Then the -debug flag is showing the raw bytes being sent in the next step:

    write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
    0000 - 16 03 01 00 07 0b 00 00-03                        .........
    000c - <SPACES/NULS>
    
  • Finally, the -state flag is once again reporting the result of the step that -debug just echoed:

    SSL_connect:SSLv3 write client certificate A
    

So in other words: s_client finished reading data sent from the server, and sent 12 bytes to the server as (what I assume is) a "no client certificate" message.


If you repeat the test, but this time include the -cert and -key flags like this:

$ openssl s_client -connect host:443 \
   -cert cert_and_key.pem \
   -key cert_and_key.pem  \
   -state -debug

your output between the "read server done" line and the "write client certificate" line will be much longer, representing the binary form of your client certificate:

SSL_connect:SSLv3 read server done A
write to 0x7bd970 [0x86d890] (1576 bytes => 1576 (0x628))
0000 - 16 03 01 06 23 0b 00 06-1f 00 06 1c 00 06 19 31   ....#..........1
(*SNIP*)
0620 - 95 ca 5e f4 2f 6c 43 11-                          ..^%/lC.
SSL_connect:SSLv3 write client certificate A

The 1576 bytes is an excellent indication on its own that the cert was transmitted, but on top of that, the right-hand column will show parts of the certificate that are human-readable: You should be able to recognize the CN and issuer strings of your cert in there.

Creating composite primary key in SQL Server

How about something like

CREATE TABLE testRequest (
        wardNo nchar(5),
        BHTNo nchar(5),
        testID nchar(5),
        reqDateTime datetime,
        PRIMARY KEY (wardNo, BHTNo, testID)
);

Have a look at this example

SQL Fiddle DEMO

jQuery’s .bind() vs. .on()

These snippets all perform exactly the same thing:

element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });

However, they are very different from these, which all perform the same thing:

element.on('click', 'selector', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });

The second set of event handlers use event delegation and will work for dynamically added elements. Event handlers that use delegation are also much more performant. The first set will not work for dynamically added elements, and are much worse for performance.

jQuery's on() function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery (you no longer have to decide between live, bind, or delegate).

Database development mistakes made by application developers

Many developers tend to execute multiple queries against the database (often querying one or two tables) extract the results and perform simple operations in java/c/c++ - all of which could have been done with a single SQL statement.

Many developers often dont realize that on development environments database and app servers are on their laptops - but on a production environment, database and apps server will be on different machines. Hence for every query there is an additional n/w overhead for the data to be passed between the app server and the database server. I have been amazed to find the number of database calls that are made from the app server to the database server to render one page to the user!

Converting newline formatting from Mac to Windows

  1. Install dos2unix with homebrew
  2. Run find ./ -type f -exec dos2unix {} \; to recursively convert all line-endings within current folder

Giving graphs a subtitle in matplotlib

Just use TeX ! This works :

title(r"""\Huge{Big title !} \newline \tiny{Small subtitle !}""")

EDIT: To enable TeX processing, you need to add the "usetex = True" line to matplotlib parameters:

fig_size = [12.,7.5]
params = {'axes.labelsize': 8,
      'text.fontsize':   6,
      'legend.fontsize': 7,
      'xtick.labelsize': 6,
      'ytick.labelsize': 6,
      'text.usetex': True,       # <-- There 
      'figure.figsize': fig_size,
      }
rcParams.update(params)

I guess you also need a working TeX distribution on your computer. All details are given at this page:

http://matplotlib.org/users/usetex.html

VBA using ubound on a multidimensional array

Looping D3 ways;

Sub SearchArray()
    Dim arr(3, 2) As Variant
    arr(0, 0) = "A"
    arr(0, 1) = "1"
    arr(0, 2) = "w"

    arr(1, 0) = "B"
    arr(1, 1) = "2"
    arr(1, 2) = "x"

    arr(2, 0) = "C"
    arr(2, 1) = "3"
    arr(2, 2) = "y"

    arr(3, 0) = "D"
    arr(3, 1) = "4"
    arr(3, 2) = "z"

    Debug.Print "Loop Dimension 1"
    For i = 0 To UBound(arr, 1)
        Debug.Print "arr(" & i & ", 0) is " & arr(i, 0)
    Next i
    Debug.Print ""

    Debug.Print "Loop Dimension 2"
    For j = 0 To UBound(arr, 2)
        Debug.Print "arr(0, " & j & ") is " & arr(0, j)
    Next j
    Debug.Print ""

    Debug.Print "Loop Dimension 1 and 2"
    For i = 0 To UBound(arr, 1)
        For j = 0 To UBound(arr, 2)
            Debug.Print "arr(" & i & ", " & j & ") is " & arr(i, j)
        Next j
    Next i
    Debug.Print ""

End Sub

What are best practices for multi-language database design?

Martin's solution is very similar to mine, however how would you handle a default descriptions when the desired translation isn't found ?

Would that require an IFNULL() and another SELECT statement for each field ?

The default translation would be stored in the same table, where a flag like "isDefault" indicates wether that description is the default description in case none has been found for the current language.

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

Eclipse - java.lang.ClassNotFoundException

We had the exact exception (using SpringSource Tools, tomcat, on Win7) and the cause was that we had refactored a filename (renamed a file) from SubDomain.java to Subdomain.java (D vs d) and somehow it collided though SpringSource was showing the new name Subdomain.java. The solution was to delete the file (via SpringSource) and create it again under the name Subdomain.java and copy-pasting its former content. Simple as that.

Determine if 2 lists have the same elements, regardless of order?

You can simply check whether the multisets with the elements of x and y are equal:

import collections
collections.Counter(x) == collections.Counter(y)

This requires the elements to be hashable; runtime will be in O(n), where n is the size of the lists.

If the elements are also unique, you can also convert to sets (same asymptotic runtime, may be a little bit faster in practice):

set(x) == set(y)

If the elements are not hashable, but sortable, another alternative (runtime in O(n log n)) is

sorted(x) == sorted(y)

If the elements are neither hashable nor sortable you can use the following helper function. Note that it will be quite slow (O(n²)) and should generally not be used outside of the esoteric case of unhashable and unsortable elements.

def equal_ignore_order(a, b):
    """ Use only when elements are neither hashable nor sortable! """
    unmatched = list(b)
    for element in a:
        try:
            unmatched.remove(element)
        except ValueError:
            return False
    return not unmatched

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

Git branching: master vs. origin/master vs. remotes/origin/master

  1. origin - This is a custom and most common name to point to remote.

$ git remote add origin https://github.com/git/git.git --- You will run this command to link your github project to origin. Here origin is user-defined. You can rename it by $ git remote rename old-name new-name


  1. master - The default branch name in Git is master. For both remote and local computer.

  1. origin/master - This is just a pointer to refer master branch in remote repo. Remember i said origin points to remote.

$ git fetch origin - Downloads objects and refs from remote repository to your local computer [origin/master]. That means it will not affect your local master branch unless you merge them using $ git merge origin/master. Remember to checkout the correct branch where you need to merge before run this command

Note: Fetched content is represented as a remote branch. Fetch gives you a chance to review changes before integrating them into your copy of the project. To show changes between yours and remote $git diff master..origin/master

getting JRE system library unbound error in build path

I too faced the same issue. I followed the following steps to resolve my issue -

  • Right click on your project -> Properties
  • Select Java Build Path in the left menu
  • Select Libraries tab
  • Under the module path, select the troublesome JRE entry
  • Click on Edit button
  • Select Workspace default JRE.
  • Click on Finish button

If the above steps don't work for you, instead of Workspace default JRE, you can choose an Alternate JRE and give the path to the JRE that you want to point.

How to apply bold text style for an entire row using Apache POI?

This worked for me

    Object[][] bookData = { { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 },
            { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 } };

    String[] headers = new String[] { "HEader 1", "HEader 2", "HEader 3" };

    int noOfColumns = headers.length;
    int rowCount = 0;

    Row rowZero = sheet.createRow(rowCount++);
    CellStyle style = workbook.createCellStyle();
    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style.setFont(font);
    for (int col = 1; col <= noOfColumns; col++) {
        Cell cell = rowZero.createCell(col);
        cell.setCellValue(headers[col - 1]);
        cell.setCellStyle(style);
    }

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

INSERT INTO mytable(col1,col2) 
    SELECT 'val1','val2' 
    WHERE NOT EXISTS (SELECT 1 FROM mytable WHERE col1='val1')

Copy tables from one database to another in SQL Server

  1. Script the create table in management studio, run that script in bar to create the table. (Right click table in object explorer, script table as, create to...)

  2. INSERT bar.[schema].table SELECT * FROM foo.[schema].table

Can I return the 'id' field after a LINQ insert?

Try this:

MyContext Context = new MyContext(); 
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;

not-null property references a null or transient value

Check the unsaved values for your primary key/Object ID in your hbm files. If you have automated ID creation by hibernate framework and you are setting the ID somewhere it will throw this error.By default the unsaved value is 0, so if you set the ID to 0 you will see this error.

SQL Stored Procedure: If variable is not null, update statement

Another approach when you have many updates would be to use COALESCE:

UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET    
    [ABC]  = COALESCE(@ABC, [ABC]),
    [ABCD] = COALESCE(@ABCD, [ABCD])

How to Deep clone in javascript

Use immutableJS

import { fromJS } from 'immutable';

// An object we want to clone
let objA = { 
   a: { deep: 'value1', moreDeep: {key: 'value2'} } 
};

let immB = fromJS(objA); // Create immutable Map
let objB = immB.toJS(); // Convert to plain JS object

console.log(objA); // Object { a: { deep: 'value1', moreDeep: {key: 'value2'} } }
console.log(objB); // Object { a: { deep: 'value1', moreDeep: {key: 'value2'} } }

// objA and objB are equalent, but now they and their inner objects are undependent
console.log(objA === objB); // false
console.log(objA.a === objB.a); // false
console.log(objA.moreDeep === objB.moreDeep); // false

Or lodash/merge

import merge from 'lodash/merge'

var objA = {
    a: [{ 'b': 2 }, { 'd': 4 }]
};
// New deeply cloned object:
merge({}, objA ); 

// We can also create new object from several objects by deep merge:
var objB = {
    a: [{ 'c': 3 }, { 'e': 5 }]
};
merge({}, objA , objB ); // Object { a: [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

How to calculate the time interval between two time strings

    import datetime
    
    day = int(input("day[1,2,3,..31]: "))
    month = int(input("Month[1,2,3,...12]: "))
    year = int(input("year[0~2020]: "))
    start_date = datetime.date(year, month, day)
    
    day = int(input("day[1,2,3,..31]: "))
    month = int(input("Month[1,2,3,...12]: "))
    year = int(input("year[0~2020]: "))
    end_date = datetime.date(year, month, day)
    
    time_difference = end_date - start_date
    age = time_difference.days
    print("Total days: " + str(age))

CSS no text wrap

Additionally to overflow:hidden, use

white-space:nowrap;

Is there a method to generate a UUID with go language

There is an official implementation by Google: https://github.com/google/uuid

Generating a version 4 UUID works like this:

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    id := uuid.New()
    fmt.Println(id.String())
}

Try it here: https://play.golang.org/p/6YPi1djUMj9

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

If first variable($a) is null, then assign value of second variable($b) to first variable($a)

 $a = 5;
 $b = 10;   

 $a != ''?$a: $a = $b;

 echo $a;

WPF Binding to parent DataContext

Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).

If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel

public class ThisViewModel : ViewModelBase
{
    TypeOfAncestorViewModel Parent { get; set; }
}

and bind against that directly instead.

<TextBox Text="{Binding Parent}" />

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You are using str methods on an open file object.

You can read the file as a list of lines by simply calling list() on the file object:

with open('goodlines.txt') as f:
    mylist = list(f)

This does include the newline characters. You can strip those in a list comprehension:

with open('goodlines.txt') as f:
    mylist = [line.rstrip('\n') for line in f]

Can I get image from canvas element and use it in img src tag?

Do this. Add this to the bottom of your doc just before you close the body tag.

<script>
    function canvasToImg() {
      var canvas = document.getElementById("yourCanvasID");
      var ctx=canvas.getContext("2d");
      //draw a red box
      ctx.fillStyle="#FF0000";
      ctx.fillRect(10,10,30,30);

      var url = canvas.toDataURL();

      var newImg = document.createElement("img"); // create img tag
      newImg.src = url;
      document.body.appendChild(newImg); // add to end of your document
    }

    canvasToImg(); //execute the function
</script>

Of course somewhere in your doc you need the canvas tag that it will grab.

<canvas id="yourCanvasID" />

How to kill/stop a long SQL query immediately?

This is kind of a silly answer, but it works reliably at least in my case: In management studio, when the "Cancel Executing Query" doesn't stop the query I just click to close the current sql document. it asks me if I want to cancel the query, I say yes, and lo and behold in a few seconds it stops executing. After that it asks me if I want to save the document before closing. At this point I can click Cancel to keep the document open and continue working. No idea what's going on behind the scenes, but it seems to work.

Set session variable in laravel

I think your question ultimately can be boiled down to this:

Where can I set a long-lived value that is accessible globally in my application?

The obvious answer is that it depends. What it depends on are a couple of factors:

  • Will the value ever be different, or is it going to be the same for everybody?
  • How long exactly is long-lived? (Forever? A Day? One browsing 'session'?)

Config

If the value is the same for everyone and will seldom change, the best place to probably put it is in a configuration file somewhere underneath app/config, e.g. app/config/companyname.php:

<?php
return [
    'somevalue' => 10,
];

You could access this value from anywhere in your application via Config::get('companyname.somevalue')

Session

If the value you are intending to store is going to be different for each user, the most logical place to put it is in Session. This is what you allude to in your question, but you are using incorrect syntax. The correct syntax to store a variable in Session is:

Session::put('somekey', 'somevalue');

The correct syntax to retrieve it back out later is:

Session::get('somekey');

As far as when to perform these operations, that's a little up to you. I would probably choose a route filter if on Laravel 4.x or Middleware if using Laravel 5. Below is an example of using a route filter that leverages another class to actually come up with the value:

// File: ValueMaker.php (saved in some folder that can be autoloaded)
class ValueMaker
{
    public function makeValue()
    {
        return 42;
    }
}

// File: app/filters.php is probably the best place
Route::filter('set_value', function() {
    $valueMaker = app()->make('ValueMaker');
    Session::put('somevalue', $valueMaker->makeValue());
});

// File: app/routes.php
Route::group(['before' => 'set_value'], function() {
   // Value has already been 'made' by this point. 
   return View::make('view')
       ->with('value', Session::get('somevalue'))
   ;
});

How to validate a url in Python? (Malformed or not)

django url validation regex (source):

import re
regex = re.compile(
        r'^(?:http|ftp)s?://' # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
        r'localhost|' #localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
        r'(?::\d+)?' # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)

print(re.match(regex, "http://www.example.com") is not None) # True
print(re.match(regex, "example.com") is not None)            # False

Pandas - Get first row value of a given column

  1. df.iloc[0].head(1) - First data set only from entire first row.
  2. df.iloc[0] - Entire First row in column.

How to efficiently build a tree from a flat structure?

Store IDs of the objects in a hash table mapping to the specific object. Enumerate through all the objects and find their parent if it exists and update its parent pointer accordingly.

class MyObject
{ // The actual object
    public int ParentID { get; set; }
    public int ID { get; set; }
}

class Node
{
    public List<Node> Children = new List<Node>();
    public Node Parent { get; set; }
    public MyObject AssociatedObject { get; set; }
}

IEnumerable<Node> BuildTreeAndGetRoots(List<MyObject> actualObjects)
{
    Dictionary<int, Node> lookup = new Dictionary<int, Node>();
    actualObjects.ForEach(x => lookup.Add(x.ID, new Node { AssociatedObject = x }));
    foreach (var item in lookup.Values) {
        Node proposedParent;
        if (lookup.TryGetValue(item.AssociatedObject.ParentID, out proposedParent)) {
            item.Parent = proposedParent;
            proposedParent.Children.Add(item);
        }
    }
    return lookup.Values.Where(x => x.Parent == null);
}

How to remove numbers from a string?

Very close, try:

questionText = questionText.replace(/[0-9]/g, '');

replace doesn't work on the existing string, it returns a new one. If you want to use it, you need to keep it!
Similarly, you can use a new variable:

var withNoDigits = questionText.replace(/[0-9]/g, '');

One last trick to remove whole blocks of digits at once, but that one may go too far:

questionText = questionText.replace(/\d+/g, '');

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

If you are getting this message from a Maven built war change the scope of the JDBC driver to provided, and put a copy of it in the lib directory. Like this:

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.18</version>
  <!-- put a copy in /usr/share/tomcat7/lib -->
  <scope>provided</scope>
</dependency>

How to enumerate an enum

What if you know the type will be an enum, but you don't know what the exact type is at compile time?

public class EnumHelper
{
    public static IEnumerable<T> GetValues<T>()
    {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }

    public static IEnumerable getListOfEnum(Type type)
    {
        MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod("GetValues").MakeGenericMethod(type);
        return (IEnumerable)getValuesMethod.Invoke(null, null);
    }
}

The method getListOfEnum uses reflection to take any enum type and returns an IEnumerable of all enum values.

Usage:

Type myType = someEnumValue.GetType();

IEnumerable resultEnumerable = getListOfEnum(myType);

foreach (var item in resultEnumerable)
{
    Console.WriteLine(String.Format("Item: {0} Value: {1}",item.ToString(),(int)item));
}

How to add a class to a given element?

If you're only targeting modern browsers:

Use element.classList.add to add a class:

element.classList.add("my-class");

And element.classList.remove to remove a class:

element.classList.remove("my-class");

If you need to support Internet Explorer 9 or lower:

Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.

<div id="div1" class="someclass">
    <img ... id="image1" name="image1" />
</div>

Then

var d = document.getElementById("div1");
d.className += " otherclass";

Note the space before otherclass. It's important to include the space otherwise it compromises existing classes that come before it in the class list.

See also element.className on MDN.

Error related to only_full_group_by when executing a query in MySql

If you don't want to make any changes in your current query then follow the below steps -

  1. vagrant ssh into your box
  2. Type: sudo vim /etc/mysql/my.cnf
  3. Scroll to the bottom of file and type A to enter insert mode
  4. Copy and paste

    [mysqld]
    sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
    
  5. Type esc to exit input mode

  6. Type :wq to save and close vim.
  7. Type sudo service mysql restart to restart MySQL.

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

There is a difference.

When the ^ character appears outside of [] matches the beginning of the line (or string). When the ^ character appears inside the [], it matches any character not appearing inside the [].

Can't connect to localhost on SQL Server Express 2012 / 2016

After doing the steps which were mentioned by @Ravindra Bagale, Try this step. Server name: localhost\{Instance name you were gave}

enter image description here

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

Java Read Large Text File With 70million line of text

In Java 8, for anyone looking now to read file large files line by line,

Stream<String> lines = Files.lines(Paths.get("c:\myfile.txt"));
lines.forEach(l -> {
  // Do anything line by line   
});

Output data with no column headings using PowerShell

If you use "format-table" you can use -hidetableheaders

Android update activity UI from service

I would recommend checking out Otto, an EventBus tailored specifically to Android. Your Activity/UI can listen to events posted on the Bus from the Service, and decouple itself from the backend.

select count(*) from table of mysql in php

With mysql v5.7.20, here is how I was able to get the row count from a table using PHP v7.0.22:

$query = "select count(*) from bigtable";
$qresult = mysqli_query($this->conn, $query);
$row = mysqli_fetch_assoc($qresult);
$count = $row["count(*)"];
echo $count;

The third line will return a structure that looks like this:

array(1) {
   ["count(*)"]=>string(4) "1570"
}

In which case the ending echo statement will return:

1570

How to pass values across the pages in ASP.net without using Session

You can assign it to a hidden field, and retrieve it using

var value= Request.Form["value"]

Composer could not find a composer.json

The "Getting Started" page is the introduction to the documentation. Most documentation will start off with installation instructions, just like Composer's do.

The page that contains information on the composer.json file is located here - under "Basic Usage", the second page.

I'd recommend reading over the documentation in full, so that you gain a better understanding of how to use Composer. I'd also recommend removing what you have and following the installation instructions provided in the documentation.

Quotation marks inside a string

You need to escape the quotation marks:

String name = "\"john\"";

How to create a stopwatch using JavaScript?

jsbin.com demo

You'll see the demo code is just a start/stop/reset millisecond counter. If you want to do fanciful formatting on the time, that's completely up to you. This should be more than enough to get you started.

This was a fun little project to work on. Here's how I'd approach it

var Stopwatch = function(elem, options) {

  var timer       = createTimer(),
      startButton = createButton("start", start),
      stopButton  = createButton("stop", stop),
      resetButton = createButton("reset", reset),
      offset,
      clock,
      interval;

  // default options
  options = options || {};
  options.delay = options.delay || 1;

  // append elements     
  elem.appendChild(timer);
  elem.appendChild(startButton);
  elem.appendChild(stopButton);
  elem.appendChild(resetButton);

  // initialize
  reset();

  // private functions
  function createTimer() {
    return document.createElement("span");
  }

  function createButton(action, handler) {
    var a = document.createElement("a");
    a.href = "#" + action;
    a.innerHTML = action;
    a.addEventListener("click", function(event) {
      handler();
      event.preventDefault();
    });
    return a;
  }

  function start() {
    if (!interval) {
      offset   = Date.now();
      interval = setInterval(update, options.delay);
    }
  }

  function stop() {
    if (interval) {
      clearInterval(interval);
      interval = null;
    }
  }

  function reset() {
    clock = 0;
    render();
  }

  function update() {
    clock += delta();
    render();
  }

  function render() {
    timer.innerHTML = clock/1000; 
  }

  function delta() {
    var now = Date.now(),
        d   = now - offset;

    offset = now;
    return d;
  }

  // public API
  this.start  = start;
  this.stop   = stop;
  this.reset  = reset;
};

Get some basic HTML wrappers for it

<!-- create 3 stopwatches -->
<div class="stopwatch"></div>
<div class="stopwatch"></div>
<div class="stopwatch"></div>

Usage is dead simple from there

var elems = document.getElementsByClassName("stopwatch");

for (var i=0, len=elems.length; i<len; i++) {
  new Stopwatch(elems[i]);
}

As a bonus, you get a programmable API for the timers as well. Here's a usage example

var elem = document.getElementById("my-stopwatch");
var timer = new Stopwatch(elem, {delay: 10});

// start the timer
timer.start();

// stop the timer
timer.stop();

// reset the timer
timer.reset();

jQuery plugin

As for the jQuery portion, once you have nice code composition as above, writing a jQuery plugin is easy mode

(function($) {

  var Stopwatch = function(elem, options) {
    // code from above...
  };

  $.fn.stopwatch = function(options) {
    return this.each(function(idx, elem) {
      new Stopwatch(elem, options);
    });
  };
})(jQuery);

jQuery plugin usage

// all elements with class .stopwatch; default delay (1 ms)
$(".stopwatch").stopwatch();

// a specific element with id #my-stopwatch; custom delay (10 ms)
$("#my-stopwatch").stopwatch({delay: 10});

Convert output of MySQL query to utf8

You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html

SELECT column1, CONVERT(column2 USING utf8)
FROM my_table 
WHERE my_condition;

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

I faced similar issue with Spring MVC application. I used < mvc:resources > tag to resolve this issue.

Please find the following link having more details.

http://www.mkyong.com/spring-mvc/spring-mvc-how-to-include-js-or-css-files-in-a-jsp-page/

Java rounding up to an int using Math.ceil

int total = (int) Math.ceil( (double)157/ (double) 32);

What is the best way to remove accents (normalize) in a Python unicode string?

perfplot

import unicodedata
from random import choice

import perfplot
import regex
import text_unidecode


def remove_accent_chars_regex(x: str):
    return regex.sub(r'\p{Mn}', '', unicodedata.normalize('NFKD', x))


def remove_accent_chars_join(x: str):
    # answer by MiniQuark
    # https://stackoverflow.com/a/517974/7966259
    return u"".join([c for c in unicodedata.normalize('NFKD', x) if not unicodedata.combining(c)])


perfplot.show(
    setup=lambda n: ''.join([choice('Málaga François Phút Hon ??') for i in range(n)]),
    kernels=[
        remove_accent_chars_regex,
        remove_accent_chars_join,
        text_unidecode.unidecode,
    ],
    labels=['regex', 'join', 'unidecode'],
    n_range=[2 ** k for k in range(22)],
    equality_check=None, relative_to=0, xlabel='str len'
)

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

How to undo a SQL Server UPDATE query?

If you already have a full backup from your database, fortunately, you have an option in SQL Management Studio. In this case, you can use the following steps:

  1. Right click on database -> Tasks -> Restore -> Database.

  2. In General tab, click on Timeline -> select Specific date and time option.

  3. Move the timeline slider to before update command time -> click OK.

  4. In the destination database name, type a new name.

  5. In the Files tab, check in Reallocate all files to folder and then select a new path to save your recovered database.

  6. In the options tab, check in Overwrite ... and remove Take tail-log... check option.

  7. Finally, click on OK and wait until the recovery process is over.

I have used this method myself in an operational database and it was very useful.

Split array into chunks

Super late to the party but I solved a similar problem with the approach of using .join("") to convert the array to one giant string, then using regex to .match(/.{1,7}/) it into arrays of substrings of max length 7.

const arr = ['abc', 'def', 'gh', 'ijkl', 'm', 'nopq', 'rs', 'tuvwx', 'yz'];
const arrayOfSevens = arr.join("").match(/.{1,7}/g);
// ["abcdefg", "hijklmn", "opqrstu", "vwxyz"]

Would be interesting to see how this performs in a speed test against other methods

Symbol for any number of any characters in regex?

I would use .*. . matches any character, * signifies 0 or more occurrences. You might need a DOTALL switch to the regex to capture new lines with ..

Can you write virtual functions / methods in Java?

Can you write virtual functions in Java?

Yes. In fact, all instance methods in Java are virtual by default. Only certain methods are not virtual:

  • Class methods (because typically each instance holds information like a pointer to a vtable about its specific methods, but no instance is available here).
  • Private instance methods (because no other class can access the method, the calling instance has always the type of the defining class itself and is therefore unambiguously known at compile time).

Here are some examples:

"Normal" virtual functions

The following example is from an old version of the wikipedia page mentioned in another answer.

import java.util.*;

public class Animal 
{
   public void eat() 
   { 
      System.out.println("I eat like a generic Animal."); 
   }

   public static void main(String[] args) 
   {
      List<Animal> animals = new LinkedList<Animal>();

      animals.add(new Animal());
      animals.add(new Fish());
      animals.add(new Goldfish());
      animals.add(new OtherAnimal());

      for (Animal currentAnimal : animals) 
      {
         currentAnimal.eat();
      }
   }
}

class Fish extends Animal 
{
   @Override
   public void eat() 
   { 
      System.out.println("I eat like a fish!"); 
   }
}

class Goldfish extends Fish 
{
   @Override
   public void eat() 
   { 
      System.out.println("I eat like a goldfish!"); 
   }
}

class OtherAnimal extends Animal {}

Output:

I eat like a generic Animal.
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.

Example with virtual functions with interfaces

Java interface methods are all virtual. They must be virtual because they rely on the implementing classes to provide the method implementations. The code to execute will only be selected at run time.

For example:

interface Bicycle {         //the function applyBrakes() is virtual because
    void applyBrakes();     //functions in interfaces are designed to be 
}                           //overridden.

class ACMEBicycle implements Bicycle {
    public void applyBrakes(){               //Here we implement applyBrakes()
       System.out.println("Brakes applied"); //function
    }
}

Example with virtual functions with abstract classes.

Similar to interfaces Abstract classes must contain virtual methods because they rely on the extending classes' implementation. For Example:

abstract class Dog {                   
    final void bark() {               //bark() is not virtual because it is 
        System.out.println("woof");   //final and if you tried to override it
    }                                 //you would get a compile time error.

    abstract void jump();             //jump() is a "pure" virtual function 
}                                     
class MyDog extends Dog{
    void jump(){
        System.out.println("boing");    //here jump() is being overridden
    }                                  
}
public class Runner {
    public static void main(String[] args) {
        Dog dog = new MyDog();       // Create a MyDog and assign to plain Dog variable
        dog.jump();                  // calling the virtual function.
                                     // MyDog.jump() will be executed 
                                     // although the variable is just a plain Dog.
    }
}

.htaccess or .htpasswd equivalent on IIS?

I've never used it but Trilead, a free ISAPI filter which enables .htaccess based control, looks like what you want.

Best way to move files between S3 buckets?

The new official AWS CLI natively supports most of the functionality of s3cmd. I'd previously been using s3cmd or the ruby AWS SDK to do things like this, but the official CLI works great for this.

http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html

aws s3 sync s3://oldbucket s3://newbucket

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

document.createElement("script") synchronously

Asynchronous programming is slightly more complicated because the consequence of making a request is encapsulated in a function instead of following the request statement. But the realtime behavior that the user experiences can be significantly better because they will not see a sluggish server or sluggish network cause the browser to act as though it had crashed. Synchronous programming is disrespectful and should not be employed in applications which are used by people.

Douglas Crockford (YUI Blog)

Alright, buckle your seats, because it's going to be a bumpy ride. More and more people ask about loading scripts dynamically via javascript, it seems to be a hot topic.

The main reasons why this became so popular are:

  • client-side modularity
  • easier dependency management
  • error handling
  • performance advantages

About modularity: it is obvious that managing client-side dependencies should be handled right on the client-side. If a certain object, module or library is needed we just ask for it and load it dynamically.

Error handling: if a resource fails we still get the chance to block only the parts that depend on the affected script, or maybe even give it another try with some delay.

Performance has become a competitive edge between websites, it is now a search ranking factor. What dynamic scripts can do is mimic asynchronous behavior as opposed to the default blocking way of how browsers handle scripts. Scripts block other resources, scripts block further parsing of the HTML document, scripts block the UI. Now with dynamic script tags and its cross-browser alternatives you can do real asynchronous requests, and execute dependent code only when they are available. Your scripts will load in-parallel even with other resources and the rendering will be flawless.

The reason why some people stick to synchronous scripting is because they are used to it. They think it is the default way, it is the easier way, and some may even think it is the only way.

But the only thing we should care about when this needs to be decided concerning an applications's design is the end-user experience. And in this area asynchronous cannot be beaten. The user gets immediate responses (or say promises), and a promise is always better than nothing. A blank screen scares people. Developers shouldn't be lazy to enhance perceived performance.

And finally some words about the dirty side. What you should do in order to get it working across browsers:

  1. learn to think asynchronously
  2. organize your code to be modular
  3. organize your code to handle errors and edge cases well
  4. enhance progressively
  5. always take care of the right amount of feedback

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

Check out from dateutil.relativedelta import * for adding a specific amount of time to a date, you can continue to use timedelta for the simple stuff i.e.

use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)

or you can start using relativedelta

use_date = use_date+relativedelta(months=+1)

use_date = use_date+relativedelta(years=+1)

for the last day of next month:

use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)

Right now this will provide 29/02/2016

for the penultimate day of next month:

use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)

last Friday of the next month:

use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))

2nd Tuesday of next month:

new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))

As @mrroot5 points out dateutil's rrule functions can be applied, giving you an extra bang for your buck, if you require date occurences.
for example:
Calculating the last day of the month for 9 months from the last day of last month.
Then, calculate the 2nd Tuesday for each of those months.

from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import datetime
use_date = datetime(2020,11,21)

#Calculate the last day of last month
use_date = use_date+relativedelta(months=-1)
use_date = use_date+relativedelta(day=31)

#Generate a list of the last day for 9 months from the calculated date
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, bymonthday=(-1,)))
print("Last day")
for ld in x:
    print(ld)

#Generate a list of the 2nd Tuesday in each of the next 9 months from the calculated date
print("\n2nd Tuesday")
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, byweekday=TU(2)))
for tuesday in x:
    print(tuesday)

Last day
2020-10-31 00:00:00
2020-11-30 00:00:00
2020-12-31 00:00:00
2021-01-31 00:00:00
2021-02-28 00:00:00
2021-03-31 00:00:00
2021-04-30 00:00:00
2021-05-31 00:00:00
2021-06-30 00:00:00

2nd Tuesday
2020-11-10 00:00:00
2020-12-08 00:00:00
2021-01-12 00:00:00
2021-02-09 00:00:00
2021-03-09 00:00:00
2021-04-13 00:00:00
2021-05-11 00:00:00
2021-06-08 00:00:00
2021-07-13 00:00:00

This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/

Where is Developer Command Prompt for VS2013?

From VS2013 Menu Select "Tools", then Select "External Tools". Enter as below:

  • Title: "VS2013 Native Tools-Command Prompt" would be good
  • Command: C:\Windows\System32\cmd.exe
  • Arguments: /k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat"
  • Initial Directory: Select as suits your needs.

Click OK. Now you have command prompt access under the Tools Menu.

Does it make sense to use Require.js with Angular.js?

Answer from Brian Ford

AngularJS has it's own module system an typically doesn't need something like RJS.

Reference: https://github.com/yeoman/generator-angular/issues/40

Making a div vertically scrollable using CSS

For 100% viewport height use:

overflow: auto;
max-height: 100vh;

Make ABC Ordered List Items Have Bold Style

Are you sure you correctly applied the styles, or that there isn't another stylesheet interfering with your lists? I tried this:

<ol type="A">
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
</ol>

Then in the stylesheet:

ol {font-weight: bold;}
ol li span.label {font-weight:normal;}

And it bolded the A, B, C etc and not the text.

(Tested it in Opera 9.6, FF 3, Safari 3.2 and IE 7)

Host binding and Host listening

This is the simple example to use both of them:

import {
  Directive, HostListener, HostBinding
}
from '@angular/core';

@Directive({
  selector: '[Highlight]'
})
export class HighlightDirective {
  @HostListener('mouseenter') mouseover() {
    this.backgroundColor = 'green';
  };

  @HostListener('mouseleave') mouseleave() {
    this.backgroundColor = 'white';
  }

  @HostBinding('style.backgroundColor') get setColor() {
     return this.backgroundColor;
  };

  private backgroundColor = 'white';
  constructor() {}

}

Introduction:

  1. HostListener can bind an event to the element.

  2. HostBinding can bind a style to the element.

  3. this is directive, so we can use it for

    Some Text
  4. So according to the debug, we can find that this div has been binded style = "background-color:white"

    Some Text
  5. we also can find that EventListener of this div has two event: mouseenter and mouseleave. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.

Delete branches in Bitbucket

For deleting branch from Bitbucket,

  1. Go to Overview (Your repository > branches in the left sidebar)
  2. Click the number of branches (that should show you the list of branches)
  3. Click on the branch that you want to delete
  4. On top right corner, click the 3 dots (besides Merge button).
  5. There is the option of "Delete Branch" if you have rights.

How to convert a python numpy array to an RGB image with Opencv 2.4?

The images c, d, e , and f in the following show colorspace conversion they also happen to be numpy arrays <type 'numpy.ndarray'>:

import numpy, cv2
def show_pic(p):
        ''' use esc to see the results'''
        print(type(p))
        cv2.imshow('Color image', p)
        while True:
            k = cv2.waitKey(0) & 0xFF
            if k == 27: break 
        return
        cv2.destroyAllWindows()

b = numpy.zeros([200,200,3])

b[:,:,0] = numpy.ones([200,200])*255
b[:,:,1] = numpy.ones([200,200])*255
b[:,:,2] = numpy.ones([200,200])*0
cv2.imwrite('color_img.jpg', b)


c = cv2.imread('color_img.jpg', 1)
c = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)

d = cv2.imread('color_img.jpg', 1)
d = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)

e = cv2.imread('color_img.jpg', -1)
e = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)

f = cv2.imread('color_img.jpg', -1)
f = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)


pictures = [d, c, f, e]

for p in pictures:
        show_pic(p)
# show the matrix
print(c)
print(c.shape)

See here for more info: http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor

OR you could:

img = numpy.zeros([200,200,3])

img[:,:,0] = numpy.ones([200,200])*255
img[:,:,1] = numpy.ones([200,200])*255
img[:,:,2] = numpy.ones([200,200])*0

r,g,b = cv2.split(img)
img_bgr = cv2.merge([b,g,r])

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

How to click an element in Selenium WebDriver using JavaScript

Executing a click via JavaScript has some behaviors of which you should be aware. If for example, the code bound to the onclick event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.

// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

I updated my iPhone to the latest version 11.0.3, then restarted my iPhone. Restarted my XCode 9. Then it worked.

JavaScript Chart Library

Check out Google Visualization API, which is kind of a generalization of the simpler Chart API

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

How to merge multiple dicts with same key or different key?

dict1 = {'m': 2, 'n': 4}
dict2 = {'n': 3, 'm': 1}

Making sure that the keys are in the same order:

dict2_sorted = {i:dict2[i] for i in dict1.keys()}

keys = dict1.keys()
values = zip(dict1.values(), dict2_sorted.values())
dictionary = dict(zip(keys, values))

gives:

{'m': (2, 1), 'n': (4, 3)}

How to install Android SDK on Ubuntu?

If you are on Ubuntu 17.04 (Zesty), and you literally just need the SDK (no Android Studio), you can install it like on Debian:

  • sudo apt install android-sdk android-sdk-platform-23
  • export ANDROID_HOME=/usr/lib/android-sdk
  • In build.gradle, change compileSdkVersion to 23 and buildToolsVersion to 24.0.0
  • run gradle build

When to use reinterpret_cast?

Read the FAQ! Holding C++ data in C can be risky.

In C++, a pointer to an object can be converted to void * without any casts. But it's not true the other way round. You'd need a static_cast to get the original pointer back.

Getting list of parameter names inside python function

Well we don't actually need inspect here.

>>> func = lambda x, y: (x, y)
>>> 
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
...  print(func2.__code__.co_varnames)
...  pass # Other things
... 
>>> func2(3,3)
('x', 'y')
>>> 
>>> func2.__defaults__
(3,)

For Python 2.5 and older, use func_code instead of __code__, and func_defaults instead of __defaults__.

How do I create an .exe for a Java program?

Launch4j perhaps? Can't say I've used it myself, but it sounds like what you're after.

Change SQLite database mode to read-write

From the command line, enter the folder where your database file is located and execute the following command:

chmod 777 databasefilename

This will grant all permissions to all users.

Link entire table row?

To link the entire row, you need to define onclick function on your row, which is <tr>element and define a mouse hover in the CSS for tr element to make the mouse pointer to a typical click-hand in web:

In table:

<tr onclick="location.href='http://www.google.com'">
<td>blah</td>
<td>blah</td>
<td><strong>Text</strong></td>
</tr>

In related CSS:

tr:hover {
cursor: pointer;
}

Action bar navigation modes are deprecated in Android L

FragmentTabHost is also an option.

This code is from Android developer's site:

/**
 * This demonstrates how you can implement switching between the tabs of a
 * TabHost through fragments, using FragmentTabHost.
 */
public class FragmentTabs extends FragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.fragment_tabs);
    mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

    mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
            FragmentStackSupport.CountingFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
            LoaderCursorSupport.CursorLoaderListFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
            LoaderCustomSupport.AppListFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
            LoaderThrottleSupport.ThrottledLoaderListFragment.class, null);
    }
}

How to lose margin/padding in UITextView?

Up-to-date for 2021

It is one of the silliest bugs in iOS.

The class given here, UITextViewFixed , is used widely, and is usually the most reasonable solution overall.

Here is the class:

@IBDesignable class UITextViewFixed: UITextView {
    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }
    func setup() {
        textContainerInset = UIEdgeInsets.zero
        textContainer.lineFragmentPadding = 0
    }
}

Don't forget to turn off scrollEnabled in the Inspector!

  1. The solution works properly in storyboard

  2. The solution works properly at runtime

That's it, you're done.

In general, that should be all you need in most cases.

Even if you are changing the height of the text view on the fly, UITextViewFixed usually does all you need.

(A common example of changing the height on the fly, is changing it as the user types.)

Here is the broken UITextView from Apple...

screenshot of IB with UITextView

Here is UITextViewFixed:

screenshot of IB with UITextViewFixed

Note that of course you must...

...turn off scrollEnabled in the Inspector!

(Turning on scrollEnabled means "make this view expand as much as possible vertically by expanding the bottom margin as much as possible.")


Some further issues

(1) In some very unusual cases dynamically changing heights, Apple does a bizarre thing: they add extra space at the bottom.

No, really! This would have to be one of the most infuriating things in iOS.

If you encounter the problem, here is a "quick fix" which usually helps:

...
        textContainerInset = UIEdgeInsets.zero
        textContainer.lineFragmentPadding = 0
       
        // this is not ideal, but sometimes this "quick fix"
        // will solve the "extra space at the bottom" insanity:
        var b = bounds
        let h = sizeThatFits(CGSize(
           width: bounds.size.width,
           height: CGFloat.greatestFiniteMagnitude)
       ).height
       b.size.height = h
       bounds = b
 ...

(2) In rare cases, to fix yet another subtle mess-up by Apple, you have to add:

override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) {
    super.setContentOffset(contentOffset, animated: false) // sic
}

(3) Arguably, we should be adding :

contentInset = UIEdgeInsets.zero

just after .lineFragmentPadding = 0 in UITextViewFixed .

However ... believe or not ... that just doesn't work in current iOS! (Checked 2021.) It may be necessary to add that line in the future.

The fact that UITextView is broken in iOS is one of the weirdest things in all of mobile computing. Ten year anniversary of this question and it's still not fixed!

Finally, here's a somewhat similar tip for TextField: https://stackoverflow.com/a/43099816/294884

Completely random tip: how to add the "..." on the end

Often you are using a UITextView "like a UILabel". So you want it to truncate text using an ellipsis "..."

If so, add:

 textContainer.lineBreakMode = .byTruncatingTail

Handy tip if you want zero height, when, there's no text at all

Often you use a text view to only display text. So, you use lines "0" to mean the text view will automatically change height depending on how many lines of text.

That's great. But if there is no text at all, then unfortunately you get the same height as if there is one line of text!!!! The text view never "goes away".

enter image description here

If you want it to "go away", just add this

override var intrinsicContentSize: CGSize {
    var i = super.intrinsicContentSize
    print("for \(text) size will be \(i)")
    if text == "" { i.height = 1.0 }
    print("   but we changed it to \(i)")
    return i
}

enter image description here

(I made it '1' height so it's clear what's going on in that demo, '0' is fine.)

What about UILabel ?

When just displaying text, UILabel has many advantages over UITextView. UILabel does not suffer from the problems described on this QA page.

Indeed the reason we all usually "give up" and just use UITextView is that UILabel is difficult to work with. In particular it is ridiculously difficult to just add padding, correctly, to UILabel.

In fact here is a full discussion on how to "finally" correctly add padding to UILabel: https://stackoverflow.com/a/58876988/294884 In some cases if you are doing a difficult layout with dynamic height cells, it is sometimes better to do it the hard way with UILabel.