Programs & Examples On #Epub

EPUB (short for electronic publication) is an open XML-based digital book format which uses XHTML and CSS for document content.

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

The term "Add-Migration" is not recognized

same issue...resolved by dong the following

1.) close pm manager 2.) close Visual Studio 3.) Open Visual Studio 4.) Open pm manager

seems the trick is to close PM Manager before closing VS

Android 6.0 Marshmallow. Cannot write to SD Card

Right. So I've finally got to the bottom of the problem: it was a botched in-place OTA upgrade.

My suspicions intensified after my Garmin Fenix 2 wasn't able to connect via bluetooth and after googling "Marshmallow upgrade issues". Anyway, a "Factory reset" fixed the issue.

Surprisingly, the reset did not return the phone to the original Kitkat; instead, the wipe process picked up the OTA downloaded 6.0 upgrade package and ran with it, resulting (I guess) in a "cleaner" upgrade.

Of course, this meant that the phone lost all the apps that I'd installed. But, freshly installed apps, including mine, work without any changes (i.e. there is backward compatibility). Whew!

Could not load the Tomcat server configuration

You can install tomcat7 in ~/tomcat7 instead of /usr/share/tomcat7.

  1. Close Eclipse.
  2. Delete org.eclipse.wst.server.core.prefs and org.eclipse.jst.server.tomcat.core.prefs in {workspace-directory}/.metadata/.plugins/org.eclipse.core.runtime/.settings.
  3. Launch Eclipse.
  4. Go to Window->Show View->Other... and choose the Servers.
  5. Select Tomcat v7.0 Server from the server type and press Next.
  6. Enter /home/user/tomcat7 (not /usr/share/tomcat7) into the "Tomcat installation directory" and press Download.
  7. Wait a few minutes and press Finish.

tomcat7 worked correctly with Eclipse 4.4 on my Ubuntu 15.04 in this way.

How to make a view with rounded corners?

Jaap van Hengstum's answer works great however I think it is expensive and if we apply this method on a Button for example, the touch effect is lost since the view is rendered as a bitmap.

For me the best method and the simplest one consists in applying a mask on the view, like that:

@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
    super.onSizeChanged(width, height, oldWidth, oldHeight);

    float cornerRadius = <whatever_you_want>;
    this.path = new Path();
    this.path.addRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, Path.Direction.CW);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    if (this.path != null) {
        canvas.clipPath(this.path);
    }
    super.dispatchDraw(canvas);
}

pip is not able to install packages correctly: Permission denied error

On a Mac, you need to use this command:

STATIC_DEPS=true sudo pip install lxml

How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();

Exploits of a Mom

(xkcd)

Left Join without duplicate rows from left table

Using the DISTINCT flag will remove duplicate rows.

SELECT DISTINCT
C.Content_ID,
C.Content_Title,
M.Media_Id

FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
ORDER BY C.Content_DatePublished ASC

Android Open External Storage directory(sdcard) for storing file

Complementing rijul gupta answer:

String strSDCardPath = System.getenv("SECONDARY_STORAGE");

    if ((strSDCardPath == null) || (strSDCardPath.length() == 0)) {
        strSDCardPath = System.getenv("EXTERNAL_SDCARD_STORAGE");
    }

    //If may get a full path that is not the right one, even if we don't have the SD Card there. 
    //We just need the "/mnt/extSdCard/" i.e and check if it's writable
    if(strSDCardPath != null) {
        if (strSDCardPath.contains(":")) {
            strSDCardPath = strSDCardPath.substring(0, strSDCardPath.indexOf(":"));
        }
        File externalFilePath = new File(strSDCardPath);

        if (externalFilePath.exists() && externalFilePath.canWrite()){
            //do what you need here
        }
    }

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

In my case I had to delete the services in my installshield project and start from square one. My original service components were added manually and I couldn't get them working, the only error I was getting was the same "Error 1920 service failed to start. Verify that you have sufficient privileges to start system services." that you were getting. After deleting my components, I re-added them using the component wizard.
enter image description here

Component Wizard looks like this

I actually had to create two new components. One was of type "Install Service".

Service Component type shown here

enter image description here

The other component I had to add was of "Control Service" type.

enter image description here

I had to choose the service that I had setup when I added the Install Service component.enter image description here

After that it worked, even though nothing looked differently from the components I had added manually. Installshield must do something behind the scenes when it wires up the service components with the component wizard.

All of this was with Install Shield 2016.

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

Also try aspnet_regiis -u then aspnet_regiis -i on below path

C:\Windows\Microsoft.NET\Framework\v4.0.30319 

Now restart the IIS and check

Hope this will help !

How to read .pem file to get private and public key

Java 9+:

private byte[] loadPEM(String resource) throws IOException {
    URL url = getClass().getResource(resource);
    InputStream in = url.openStream();
    String pem = new String(in.readAllBytes(), StandardCharsets.ISO_8859_1);
    Pattern parse = Pattern.compile("(?m)(?s)^---*BEGIN.*---*$(.*)^---*END.*---*$.*");
    String encoded = parse.matcher(pem).replaceFirst("$1");
    return Base64.getMimeDecoder().decode(encoded);
}

@Test
public void test() throws Exception {
    KeyFactory kf = KeyFactory.getInstance("RSA");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    PrivateKey key = kf.generatePrivate(new PKCS8EncodedKeySpec(loadPEM("test.key")));
    PublicKey pub = kf.generatePublic(new X509EncodedKeySpec(loadPEM("test.pub")));
    Certificate crt = cf.generateCertificate(getClass().getResourceAsStream("test.crt"));
}

Java 8:

replace the in.readAllBytes() call with a call to this:

byte[] readAllBytes(InputStream in) throws IOException {
    ByteArrayOutputStream baos= new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    for (int read=0; read != -1; read = in.read(buf)) { baos.write(buf, 0, read); }
    return baos.toByteArray();
}

thanks to Daniel for noticing API compatibility issues

annotation to make a private method public only for test classes

An article on Testing Private Methods lays out some approaches to testing private code. using reflection puts extra burden on the programmer to remember if refactoring is done, the strings aren't automatically changed, but I think it's the cleanest approach.

how to check if List<T> element contains an item with a Particular Property Value

bool contains = pricePublicList.Any(p => p.Size == 200);

mysql server port number

if you want to have your port as a variable, you can write php like this:

$username = user;
$password = pw;
$host = 127.0.0.1;
$database = dbname;
$port = 3308; 

$conn = mysql_connect($host.':'.$port, $username, $password);
$db=mysql_select_db($database,$conn);

How do I add more members to my ENUM-type column in MySQL?

FYI: A useful simulation tool - phpMyAdmin with Wampserver 3.0.6 - Preview SQL: I use 'Preview SQL' to see the SQL code that would be generated before you save the column with the change to ENUM. Preview SQL

Above you see that I have entered 'Ford','Toyota' into the ENUM but I am getting syntax ENUM(0) which is generating syntax error Query error 1064#

I then copy and paste and alter the SQL and run it through SQL with a positive result.

SQL changed

This is a quickfix that I use often and can also be used on existing ENUM values that need to be altered. Thought this might be useful.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it.

However, there are other considerations at play here too.

Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads.

Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership).

If you refer to classic VxWorks RTOS kernel, they define three mechanisms:

  • mutex - supports recursion, and optionally priority inheritance. This mechanism is commonly used to protect critical sections of data in a coherent manner.
  • binary semaphore - no recursion, no inheritance, simple exclusion, taker and giver does not have to be same thread, broadcast release available. This mechanism can be used to protect critical sections, but is also particularly useful for coherent signalling or synchronization between threads.
  • counting semaphore - no recursion or inheritance, acts as a coherent resource counter from any desired initial count, threads only block where net count against the resource is zero.

Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play.

Rename master branch for both local and remote Git repositories

You may do the following:

git -m master master-old #rename current master
git checkout -b master   #create a new branch master
git push -f origin master #force push to master

But force pushing is a bad idea if other people are sharing this repository. Force push will cause their revision history to conflict with the new one.

How to detect duplicate values in PHP array?

To get rid use array_unique(). To detect if have any use count(array_unique()) and compare to count($array).

Number of times a particular character appears in a string

You can do it inline, but you have to be careful with spaces in the column data. Better to use datalength()

SELECT 
  ColName, 
  DATALENGTH(ColName) -
  DATALENGTH(REPLACE(Col, 'A', '')) AS NumberOfLetterA
FROM ColName;

-OR- Do the replace with 2 characters

SELECT 
  ColName, 
  -LEN(ColName)
  +LEN(REPLACE(Col, 'A', '><')) AS NumberOfLetterA
FROM ColName;

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

The operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value.

Examples:

1 === 1: true
1 == 1: true
1 === "1": false // 1 is an integer, "1" is a string
1 == "1": true // "1" gets casted to an integer, which is 1
"foo" === "foo": true // both operands are strings and have the same value

Warning: two instances of the same class with equivalent members do NOT match the === operator. Example:

$a = new stdClass();
$a->foo = "bar";
$b = clone $a;
var_dump($a === $b); // bool(false)

What is the proper way to comment functions in Python?

I would go a step further than just saying "use a docstring". Pick a documentation generation tool, such as pydoc or epydoc (I use epydoc in pyparsing), and use the markup syntax recognized by that tool. Run that tool often while you are doing your development, to identify holes in your documentation. In fact, you might even benefit from writing the docstrings for the members of a class before implementing the class.

What does it mean when a PostgreSQL process is "idle in transaction"?

As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.

How to convert a string with comma-delimited items to a list in Python?

I don't think you need to

In python you seldom need to convert a string to a list, because strings and lists are very similar

Changing the type

If you really have a string which should be a character array, do this:

In [1]: x = "foobar"
In [2]: list(x)
Out[2]: ['f', 'o', 'o', 'b', 'a', 'r']

Not changing the type

Note that Strings are very much like lists in python

Strings have accessors, like lists

In [3]: x[0]
Out[3]: 'f'

Strings are iterable, like lists

In [4]: for i in range(len(x)):
...:     print x[i]
...:     
f
o
o
b
a
r

TLDR

Strings are lists. Almost.

Sibling package imports

You need to look to see how the import statements are written in the related code. If examples/example_one.py uses the following import statement:

import api.api

...then it expects the root directory of the project to be in the system path.

The easiest way to support this without any hacks (as you put it) would be to run the examples from the top level directory, like this:

PYTHONPATH=$PYTHONPATH:. python examples/example_one.py 

How to add,set and get Header in request of HttpClient?

You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):

public class App {

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

        CloseableHttpClient client = HttpClients.custom().build();

        // (1) Use the new Builder API (from v4.3)
        HttpUriRequest request = RequestBuilder.get()
                .setUri("https://api.github.com")
                // (2) Use the included enum
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                // (3) Or your own
                .setHeader("Your own very special header", "value")
                .build();

        CloseableHttpResponse response = client.execute(request);

        // (4) How to read all headers with Java8
        List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
        httpHeaders.stream().forEach(System.out::println);

        // close client and response
    }
}

Assignment makes pointer from integer without cast

As others already noted, in one case you are attempting to return cString (which is a char * value in this context - a pointer) from a function that is declared to return a char (which is an integer). In another case you do the reverse: you are assigning a char return value to a char * pointer. This is what triggers the warnings. You certainly need to declare your return values as char *, not as char.

Note BTW that these assignments are in fact constraint violations from the language point of view (i.e. they are "errors"), since it is illegal to mix pointers and integers in C like that (aside from integral constant zero). Your compiler is simply too forgiving in this regard and reports these violations as mere "warnings".

What I also wanted to note is that in several answers you might notice the relatively strange suggestion to return void from your functions, since you are modifying the string in-place. While it will certainly work (since you indeed are modifying the string in-place), there's nothing really wrong with returning the same value from the function. In fact, it is a rather standard practice in C language where applicable (take a look at the standard functions like strcpy and others), since it enables "chaining" of function calls if you choose to use it, and costs virtually nothing if you don't use "chaining".

That said, the assignments in your implementation of compareString look complete superfluous to me (even though they won't break anything). I'd either get rid of them

int compareString(char cString1[], char cString2[]) { 
    // To lowercase 
    strToLower(cString1); 
    strToLower(cString2); 

    // Do regular strcmp 
    return strcmp(cString1, cString2); 
} 

or use "chaining" and do

int compareString(char cString1[], char cString2[]) { 
    return strcmp(strToLower(cString1), strToLower(cString2)); 
} 

(this is when your char * return would come handy). Just keep in mind that such "chained" function calls are sometimes difficult to debug with a step-by-step debugger.

As an additional, unrealted note, I'd say that implementing a string comparison function in such a destructive fashion (it modifies the input strings) might not be the best idea. A non-destructive function would be of a much greater value in my opinion. Instead of performing as explicit conversion of the input strings to a lower case, it is usually a better idea to implement a custom char-by-char case-insensitive string comparison function and use it instead of calling the standard strcmp.

How do I get the path of the assembly the code is in?

This is what I came up with. In between web projects, unit tests (nunit and resharper test runner); I found this worked for me.

I have been looking for code to detect what configuration the build is in, Debug/Release/CustomName. Alas, the #if DEBUG. So if someone can improve that!

Feel free to edit and improve.

Getting app folder. Useful for web roots, unittests to get the folder of test files.

public static string AppPath
{
    get
    {
        DirectoryInfo appPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

        while (appPath.FullName.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
                || appPath.FullName.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
        {
            appPath = appPath.Parent;
        }
        return appPath.FullName;
    }
}

Getting bin folder: Useful for executing assemblies using reflection. If files are copied there due to build properties.

public static string BinPath
{
    get
    {
        string binPath = AppDomain.CurrentDomain.BaseDirectory;

        if (!binPath.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
            && !binPath.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
        {
            binPath = Path.Combine(binPath, "bin");
            //-- Please improve this if there is a better way
            //-- Also note that apps like webapps do not have a debug or release folder. So we would just return bin.
#if DEBUG
            if (Directory.Exists(Path.Combine(binPath, "Debug"))) 
                        binPath = Path.Combine(binPath, "Debug");
#else
            if (Directory.Exists(Path.Combine(binPath, "Release"))) 
                        binPath = Path.Combine(binPath, "Release");
#endif
        }
            return binPath;
    }
}

How to create Toast in Flutter?

For android original graphics toast you can use this: https://pub.dartlang.org/packages/fluttertoast

Works fine on Android and iOS. enter image description here

How to get JSON Key and Value?

$.each(result, function(key, value) {
  console.log(key+ ':' + value);
});

Turn on torch/flash on iPhone

Swift 2.0 version:

func setTorchLevel(torchLevel: Float)
{
    self.captureSession?.beginConfiguration()
    defer {
        self.captureSession?.commitConfiguration()
    }

    if let device = backCamera?.device where device.hasTorch && device.torchAvailable {
        do {
            try device.lockForConfiguration()
            defer {
                device.unlockForConfiguration()
            }

            if torchLevel <= 0.0 {
                device.torchMode = .Off
            }
            else if torchLevel >= 1.0 {
                try device.setTorchModeOnWithLevel(min(torchLevel, AVCaptureMaxAvailableTorchLevel))
            }
        }
        catch let error {
            print("Failed to set up torch level with error \(error)")
            return
        }
    }
}

What does 'wb' mean in this code, using Python?

File mode, write and binary. Since you are writing a .jpg file, it looks fine.

But if you supposed to read that jpg file you need to use 'rb'

More info

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.

extract date only from given timestamp in oracle sql

This is exactly what TO_DATE() is for: to convert timestamp to date.

Just use TO_DATE(sysdate) instead of TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS').

SQLFiddle demo

UPDATE:

Per your update, your cdate column is not real DATE or TIMESTAMP type, but VARCHAR2. It is not very good idea to use string types to keep dates. It is very inconvenient and slow to search, compare and do all other kinds of math on dates.

You should convert your cdate VARCHAR2 field into real TIMESTAMP. Assuming there are no other users for this field except for your code, you can convert cdate to timestamp as follows:

BEGIN TRANSACTION;
-- add new temp field tdate:
ALTER TABLE mytable ADD tdate TIMESTAMP;
-- save cdate to tdate while converting it:
UPDATE mytable SET tdate = to_date(cdate, 'YYYY-MM-DD HH24:MI:SS');

-- you may want to check contents of tdate before next step!!!

-- drop old field
ALTER TABLE mytable DROP COLUMN cdate;
-- rename tdate to cdate:
ALTER TABLE mytable RENAME COLUMN tdate TO cdate;
COMMIT;

SQLFiddle Demo

How can I parse a string with a comma thousand separator to a number?

Removing commas is potentially dangerous because, as others have mentioned in the comments, many locales use a comma to mean something different (like a decimal place).

I don't know where you got your string from, but in some places in the world "2,299.00" = 2.299

The Intl object could have been a nice way to tackle this problem, but somehow they managed to ship the spec with only a Intl.NumberFormat.format() API and no parse counterpart :(

The only way to parse a string with cultural numeric characters in it to a machine recognisable number in any i18n sane way is to use a library that leverages CLDR data to cover off all possible ways of formatting number strings http://cldr.unicode.org/

The two best JS options I've come across for this so far:

Javascript objects: get parent

No. There is no way of knowing which object it came from.

s and obj.subObj both simply have references to the same object.

You could also do:

var obj = { subObj: {foo: 'hello world'} };
var obj2 = {};
obj2.subObj = obj.subObj;
var s = obj.subObj;

You now have three references, obj.subObj, obj2.subObj, and s, to the same object. None of them is special.

psql: FATAL: Ident authentication failed for user "postgres"

Hmmm ...

If you can connect with the username and password in pgAdminIII but you can't connect with psql then those two programs are probably connecting to the database differently.

[If you're connecting to different databases, first try connecting to the same database. See below.]

From PostgreSQL: Documentation: 9.3: psql:

If you omit the host name, psql will connect via a Unix-domain socket to a server on the local host, or via TCP/IP to localhost on machines that don't have Unix-domain sockets.

If you're not running something like psql ... -h host_name ..., and you're running Ubuntu, psql should be connecting via a Unix-domain socket, so PostgreSQL probably isn't configured to allow one of the password authentication methods for the postgres user.

You can test this by running:

sudo -u postgres psql

If the above works, your server is probably configured to use peer authentication for local connections by the postgres user, i.e. asking the OS for your user name to confirm that you're postgres.

So It's Probably Your pg_hba.conf File

The full path of the file will be something like /etc/postgresql/9.3/main/pg_hba.conf. You can view it by, e.g. sudo cat /etc/postgresql/9.3/main/pg_hba.conf | more.

If you're omitting the host name in your psql command, you should be able to connect if you add the following entry to your pg_hba.conf file:

# Connection type   Database   User       IP addresses   Method
local               all        postgres                  md5

[Commented lines in the pg_hba.conf file start with #.]

If you are including the host name in your psql command, add this entry instead:

# Connection type   Database   User       IP addresses   Method
host                all        postgres   127.0.0.1/32   md5

You need to put the entry before any other entries are matched for your connection via psql. If in doubt about where to put it, just put it before the first un-commented line.

More about pg_hba.conf

From PostgreSQL: Documentation: 9.3: The pg_hba.conf File [bold emphasis mine]:

The first record with a matching connection type, client address, requested database, and user name is used to perform authentication. There is no "fall-through" or "backup": if one record is chosen and the authentication fails, subsequent records are not considered. If no record matches, access is denied.

Note that records are not matched on authentication method. So, if your pg_hba.conf file contains the following entry:

# Connection type   Database   User       IP addresses   Method
local               all        postgres                  peer

Then you won't be able to connect via:

psql -u postgres

Unless one of these entries is in your pg_hba.conf file above the former entry:

# Connection type   Database   User       IP addresses   Method
local               all        postgres                  md5
local               all        postgres                  password   # Unencrypted!
local               all        all                       md5
local               all        all                       password   # Unencrypted!

What is Java EE?

Java EE is a collection of specifications for developing and deploying enterprise applications.

In general, enterprise applications refer to software hosted on servers that provide the applications that support the enterprise.

The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols.

The 13 core technologies that make up Java EE are:

  1. JDBC
  2. JNDI
  3. EJBs
  4. RMI
  5. JSP
  6. Java servlets
  7. XML
  8. JMS
  9. Java IDL
  10. JTS
  11. JTA
  12. JavaMail
  13. JAF

The Java EE product provider is typically an application-server, web-server, or database-system vendor who provides classes that implement the interfaces defined in the specifications. These vendors compete on implementations of the Java EE specifications.

When a company requires Java EE experience what are they really asking for is experience using the technologies that make up Java EE. Frequently, a company will only be using a subset of the Java EE technologies.

How to get the current directory in a C program?

Look up the man page for getcwd.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

Pre Java 6 the DriverManager class wouldn't have known which JDBC driver you wanted to use. Class.forName("...") was a way on pre-loading the driver classes.

If you are using Java 6 you no longer need to do this.

How to add Action bar options menu in Android Fragments

in AndroidManifest.xml set theme holo like this:

<activity
android:name="your Fragment or activity"
android:label="@string/xxxxxx"
android:theme="@android:style/Theme.Holo" >

How can we run a test method with multiple parameters in MSTest?

MSTest does not support that feature, but you can implement your own attribute to achieve that.

Have a look at Enabling parameterized tests in MSTest using PostSharp.

Looking for simple Java in-memory cache

Since this question was originally asked, Google's Guava library now includes a powerful and flexible cache. I would recommend using this.

Have a fixed position div that needs to scroll if content overflows

Here are both fixes.

First, regarding the fixed sidebar, you need to give it a height for it to overflow:

HTML Code:

<div id="sidebar">Menu</div>
<div id="content">Text</div>

CSS Code:

body {font:76%/150% Arial, Helvetica, sans-serif; color:#666; width:100%; height:100%;}
#sidebar {position:fixed; top:0; left:0; width:20%; height:100%; background:#EEE; overflow:auto;}
#content {width:80%; padding-left:20%;}

@media screen and (max-height:200px){
    #sidebar {color:blue; font-size:50%;}
}

Live example: http://jsfiddle.net/RWxGX/3/

It's impossible NOT to get a scroll bar if your content overflows the height of the div. That's why I've added a media query for screen height. Maybe you can adjust your styles for short screen sizes so the scroll doesn't need to appear.

Cheers, Ignacio

Extract value of attribute node via XPath

@ryenus, You need to loop through the result. This is how I'd do it in vbscript;

Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load("kids.xml")

'Remove the id=1 attribute on Parent to return all child names for all Parent nodes
For Each c In xmlDoc.selectNodes ("//Parent[@id='1']/Children/child/@name")
    Wscript.Echo c.text
Next

gcloud command not found - while installing Google Cloud SDK

Same here, I try

source ~/.bashrc

Then, It worked

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

Select "all project" and right click

Maven-> Update project

Tomcat won't stop or restart

Make sure Tomcat is not currently running and the PID file is removed. Them you should start Tomcat successfully.

If you start fresh then:

  1. Create setenv.sh file in <CATALINA_HOME>/bin.
  2. In it I set CATALINA_PID=/tmp/tomcat.pid (or other directory of your choice) so you have more control over the Tomcat process.

Then to start Tomcat find catalina.sh in <CATALINA_HOME>/bin and execute:

./catalina.sh start

and to stop it run:

./catalina.sh stop 10 -force

From catalina.sh script's doc:

./catalina.sh

Usage: catalina.sh ( commands ... )
commands:

start             Start Catalina in a separate window
stop              Stop Catalina, waiting up to 5 seconds for the process to end
stop n            Stop Catalina, waiting up to n seconds for the process to end
stop -force       Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running
stop n -force     Stop Catalina, wait up to n seconds and then use kill -KILL if still running

Note: If you want to use -force flag then setting CATALINA_PID is mandatory.

Getting the object's property name

These solutions work too.

// Solution One
function removeProperty(obj, prop) {
  var bool;
  var keys = Object.keys(obj);
  for (var i = 0; i < keys.length; i++) {
    if (keys[i] === prop) {
      delete obj[prop];
      bool = true;
    } 
  }
  return Boolean(bool);
}


//Solution two
function removeProperty(obj, prop) {
  var bool;
  if (obj.hasOwnProperty(prop)) {
      bool = true;
      delete obj[prop];
  }
  return Boolean(bool);
}

Eclipse 3.5 Unable to install plugins

I had a similar problem setting up eclipse.

I changed: NATIVE connection to MANUAL and cleared the proxy settings for SOCKS in Windows -> Preferences -> General -> Network connection. That fixed the problem for me.

Uncaught TypeError: Cannot set property 'value' of null

You don't have an element with the id u.That's why the error occurs. Note that the global variable document.getElementById("u").value means you are trying to get the value of input element with name u and its not defined in your code.

How to "flatten" a multi-dimensional array to simple one in PHP?

A new approach based on the previous example function submited by chaos, which fixes the bug of overwritting string keys in multiarrays:

# Flatten a multidimensional array to one dimension, optionally preserving keys.
# $array - the array to flatten
# $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
# $out - internal use argument for recursion

function flatten_array($array, $preserve_keys = 2, &$out = array(), &$last_subarray_found) 
{
        foreach($array as $key => $child)
        {
            if(is_array($child))
            {
                $last_subarray_found = $key;
                $out = flatten_array($child, $preserve_keys, $out, $last_subarray_found);
            }
            elseif($preserve_keys + is_string($key) > 1)
            {
                if ($last_subarray_found)
                {
                    $sfinal_key_value = $last_subarray_found . "_" . $key;
                }
                else
                {
                    $sfinal_key_value = $key;
                }
                $out[$sfinal_key_value] = $child;
            }
            else
            {
                $out[] = $child;
            }
        }

        return $out;
}

Example:
$newarraytest = array();
$last_subarray_found = "";
$this->flatten_array($array, 2, $newarraytest, $last_subarray_found);

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

The best way to get filetype-specific indentation is to use filetype plugin indent on in your vimrc. Then you can specify things like set sw=4 sts=4 et in .vim/ftplugin/c.vim, for example, without having to make those global for all files being edited and other non-C type syntaxes will get indented correctly, too (even lisps).

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

check if directory exists and delete in one command unix

Assuming $WORKING_DIR is set to the directory... this one-liner should do it:

if [ -d "$WORKING_DIR" ]; then rm -Rf $WORKING_DIR; fi

(otherwise just replace with your directory)

Converting Columns into rows with their respective data in sql server

As an alternative:

Using CROSS APPLY and VALUES performs this operation quite simply and efficiently with just a single pass of the table (unlike union queries that do one pass for every column)

SELECT
    ca.ColName, ca.ColValue
FROM YOurTable
CROSS APPLY (
      Values
         ('ScripName' , ScripName),
         ('ScripCode' , ScripCode),
         ('Price'     , cast(Price as varchar(50)) )
  ) as CA (ColName, ColValue)

Personally I find this syntax easier than using unpivot.

NB: You must take care that all source columns are converted into compatible types for the single value column

Dialog to pick image from gallery or from camera

The code below can be used for taking a photo and for picking a photo. Just show a dialog with two options and upon selection, use the appropriate code.

To take picture from camera:

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code (called requestCode)

To pick photo from gallery:

Intent pickPhoto = new Intent(Intent.ACTION_PICK,
           android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code

onActivityResult code:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
    switch(requestCode) {
    case 0:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            imageview.setImageURI(selectedImage);
        }

    break; 
    case 1:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            imageview.setImageURI(selectedImage);
        }
    break;
    }
}

Finally add this permission in the manifest file:

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Rock, Paper, Scissors Game Java

I would recommend making Rock, Paper and Scissors objects. The objects would have the logic of both translating to/from Strings and also "knowing" what beats what. The Java enum is perfect for this.

public enum Type{

  ROCK, PAPER, SCISSOR;

  public static Type parseType(String value){
     //if /else logic here to return either ROCK, PAPER or SCISSOR

     //if value is not either, you can return null
  }
}

The parseType method can return null if the String is not a valid type. And you code can check if the value is null and if so, print "invalid try again" and loop back to re-read the Scanner.

Type person=null;

 while(person==null){
      System.out.println("Enter your play: "); 
      person= Type.parseType(scan.next());
      if(person ==null){
         System.out.println("invalid try again");
      }
 }

Furthermore, your type enum can determine what beats what by having each Type object know:

public enum Type{

    //...

    //each type will implement this method differently
    public abstract boolean beats(Type other);


}

each type will implement this method differently to see what beats what:

ROCK{

   @Override
   public boolean beats(Type other){            
        return other ==  SCISSOR;

   }
}

 ...

Then in your code

 Type person, computer;
   if (person.equals(computer)) 
   System.out.println("It's a tie!");
  }else if(person.beats(computer)){
     System.out.println(person+ " beats " + computer + "You win!!"); 
  }else{
     System.out.println(computer + " beats " + person+ "You lose!!");
  }

How to launch a Google Chrome Tab with specific URL using C#

If the user doesn't have Chrome, it will throw an exception like this:

    //chrome.exe http://xxx.xxx.xxx --incognito
    //chrome.exe http://xxx.xxx.xxx -incognito
    //chrome.exe --incognito http://xxx.xxx.xxx
    //chrome.exe -incognito http://xxx.xxx.xxx
    private static void Chrome(string link)
    {
        string url = "";

        if (!string.IsNullOrEmpty(link)) //if empty just run the browser
        {
            if (link.Contains('.')) //check if it's an url or a google search
            {
                url = link;
            }
            else
            {
                url = "https://www.google.com/search?q=" + link.Replace(" ", "+");
            }
        }

        try
        {
            Process.Start("chrome.exe", url + " --incognito");
        }
        catch (System.ComponentModel.Win32Exception e)
        {
            MessageBox.Show("Unable to find Google Chrome...",
                "chrome.exe not found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Default visibility for C# classes and members (fields, methods, etc.)?

By default, the access modifier for a class is internal. That means to say, a class is accessible within the same assembly. But if we want the class to be accessed from other assemblies then it has to be made public.

How set background drawable programmatically in Android

I'm using a minSdkVersion 16 and targetSdkVersion 23.
The following is working for me, it uses

ContextCompat.getDrawable(context, R.drawable.drawable);

Instead of using:

layout.setBackgroundResource(R.drawable.ready);

Rather use:

layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));

getActivity() is used in a fragment, if calling from a activity use this.

How to print the values of slices

You can try the %v, %+v or %#v verbs of go fmt:

fmt.Printf("%v", projects)

If your array (or here slice) contains struct (like Project), you will see their details.
For more precision, you can use %#v to print the object using Go-syntax, as for a literal:

%v  the value in a default format.
    when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value

For basic types, fmt.Println(projects) is enough.


Note: for a slice of pointers, that is []*Project (instead of []Project), you are better off defining a String() method in order to display exactly what you want to see (or you will see only pointer address).
See this play.golang example.

How to fix "Attempted relative import in non-package" even with __init__.py

python <main module>.py does not work with relative import

The problem is relative import does not work when you run a __main__ module from the command line

python <main_module>.py

It is clearly stated in PEP 338.

The release of 2.5b1 showed a surprising (although obvious in retrospect) interaction between this PEP and PEP 328 - explicit relative imports don't work from a main module. This is due to the fact that relative imports rely on __name__ to determine the current module's position in the package hierarchy. In a main module, the value of __name__ is always '__main__', so explicit relative imports will always fail (as they only work for a module inside a package).

Cause

The issue isn't actually unique to the -m switch. The problem is that relative imports are based on __name__, and in the main module, __name__ always has the value __main__. Hence, relative imports currently can't work properly from the main module of an application, because the main module doesn't know where it really fits in the Python module namespace (this is at least fixable in theory for the main modules executed through the -m switch, but directly executed files and the interactive interpreter are completely out of luck).

To understand further, see Relative imports in Python 3 for the detailed explanation and how to get it over.

.bashrc at ssh login

For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:

What is &amp used for

if you're doing a string of characters. make:

let linkGoogle = 'https://www.google.com/maps/dir/?api=1'; 
let origin = '&origin=' + locations[0][1] + ',' + locations[0][2];


aNav.href = linkGoogle + origin;

How do you push a tag to a remote repository using Git?

I am using git push <remote-name> tag <tag-name> to ensure that I am pushing a tag. I use it like: git push origin tag v1.0.1. This pattern is based upon the documentation (man git-push):

OPTIONS
   ...
   <refspec>...
       ...
       tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>.

How do I clear all options in a dropdown box?

This is the best way :

function (comboBox) {
    while (comboBox.options.length > 0) {                
        comboBox.remove(0);
    }        
}

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

From the command prompt run the command adb kill-server. This will shutdown ADB and android studio or Eclipse if you were to use that, would show Waiting for ADB as you said.

Once ADB has shutdown down run adb start-server or run adb devices which will automatically start the adb service and show that your android emulator or development devices has successfully connected.

javac : command not found

You installed the Java Runtime Environment (JRE) only, which does not contain javac. For javac, you have to install the OpenJDK Development Environment. You can install java-devel or java-1.6.0-openjdk-devel, which both include javac.

By the way: you can find out which package provides javac with a yum search, e.g.

su -c 'yum provides javac'

on more recent releases of CentOS e.g. 6 the command changes to

su -c 'yum provides */javac'

Another note: using yum and openjdk is only one possibility to install the JDK. Many people prefer Sun/Oracle's "original" SDK. See How to install Java SDK on CentOS? and links for alternatives.

Writing to a TextBox from another thread?

Most simple, without caring about delegates

if(textBox1.InvokeRequired == true)
    textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";});

else
    textBox1.Text = "Invoke was NOT needed"; 

How to populate a sub-document in mongoose after creating it?

@user1417684 and @chris-foster are right!

excerpt from working code (without error handling):

var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel    = mongoose.model('items', ItemSchema);

var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {

  var new_item = new ItemModel(new_item);
  new_item.subitem = new_sub_item._id;
  new_item.save(function (error, new_item) {
    // so this is a valid way to populate via the Model
    // as documented in comments above (here @stack overflow):
    ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
      callback(new_item.toObject());
    });
    // or populate directly on the result object
    new_item.populate('subitem', function(error, new_item) {
      callback(new_item.toObject());
    });
  });

});

Multi-line string with extra space (preserved indentation)

in a bash script the following works:

#!/bin/sh

text="this is line one\nthis is line two\nthis is line three"
echo -e $text > filename

alternatively:

text="this is line one
this is line two
this is line three"
echo "$text" > filename

cat filename gives:

this is line one
this is line two
this is line three

Save multiple sheets to .pdf

Start by selecting the sheets you want to combine:

ThisWorkbook.Sheets(Array("Sheet1", "Sheet2")).Select

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\tempo.pdf", Quality:= xlQualityStandard, IncludeDocProperties:=True, _
     IgnorePrintAreas:=False, OpenAfterPublish:=True

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

Change color of bootstrap navbar on hover link?

Something like this has worked for me (with Bootstrap 3):

.navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus{
    font-family: proxima-nova;
    font-style: normal;
    font-weight: 100;
    letter-spacing: 3px;
    text-transform: uppercase;
    color: black;
} 

In my case I also wanted the link text to remain black before the hover so i added .navbar-nav > li > a

.navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus, .navbar-nav > li > a{
    font-family: proxima-nova;
    font-style: normal;
    font-weight: 100;
    letter-spacing: 3px;
    text-transform: uppercase;
    color: black;
} 

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

I got this error too even I ran cmd as an Administrator.

The root cause is: The file is from VCS(subversion, perforce, etc.), and when I checked the properties of this file, its' Attributes is Read-only.

So the solution is:

  • (1) disable the 'Read-only' Attribute;
  • (2) check out from VCS, let the file under the status of read&write.

Django values_list vs values

values()

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

values_list()

Returns a QuerySet that returns list of tuples, rather than model instances, when used as an iterable.

distinct()

distinct are used to eliminate the duplicate elements.

Example:

>>> list(Article.objects.values_list('id', flat=True)) # flat=True will remove the tuples and return the list   
[1, 2, 3, 4, 5, 6]

>>> list(Article.objects.values('id'))
[{'id':1}, {'id':2}, {'id':3}, {'id':4}, {'id':5}, {'id':6}]

How to properly ignore exceptions

How to properly ignore Exceptions?

There are several ways of doing this.

However, the choice of example has a simple solution that does not cover the general case.

Specific to the example:

Instead of

try:
    shutil.rmtree(path)
except:
    pass

Do this:

shutil.rmtree(path, ignore_errors=True)

This is an argument specific to shutil.rmtree. You can see the help on it by doing the following, and you'll see it can also allow for functionality on errors as well.

>>> import shutil
>>> help(shutil.rmtree)

Since this only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

General approach

Since the above only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

New in Python 3.4:

You can import the suppress context manager:

from contextlib import suppress

But only suppress the most specific exception:

with suppress(FileNotFoundError):
    shutil.rmtree(path)

You will silently ignore a FileNotFoundError:

>>> with suppress(FileNotFoundError):
...     shutil.rmtree('bajkjbkdlsjfljsf')
... 
>>> 

From the docs:

As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.

Note that suppress and FileNotFoundError are only available in Python 3.

If you want your code to work in Python 2 as well, see the next section:

Python 2 & 3:

When you just want to do a try/except without handling the exception, how do you do it in Python?

Is the following the right way to do it?

try :
    shutil.rmtree ( path )
except :
    pass

For Python 2 compatible code, pass is the correct way to have a statement that's a no-op. But when you do a bare except:, that's the same as doing except BaseException: which includes GeneratorExit, KeyboardInterrupt, and SystemExit, and in general, you don't want to catch those things.

In fact, you should be as specific in naming the exception as you can.

Here's part of the Python (2) exception hierarchy, and as you can see, if you catch more general Exceptions, you can hide problems you did not expect:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      |    +-- BufferError
      |    +-- ArithmeticError
      |    |    +-- FloatingPointError
      |    |    +-- OverflowError
      |    |    +-- ZeroDivisionError
      |    +-- AssertionError
      |    +-- AttributeError
      |    +-- EnvironmentError
      |    |    +-- IOError
      |    |    +-- OSError
      |    |         +-- WindowsError (Windows)
      |    |         +-- VMSError (VMS)
      |    +-- EOFError
... and so on

You probably want to catch an OSError here, and maybe the exception you don't care about is if there is no directory.

We can get that specific error number from the errno library, and reraise if we don't have that:

import errno

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno == errno.ENOENT: # no such file or directory
        pass
    else: # we had an OSError we didn't expect, so reraise it
        raise 

Note, a bare raise raises the original exception, which is probably what you want in this case. Written more concisely, as we don't really need to explicitly pass with code in the exception handling:

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno != errno.ENOENT: # no such file or directory
        raise 

How to take backup of a single table in a MySQL database?

You can either use mysqldump from the command line:

mysqldump -u username -p password dbname tablename > "path where you want to dump"

You can also use MySQL Workbench:

Go to left > Data Export > Select Schema > Select tables and click on Export

Changing the selected option of an HTML Select element

None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.

The right way to select Alaska and have the select show the right item as selected using:

<select id="state">
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
</select>

With jquery would be:

$('#state').val('AK').change();

Rollback to an old Git commit in a public repo

Step 1: fetch list of commits:

git log

You'll get list like in this example:

[Comp:Folder User$ git log
commit 54b11d42e12dc6e9f070a8b5095a4492216d5320
Author: author <[email protected]>
Date:   Fri Jul 8 23:42:22 2016 +0300

This is last commit message

commit fd6cb176297acca4dbc69d15d6b7f78a2463482f
Author: author <[email protected]>
Date:   Fri Jun 24 20:20:24 2016 +0300

This is previous commit message

commit ab0de062136da650ffc27cfb57febac8efb84b8d
Author: author <[email protected]>
Date:   Thu Jun 23 00:41:55 2016 +0300

This is previous previous commit message
...

Step 2: copy needed commit hash and paste it for checkout:

git checkout fd6cb176297acca4dbc69d15d6b7f78a2463482f

That's all.

Bootstrap 3 - disable navbar collapse

If you're not using the less version, here is the line you need to change:

@media (max-width: 767px) { /* Change this to 0 */
  .navbar-nav .open .dropdown-menu {
    position: static;
    float: none;
    width: auto;
    margin-top: 0;
    background-color: transparent;
    border: 0;
    box-shadow: none;
  }
  .navbar-nav .open .dropdown-menu > li > a,
  .navbar-nav .open .dropdown-menu .dropdown-header {
    padding: 5px 15px 5px 25px;
  }
  .navbar-nav .open .dropdown-menu > li > a {
    line-height: 20px;
  }
  .navbar-nav .open .dropdown-menu > li > a:hover,
  .navbar-nav .open .dropdown-menu > li > a:focus {
    background-image: none;
  }
}

How permission can be checked at runtime without throwing SecurityException?

This is another solution as well

PackageManager pm = context.getPackageManager();
int hasPerm = pm.checkPermission(
    android.Manifest.permission.WRITE_EXTERNAL_STORAGE, 
    context.getPackageName());
if (hasPerm != PackageManager.PERMISSION_GRANTED) {
   // do stuff
}

Powershell: Get FQDN Hostname

I use the following syntax :

$Domain=[System.Net.Dns]::GetHostByName($VM).Hostname.split('.')
$Domain=$Domain[1]+'.'+$Domain[2]

it does not matter if the $VM is up or down...

Execute a SQL Stored Procedure and process the results

My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code

Please make sure that your procedure return some rows

Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
    Try
        Connection.Connect()
        debug.print("Look up account number " & AccountNumber)
        Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP  '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
        Dim DST As New DataSet
        DP.Fill(DST)
        Return DST.Tables(0)      
    Catch ex As Exception
        Return Nothing
    End Try
End Function

Could not find method android() for arguments

This error appear because the compiler could not found "my-upload-key.keystore" file in your project

After you have generated the file you need to paste it into project's andorid/app folder

this worked for me!

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

Rename all files in a folder with a prefix in a single command

If your filenames contain no whitepace and you don't have any subdirectories, you can use a simple for loop:

$ for FILENAME in *; do mv $FILENAME Unix_$FILENAME; done 

Otherwise use the convenient rename command (which is a perl script) - although it might not be available out of the box on every Unix (e.g. OS X doesn't come with rename).

A short overview at debian-administration.org:

If your filenames contain whitespace it's easier to use find, on Linux the following should work:

$ find . -type f -name '*' -printf "echo mv '%h/%f' '%h/Unix_%f\n'" | sh

On BSD systems, there is no -printf option, unfortunately. But GNU findutils should be installable (on e.g. Mac OS X with brew install findutils).

$ gfind . -type f -name '*' -printf "mv \"%h/%f\" \"%h/Unix_%f\"\n" | sh

How to save all console output to file in R?

Run R in emacs with ESS (Emacs Speaks Statistics) r-mode. I have one window open with my script and R code. Another has R running. Code is sent from the syntax window and evaluated. Commands, output, errors, and warnings all appear in the running R window session. At the end of some work period, I save all the output to a file. My own naming system is *.R for scripts and *.Rout for save output files. Here's a screenshot with an example.Screenshot writing and evaluating R with Emacs/ESS.

Ascii/Hex convert in bash

The reason is because hexdump by default prints out 16-bit integers, not bytes. If your system has them, hd (or hexdump -C) or xxd will provide less surprising outputs - if not, od -t x1 is a POSIX-standard way to get byte-by-byte hex output. You can use od -t x1c to show both the byte hex values and the corresponding letters.

If you have xxd (which ships with vim), you can use xxd -r to convert back from hex (from the same format xxd produces). If you just have plain hex (just the '4161', which is produced by xxd -p) you can use xxd -r -p to convert back.

What is the difference between a static and const variable?

A static variable can get an initial value only one time. This means that if you have code such as "static int a=0" in a sample function, and this code is executed in a first call of this function, but not executed in a subsequent call of the function; variable (a) will still have its current value (for example, a current value of 5), because the static variable gets an initial value only one time.

A constant variable has its value constant in whole of the code. For example, if you set the constant variable like "const int a=5", then this value for "a" will be constant in whole of your program.

What is the pythonic way to detect the last element in a 'for' loop?

Assuming input as an iterator, here's a way using tee and izip from itertools:

from itertools import tee, izip
items, between = tee(input_iterator, 2)  # Input must be an iterator.
first = items.next()
do_to_every_item(first)  # All "do to every" operations done to first item go here.
for i, b in izip(items, between):
    do_between_items(b)  # All "between" operations go here.
    do_to_every_item(i)  # All "do to every" operations go here.

Demo:

>>> def do_every(x): print "E", x
...
>>> def do_between(x): print "B", x
...
>>> test_input = iter(range(5))
>>>
>>> from itertools import tee, izip
>>>
>>> items, between = tee(test_input, 2)
>>> first = items.next()
>>> do_every(first)
E 0
>>> for i,b in izip(items, between):
...     do_between(b)
...     do_every(i)
...
B 0
E 1
B 1
E 2
B 2
E 3
B 3
E 4
>>>

AlertDialog styling - how to change style (color) of title, message, etc

It depends how much you want to customize the alert dialog. I have different steps in order to customize the alert dialog. Please visit: https://stackoverflow.com/a/33439849/5475941

enter image description here enter image description here enter image description here enter image description here

Finding the layers and layer sizes for each Docker image

You can find the layers of the images in the folder /var/lib/docker/aufs/layers; provide if you configured for storage-driver as aufs (default option)

Example:

 docker ps -a
 CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
 0ca502fa6aae        ubuntu              "/bin/bash"         44 minutes ago      Exited (0) 44 seconds ago                       DockerTest

Now to view the layers of the containers that were created with the image "Ubuntu"; go to /var/lib/docker/aufs/layers directory and cat the file starts with the container ID (here it is 0ca502fa6aae*)

 root@viswesn-vm2:/var/lib/docker/aufs/layers# cat    0ca502fa6aaefc89f690736609b54b2f0fdebfe8452902ca383020e3b0d266f9-init 
 d2a0ecffe6fa4ef3de9646a75cc629bbd9da7eead7f767cb810f9808d6b3ecb6
 29460ac934423a55802fcad24856827050697b4a9f33550bd93c82762fb6db8f
 b670fb0c7ecd3d2c401fbfd1fa4d7a872fbada0a4b8c2516d0be18911c6b25d6
 83e4dde6b9cfddf46b75a07ec8d65ad87a748b98cf27de7d5b3298c1f3455ae4

This will show the result of same by running

root@viswesn-vm2:/var/lib/docker/aufs/layers# docker history ubuntu
IMAGE               CREATED             CREATED BY                                         SIZE                COMMENT
d2a0ecffe6fa        13 days ago         /bin/sh -c #(nop) CMD ["/bin/bash"]             0 B                 
29460ac93442        13 days ago         /bin/sh -c sed -i 's/^#\s*\   (deb.*universe\)$/   1.895 kB            
b670fb0c7ecd        13 days ago         /bin/sh -c echo '#!/bin/sh' > /usr/sbin/polic   194.5 kB            
83e4dde6b9cf        13 days ago         /bin/sh -c #(nop) ADD file:c8f078961a543cdefa   188.2 MB 

To view the full layer ID; run with --no-trunc option as part of history command.

docker history --no-trunc ubuntu

Where to place $PATH variable assertions in zsh?

I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)

Solution:


just paste whatever you were earlier pasting in ~/.bashrc to:

~/.zshrc

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

MVP:

Advantages:

Presenter will be present in between Model and view.Presenter will fetch data from Model and will do manipulations for data as view wants and give it to view and view is responsible only for rendering.

Disadvantages:

1)We can't use presenter for multiple modules because data is being modified in presenter as desired by one view class.

3)Breaking Clean architecture because data flow should be only outwards but here data is coming back from presenter to View.

MVC:

Advanatages:

Here we have Controller in between view and model.Here data request will be done from controller to view but data will be sent back to view in form of interface but not with controller.So,here controller won't get bloated up because of many transactions.

Disadvantagaes:

Data Manipulation should be done by View as it wants and this will be extra work on UI thread which may effect UI rendering if data processing is more.

MVVM:

After announcing Architectural components,we got access to ViewModel which provided us biggest advantage i.e it's lifecycle aware.So,it won't notify data if view is not available.It is a clean architecture because flow is only in forward mode and data will be notified automatically by LiveData. So,it is Android's recommended architecture.

Even MVVM has a disadvantage. Since it is a lifecycle aware some concepts like alarm or reminder should come outside app.So,in this scenario we can't use MVVM.

Display Python datetime without time

If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do

>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)

Note that this returns a new datetime object -- now remains unchanged.

Official way to ask jQuery wait for all images to load before executing something

This way you can execute an action when all images inside body or any other container (that depends of your selection) are loaded. PURE JQUERY, no pluggins needed.

var counter = 0;
var size = $('img').length;

$("img").load(function() { // many or just one image(w) inside body or any other container
    counter += 1;
    counter === size && $('body').css('background-color', '#fffaaa'); // any action
}).each(function() {
  this.complete && $(this).load();        
});

How do I convert a float to an int in Objective C?

I'm pretty sure C-style casting syntax works in Objective C, so try that, too:

int myInt = (int) myFloat;

It might silence a compiler warning, at least.

ASP.NET MVC3 Razor - Html.ActionLink style

Reviving an old question because it seems to appear at the top of search results.

I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.

  1. I wrapped the action link with a div that would contain the parent style:
<div class="parent-style-one">
      @Html.ActionLink("Homepage", "Home", "Home")
</div>
  1. Next I create the CSS for the div, this will be the parent css and will be inherited by the child elements such as the action link.
  .parent-style-one {
     /* your styles here */
  }
  1. Because all an action link is, is an element when broken down as html so you just need to target that element in your css selection:
  .parent-style-one a {
     text-decoration: none;
  }
  1. For transition effects I did this:
  .parent-style-one a:hover {
        text-decoration: underline;
        -webkit-transition-duration: 1.1s; /* Safari */
        transition-duration: 1.1s;         
  }

This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.

What is the copy-and-swap idiom?

This answer is more like an addition and a slight modification to the answers above.

In some versions of Visual Studio (and possibly other compilers) there is a bug that is really annoying and doesn't make sense. So if you declare/define your swap function like this:

friend void swap(A& first, A& second) {

    std::swap(first.size, second.size);
    std::swap(first.arr, second.arr);

}

... the compiler will yell at you when you call the swap function:

enter image description here

This has something to do with a friend function being called and this object being passed as a parameter.


A way around this is to not use friend keyword and redefine the swap function:

void swap(A& other) {

    std::swap(size, other.size);
    std::swap(arr, other.arr);

}

This time, you can just call swap and pass in other, thus making the compiler happy:

enter image description here


After all, you don't need to use a friend function to swap 2 objects. It makes just as much sense to make swap a member function that has one other object as a parameter.

You already have access to this object, so passing it in as a parameter is technically redundant.

VBA procedure to import csv file into access

Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work

Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant

    sFileIn = "z:\docs\FileName.csv"
    sFileOut = "z:\docs\FileOut.csv"

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading

    sTmp = tsIn.ReadAll

    Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
    aryFile = Split(sTmp, vbCrLf)

    ''Start at line 3 and end at last line -1
    For i = 3 To UBound(aryFile) - 1
        tsOut.WriteLine aryFile(i)
    Next

    tsOut.Close

    DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub

Edit re various comments

It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.

About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003

Introduction to importing and exporting data -- Applies to: Microsoft Access 2010

Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.

How can I send the "&" (ampersand) character via AJAX?

You could encode your string using Base64 encoding on the JavaScript side and then decoding it on the server side with PHP (?).

JavaScript (Docu)

var wysiwyg_clean = window.btoa( wysiwyg );

PHP (Docu):

var wysiwyg = base64_decode( $_POST['wysiwyg'] );

Presenting a UIAlertController properly on an iPad using iOS 8

Update for Swift 3.0 and higher

    let actionSheetController: UIAlertController = UIAlertController(title: "SomeTitle", message: nil, preferredStyle: .actionSheet)

    let editAction: UIAlertAction = UIAlertAction(title: "Edit Details", style: .default) { action -> Void in

        print("Edit Details")
    }

    let deleteAction: UIAlertAction = UIAlertAction(title: "Delete Item", style: .default) { action -> Void in

        print("Delete Item")
    }

    let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in }

    actionSheetController.addAction(editAction)
    actionSheetController.addAction(deleteAction)
    actionSheetController.addAction(cancelAction)

//        present(actionSheetController, animated: true, completion: nil)   // doesn't work for iPad

    actionSheetController.popoverPresentationController?.sourceView = yourSourceViewName // works for both iPhone & iPad

    present(actionSheetController, animated: true) {
        print("option menu presented")
    }

How to get build time stamp from Jenkins build variables?

Try use Build Timestamp Plugin and use BUILD_TIMESTAMP variable.

What is the 'realtime' process priority setting for?

It basically is higher/greater in everything else. A keyboard is less of a priority than the real time process. This means the process will be taken into account faster then keyboard and if it can't handle that, then your keyboard is slowed.

Last element in .each() set

A shorter answer from here, adapted to this question:

var arr = $('.requiredText');
arr.each(function(index, item) {
   var is_last_item = (index == (arr.length - 1));
});

Just for completeness.

How to print environment variables to the console in PowerShell?

In addition to Mathias answer.

Although not mentioned in OP, if you also need to see the Powershell specific/related internal variables, you need to use Get-Variable:

$ Get-Variable

Name                           Value
----                           -----
$                              name
?                              True
^                              gci
args                           {}
ChocolateyTabSettings          @{AllCommands=False}
ConfirmPreference              High
DebugPreference                SilentlyContinue
EnabledExperimentalFeatures    {}
Error                          {System.Management.Automation.ParseException: At line:1 char:1...
ErrorActionPreference          Continue
ErrorView                      NormalView
ExecutionContext               System.Management.Automation.EngineIntrinsics
false                          False
FormatEnumerationLimit         4
...

These also include stuff you may have set in your profile startup script.

Ignore duplicates when producing map using streams

For grouping by Objects

Map<Integer, Data> dataMap = dataList.stream().collect(Collectors.toMap(Data::getId, data-> data, (data1, data2)-> {LOG.info("Duplicate Group For :" + data2.getId());return data1;}));

How to assign name for a screen?

To start a new session

screen -S your_session_name

To rename an existing session

Ctrl+a, : sessionname YOUR_SESSION_NAME Enter

You must be inside the session

How to include Javascript file in Asp.Net page

add like

<head runat="server">
<script src="Registration.js" type="text/javascript"></script>
</head>

OR can add in code behind.

Page.ClientScript.RegisterClientScriptInclude("Registration", ResolveUrl("~/js/Registration.js"));

How to set java_home on Windows 7?

In Eclipse: Window->Preferences->Java->Installed JREs

Use the search feature to make sure your latest Java installation is listed; then make sure it is the one that is checked. This should be a JDK not a JRE.

What is the simplest way to convert array to vector?

Pointers can be used like any other iterators:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + 3);
test(v)

How to download file from database/folder using php

I have changed to your code with little modification will works well. Here is the code:

butangDonload.php

<?php
$file = "logo_ldg.png"; //Let say If I put the file name Bang.png
echo "<a href='download1.php?nama=".$file."'>download</a> ";
?>

download.php

<?php
$name= $_GET['nama'];

    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header("Content-Disposition: attachment; filename=\"" . basename($name) . "\";");
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($name));
    ob_clean();
    flush();
    readfile("your_file_path/".$name); //showing the path to the server where the file is to be download
    exit;
?>

Here you need to show the path from where the file to be download. i.e. will just give the file name but need to give the file path for reading that file. So, it should be replaced by I have tested by using your code and modifying also will works.

Getting a list of files in a directory with a glob

You can achieve this pretty easily with the help of NSPredicate, like so:

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:bundleRoot error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"];
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];

If you need to do it with NSURL instead it looks like this:

NSURL *bundleRoot = [[NSBundle mainBundle] bundleURL];
NSArray * dirContents = 
      [fm contentsOfDirectoryAtURL:bundleRoot
        includingPropertiesForKeys:@[] 
                           options:NSDirectoryEnumerationSkipsHiddenFiles
                             error:nil];
NSPredicate * fltr = [NSPredicate predicateWithFormat:@"pathExtension='jpg'"];
NSArray * onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];

how to get 2 digits after decimal point in tsql?

So, something like

DECLARE @i AS FLOAT = 2
SELECT @i / 3
SELECT CAST(@i / 3 AS DECIMAL(18,2))

I would however recomend that this be done in the UI/Report layer, as this will cuase loss of precision.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Not sure if anyone is having the same responsive issue, but it was just a simple css solution for me.

same example

...  ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed"> ...
...  div collapse="isCollapsed"> ...

with

@media screen and (min-width: 768px) {
    .collapse{
        display: block !important;
    }
}

Convert object to JSON in Android

public class Producto {

int idProducto;
String nombre;
Double precio;



public Producto(int idProducto, String nombre, Double precio) {

    this.idProducto = idProducto;
    this.nombre = nombre;
    this.precio = precio;

}
public int getIdProducto() {
    return idProducto;
}
public void setIdProducto(int idProducto) {
    this.idProducto = idProducto;
}
public String getNombre() {
    return nombre;
}
public void setNombre(String nombre) {
    this.nombre = nombre;
}
public Double getPrecio() {
    return precio;
}
public void setPrecio(Double precio) {
    this.precio = precio;
}

public String toJSON(){

    JSONObject jsonObject= new JSONObject();
    try {
        jsonObject.put("id", getIdProducto());
        jsonObject.put("nombre", getNombre());
        jsonObject.put("precio", getPrecio());

        return jsonObject.toString();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    }

}

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

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

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

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

How to convert interface{} to string?

To expand on what Peter said: Since you are looking to go from interface{} to string, type assertion will lead to headaches since you need to account for multiple incoming types. You'll have to assert each type possible and verify it is that type before using it.

Using fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) automatically handles the interface conversion. Since you know your desired output type is always a string, Sprintf will handle whatever type is behind the interface without a bunch of extra code on your behalf.

Forward host port to docker container

Your docker host exposes an adapter to all the containers. Assuming you are on recent ubuntu, you can run

ip addr

This will give you a list of network adapters, one of which will look something like

3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 22:23:6b:28:6b:e0 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
inet6 fe80::a402:65ff:fe86:bba6/64 scope link
   valid_lft forever preferred_lft forever

You will need to tell rabbit/mongo to bind to that IP (172.17.42.1). After that, you should be able to open connections to 172.17.42.1 from within your containers.

HashMap with multiple values under the same key

Another nice choice is to use MultiValuedMap from Apache Commons. Take a look at the All Known Implementing Classes at the top of the page for specialized implementations.

Example:

HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()

could be replaced with

MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();

So,

map.put(key, "A");
map.put(key, "B");
map.put(key, "C");

Collection<String> coll = map.get(key);

would result in collection coll containing "A", "B", and "C".

Where is Developer Command Prompt for VS2013?

I'm using VS 2012, so I navigated to "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Visual Studio 2012\Visual Studio Tools" and ran as administrator this "Developer Command Prompt for VS2012" shortcut. In command shell I pasted the suggested

aspnet_regiis -i

and as I suspected this did not yield any success on Windows 10: enter image description here

So all I needed to do was "Turn Windows Features On/Off" at Control Panel and restart my machine to effect the changes. That did resolve the issue. Thanks.

How to rotate x-axis tick labels in Pandas barplot

The question is clear but the title is not as precise as it could be. My answer is for those who came looking to change the axis label, as opposed to the tick labels, which is what the accepted answer is about. (The title has now been corrected).

for ax in plt.gcf().axes:
    plt.sca(ax)
    plt.xlabel(ax.get_xlabel(), rotation=90)

Checking if a string is empty or null in Java

This way you check if the string is not null and not empty, also considering the empty spaces:

boolean isEmpty = str == null || str.trim().length() == 0;
if (isEmpty) {
    // handle the validation
}

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Suppose I have the following table T:

a   b
--------
1   abc
1   def
1   ghi
2   jkl
2   mno
2   pqr

And I do the following query:

SELECT a, b
FROM T
GROUP BY a

The output should have two rows, one row where a=1 and a second row where a=2.

But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.

This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).

Fixing it might look like this:

SELECT a, MAX(b) AS x
FROM T
GROUP BY a

Now it's clear that you want the following result:

a   x
--------
1   ghi
2   pqr

PHP remove special character from string

Good try! I think you just have to make a few small changes:

  • Escape the square brackets ([ and ]) inside the character class (which are also indicated by [ and ])
  • Escape the escape character (\) itself
  • Plus there's a quirk where - is special: if it's between two characters, it means a range, but if it's at the beginning or the end, it means the literal - character.

You'll want something like this:

preg_replace('/[^a-zA-Z0-9_%\[().\]\\/-]/s', '', $String);

See http://docs.activestate.com/activeperl/5.10/lib/pods/perlrecharclass.html#special_characters_inside_a_bracketed_character_class if you want to read up further on this topic.

How to export datagridview to excel using vb.net?

In design mode: Set DataGridView1 ClipboardCopyMode properties to EnableAlwaysIncludeHeaderText

or on the program code

DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText

In the run time select all cells content (Ctrl+A) and copy (Ctrl+C) and paste to the Excel Program. Let the Excel do the rest

Sorry for the inconvenient, I have been searching the method to print data directly from the datagridvew (create report from vb.net VB2012) and have not found the satisfaction result. Above code just my though, wondering if my applications user can rely on above simple step it will be nice and I could go ahead to next step on my program progress.

update listview dynamically with adapter

SimpleListAdapter's are primarily used for static data! If you want to handle dynamic data, you're better off working with an ArrayAdapter, ListAdapter or with a CursorAdapter if your data is coming in from the database.

Here's a useful tutorial in understanding binding data in a ListAdapter

As referenced in this SO question

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

What exactly is a Context in Java?

A Context represents your environment. It represents the state surrounding where you are in your system.

For example, in web programming in Java, you have a Request, and a Response. These are passed to the service method of a Servlet.

A property of the Servlet is the ServletConfig, and within that is a ServletContext.

The ServletContext is used to tell the servlet about the Container that the Servlet is within.

So, the ServletContext represents the servlets environment within its container.

Similarly, in Java EE, you have EBJContexts that elements (like session beans) can access to work with their containers.

Those are two examples of contexts used in Java today.

Edit --

You mention Android.

Look here: http://developer.android.com/reference/android/content/Context.html

You can see how this Context gives you all sorts of information about where the Android app is deployed and what's available to it.

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

SELECT last id, without INSERT

In MySQL, this does return the highest value from the id column:

SELECT MAX(id) FROM tablename;

However, this does not put that id into $n:

$n = mysql_query("SELECT max(id) FROM tablename");

To get the value, you need to do this:

$result = mysql_query("SELECT max(id) FROM tablename");

if (!$result) {
    die('Could not query:' . mysql_error());
}

$id = mysql_result($result, 0, 'id');

If you want to get the last insert ID from A, and insert it into B, you can do it with one command:

INSERT INTO B (col) SELECT MAX(id) FROM A;

How to join two sets in one line without using "|"

You can do union or simple list comprehension

[A.add(_) for _ in B]

A would have all the elements of B

CSS to select/style first word

Sadly even with the likes of CSS 3 we still do not have the likes of :first-word :last-word etc using pure CSS. Thankfully there's almost a JavaScript nowadays for everything which brings me to my recommendation. Using nthEverything and jQuery you can expand from the traditional Pseudo elements.

Currently the valid Pseudos are:

  • :first-child
  • :first-of-type
  • :only-child
  • :last-child
  • :last-of-type
  • :only-of-type
  • :nth-child
  • :nth-of-type
  • :nth-last-child
  • :nth-last-of-type

And using nth Everything we can expand this to:

  • ::first-letter
  • ::first-line
  • ::first-word
  • ::last-letter
  • ::last-line
  • ::last-word
  • ::nth-letter
  • ::nth-line
  • ::nth-word
  • ::nth-last-letter
  • ::nth-last-line
  • ::nth-last-word

Property [title] does not exist on this collection instance

When you're using get() you get a collection. In this case you need to iterate over it to get properties:

@foreach ($collection as $object)
    {{ $object->title }}
@endforeach

Or you could just get one of objects by it's index:

{{ $collection[0]->title }}

Or get first object from collection:

{{ $collection->first() }}

When you're using find() or first() you get an object, so you can get properties with simple:

{{ $object->title }}

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

Go to Messages Gradle Sync, and Click on Install Repository and sync project. This is will install needed file in Android SDK and after syncing you will be able to create gradle or run your project.

Retrieve the maximum length of a VARCHAR column in SQL Server

Many times you want to identify the row that has that column with the longest length, especially if you are troubleshooting to find out why the length of a column on a row in a table is so much longer than any other row, for instance. This query will give you the option to list an identifier on the row in order to identify which row it is.

select ID, [description], len([description]) as descriptionlength
FROM [database1].[dbo].[table1]
where len([description]) = 
 (select max(len([description]))
  FROM [database1].[dbo].[table1]

Java ArrayList - how can I tell if two lists are equal, order not mattering?

If the cardinality of items doesn't matter (meaning: repeated elements are considered as one), then there is a way to do this without having to sort:

boolean result = new HashSet<>(listA).equals(new HashSet<>(listB));

This will create a Set out of each List, and then use HashSet's equals method which (of course) disregards ordering.

If cardinality matters, then you must confine yourself to facilities provided by List; @jschoen's answer would be more fitting in that case.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

file_put_contents(meta/services.json): failed to open stream: Permission denied

If you have Laravel 5 and looking permanent solution , applicable both php artisan command line usage and Apache server use this:

sudo chmod -R 777 vendor storage
echo "umask 000" | sudo tee -a /etc/resolv.conf
sudo service apache2 restart

See detailed explanation here.

socket connect() vs bind()

From Wikipedia http://en.wikipedia.org/wiki/Berkeley_sockets#bind.28.29

connect():

The connect() system call connects a socket, identified by its file descriptor, to a remote host specified by that host's address in the argument list.

Certain types of sockets are connectionless, most commonly user datagram protocol sockets. For these sockets, connect takes on a special meaning: the default target for sending and receiving data gets set to the given address, allowing the use of functions such as send() and recv() on connectionless sockets.

connect() returns an integer representing the error code: 0 represents success, while -1 represents an error.

bind():

bind() assigns a socket to an address. When a socket is created using socket(), it is only given a protocol family, but not assigned an address. This association with an address must be performed with the bind() system call before the socket can accept connections to other hosts. bind() takes three arguments:

sockfd, a descriptor representing the socket to perform the bind on. my_addr, a pointer to a sockaddr structure representing the address to bind to. addrlen, a socklen_t field specifying the size of the sockaddr structure. Bind() returns 0 on success and -1 if an error occurs.

Examples: 1.)Using Connect

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>

int main(){
  int clientSocket;
  char buffer[1024];
  struct sockaddr_in serverAddr;
  socklen_t addr_size;

  /*---- Create the socket. The three arguments are: ----*/
  /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
  clientSocket = socket(PF_INET, SOCK_STREAM, 0);

  /*---- Configure settings of the server address struct ----*/
  /* Address family = Internet */
  serverAddr.sin_family = AF_INET;
  /* Set port number, using htons function to use proper byte order */
  serverAddr.sin_port = htons(7891);
  /* Set the IP address to desired host to connect to */
  serverAddr.sin_addr.s_addr = inet_addr("192.168.1.17");
  /* Set all bits of the padding field to 0 */
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

  /*---- Connect the socket to the server using the address struct ----*/
  addr_size = sizeof serverAddr;
  connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size);

  /*---- Read the message from the server into the buffer ----*/
  recv(clientSocket, buffer, 1024, 0);

  /*---- Print the received message ----*/
  printf("Data received: %s",buffer);   

  return 0;
}

2.)Bind Example:

int main()
{
    struct sockaddr_in source, destination = {};  //two sockets declared as previously
    int sock = 0;
    int datalen = 0;
    int pkt = 0;

    uint8_t *send_buffer, *recv_buffer;

    struct sockaddr_storage fromAddr;   // same as the previous entity struct sockaddr_storage serverStorage;
    unsigned int addrlen;  //in the previous example socklen_t addr_size;
    struct timeval tv;
    tv.tv_sec = 3;  /* 3 Seconds Time-out */
    tv.tv_usec = 0;

    /* creating the socket */         
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) 
        printf("Failed to create socket\n");

    /*set the socket options*/
    setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));

    /*Inititalize source to zero*/
    memset(&source, 0, sizeof(source));       //source is an instance of sockaddr_in. Initialization to zero
    /*Inititalize destinaton to zero*/
    memset(&destination, 0, sizeof(destination));


    /*---- Configure settings of the source address struct, WHERE THE PACKET IS COMING FROM ----*/
    /* Address family = Internet */
    source.sin_family = AF_INET;    
    /* Set IP address to localhost */   
    source.sin_addr.s_addr = INADDR_ANY;  //INADDR_ANY = 0.0.0.0
    /* Set port number, using htons function to use proper byte order */
    source.sin_port = htons(7005); 
    /* Set all bits of the padding field to 0 */
    memset(source.sin_zero, '\0', sizeof source.sin_zero); //optional


    /*bind socket to the source WHERE THE PACKET IS COMING FROM*/
    if (bind(sock, (struct sockaddr *) &source, sizeof(source)) < 0) 
        printf("Failed to bind socket");

    /* setting the destination, i.e our OWN IP ADDRESS AND PORT */
    destination.sin_family = AF_INET;                 
    destination.sin_addr.s_addr = inet_addr("127.0.0.1");  
    destination.sin_port = htons(7005); 

    //Creating a Buffer;
    send_buffer=(uint8_t *) malloc(350);
    recv_buffer=(uint8_t *) malloc(250);

    addrlen=sizeof(fromAddr);

    memset((void *) recv_buffer, 0, 250);
    memset((void *) send_buffer, 0, 350);

    sendto(sock, send_buffer, 20, 0,(struct sockaddr *) &destination, sizeof(destination));

    pkt=recvfrom(sock, recv_buffer, 98,0,(struct sockaddr *)&destination, &addrlen);
    if(pkt > 0)
        printf("%u bytes received\n", pkt);
    }

I hope that clarifies the difference

Please note that the socket type that you declare will depend on what you require, this is extremely important

Get Windows version in a batch file

wmic os get Caption,CSDVersion /value

This will do the job.

Print range of numbers on same line

Same can be achieved by using stdout.

>>> from sys import stdout
>>> for i in range(1,11):
...     stdout.write(str(i)+' ')
...
1 2 3 4 5 6 7 8 9 10 

Alternatively, same can be done by using reduce() :

>>> xrange = range(1,11)
>>> print reduce(lambda x, y: str(x) + ' '+str(y), xrange)
1 2 3 4 5 6 7 8 9 10
>>>

How to animate button in android?

I can't comment on @omega's comment because I don't have enough reputation but the answer to that question should be something like:

shake.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"          <!-- how long the animation lasts -->
    android:fromDegrees="-5"        <!-- how far to swing left -->
    android:pivotX="50%"            <!-- pivot from horizontal center -->
    android:pivotY="50%"            <!-- pivot from vertical center -->
    android:repeatCount="10"        <!-- how many times to swing back and forth -->
    android:repeatMode="reverse"    <!-- to make the animation go the other way -->
    android:toDegrees="5" />        <!-- how far to swing right -->

Class.java

Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
view.startAnimation(shake);

This is just one way of doing what you want, there may be better methods out there.

Overriding a JavaScript function while referencing the original

So my answer ended up being a solution that allows me to use the _this variable pointing to the original object. I create a new instance of a "Square" however I hated the way the "Square" generated it's size. I thought it should follow my specific needs. However in order to do so I needed the square to have an updated "GetSize" function with the internals of that function calling other functions already existing in the square such as this.height, this.GetVolume(). But in order to do so I needed to do this without any crazy hacks. So here is my solution.

Some other Object initializer or helper function.

this.viewer = new Autodesk.Viewing.Private.GuiViewer3D(
  this.viewerContainer)
var viewer = this.viewer;
viewer.updateToolbarButtons =  this.updateToolbarButtons(viewer);

Function in the other object.

updateToolbarButtons = function(viewer) {
  var _viewer = viewer;
  return function(width, height){ 
blah blah black sheep I can refer to this.anything();
}
};

Is there any method to get the URL without query string?

Try this: window.location.href.split('?')[0]

Maven version with a property

See the Maven - Users forum 'version' contains an expression but should be a constant. Better way to add a new version?:

here is why this is a bad plan.

the pom that gets deployed will not have the property value resolved, so anyone depending on that pom will pick up the dependency as being the string uninterpolated with the ${ } and much hilarity will ensue in your build process.

in maven 2.1.0 and/or 2.2.0 an attempt was made to deploy poms with resolved properties... this broke more than expected, which is why those two versions are not recommended, 2.2.1 being the recommended 2.x version.

Confused by python file mode "w+"

Here is a list of the different modes of opening a file:

  • r

    Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

  • rb

    Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

  • r+

    Opens a file for both reading and writing. The file pointer will be at the beginning of the file.

  • rb+

    Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.

  • w

    Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • wb

    Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • w+

    Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • wb+

    Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • a

    Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • ab

    Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • a+

    Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

  • ab+

    Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Call to undefined function oci_connect()

Alright, folks.

First, use

<?php 
phpinfo();
?> 

and determine your PHP Version (located at the very top, e.g. 7.0.xxx) and also, your PHP Version architecture: x64 or x86 and also, Thread Safe or Not THread Safe (located in the first table as "Thread Safety".) "Disabled" obviously means "Not Thread Safe".

It is absolutely critical that the following three pieces of software that you will need are:

  1. for the same major version of PHP (7.0 for 7.0.xxx)
  2. same version of Oracle as the version you are accessing (11g, 12g, etc)
  3. the same Not Thread Safe / Thread Safe version of PHP
  4. all for the same architecture.

If any of the following are for a different architecture, Not Thread Safe/Thread Safe version, PHP major version number, or database version, you'll get errors:

 1. PHP for Windows
 2. OCI8 PECL Drivers for PHP (https://pecl.php.net/package/oci8)
 3. Oracle Instant Client

Remember: If you are connecting to an 11g Oracle instance, you need an 11g driver.

Second, install the correct PHP, OCI8 PECL Driver, and instant client.

I chose:

d:\php\ for php
d:\oci\ for instant client
unzip the contents of the OCI8 PECL Driver into d:\php\ext\

Third, modify d:\php\php.ini according the instructions given by Oracle:

1. set the extension directory
2. set only one of the following:
  a. for 11g drivers, use extension=php_oci8_11g.dll
  b. for 12c drivers, use extension=php_oci8_12c.dll
  c. for other oracle DB drivers, use the correct oracle extension.

Fourth: Add d:\oci\ (or whatever your instant client install location is) to your system PATH.

Fifth: reboot your PC.

Sixth, on a command prompt, type "where oci*" and verify that your Instant Client install path version of oci.dll is present.

Seventh, go to d:\php\ and type "php -m" and you should see OCI8 in the list.

If you do not see OCI8 in the list of modules after typing "php -m", open up d:\php\errorlog.txt

If you see something like:

PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\php_oci8_11g.dll' - %1 is not a valid Win32 application.

then either instant client or your PECL driver download is not the same architecture as your PHP version.

If you see something like:

PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\php_oci8_12c.dll' - The specified procedure could not be found.

then you are using the wrong OCI8 PECL driver for your version of instant client.

Hope this helps.

Convert unsigned int to signed int C

I know it's an old question, but it's a good one, so how about this?

unsigned short int x = 65529U;
short int y = *(short int*)&x;

printf("%d\n", y);

The name does not exist in the namespace error in XAML

  • In my particular case, the problem looks like a bug in Visual Studio - because the error didn't make any sense! This is what worked for me: perhaps it may work for you as well?

Solution: Try Re-building the solution

  • Short cut to re-build: CTRL + SHIFT + B

Simply rebuild and it should work!

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

If you just need to get a few items from the JSON object, I would use Json.NET's LINQ to JSON JObject class. For example:

JToken token = JObject.Parse(stringFullOfJson);

int page = (int)token.SelectToken("page");
int totalPages = (int)token.SelectToken("total_pages");

I like this approach because you don't need to fully deserialize the JSON object. This comes in handy with APIs that can sometimes surprise you with missing object properties, like Twitter.

Documentation: Serializing and Deserializing JSON with Json.NET and LINQ to JSON with Json.NET

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

This may be late, but sharing it for the new users visiting this question. To drop multiple columns actual syntax is

alter table tablename drop column col1, drop column col2 , drop column col3 ....

So for every column you need to specify "drop column" in Mysql 5.0.45.

Error With Port 8080 already in use

The solution to this issue is:

Step 1: Stop Tomcat(By service or by .bat/.sh what ever the case may be ).

Step 2: Delete the already configured Apache Tomcat on eclipse.

Step 3: Now reconfigure the apache on the eclipse and start the server using UI as provided by eclipse.

I have the same issue and it has worked.

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

When we get this error while running our java application, check if we have some class name or package names starting with ”java.”, if so change the package name. This is happening because your package name is colliding with java system file names.

Use jQuery to change an HTML tag?

This the quick way to change HTML tags inside your DOM using jQuery. I find this replaceWith() function is very useful.

   var text= $('p').text();
   $('#change').on('click', function() {
     target.replaceWith( "<h5>"+text+"</h5>" );
   });

RuntimeWarning: DateTimeField received a naive datetime

You can also override settings, particularly useful in tests:

from django.test import override_settings

with override_settings(USE_TZ=False):
    # Insert your code that causes the warning here
    pass

This will prevent you from seeing the warning, at the same time anything in your code that requires a timezone aware datetime may give you problems. If this is the case, see kravietz answer.

MySQL string replace

The replace function should work for you.

REPLACE(str,from_str,to_str)

Returns the string str with all occurrences of the string from_str replaced by the string to_str. REPLACE() performs a case-sensitive match when searching for from_str.

Install Qt on Ubuntu

In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.

For QtCreator and Examples and API Docs:

sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `

sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`

sudo apt-get install build-essential qtcreator qt5-default

If something is also missing, then:

sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `

Hope to be helpful.

Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing

Execute combine multiple Linux commands in one line

To run them all at once, you can use the pipe line key "|" like so:

$ cd /my_folder | rm *.jar | svn co path to repo | mvn compile package install

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

Load data from txt with pandas

You can use:

data = pd.read_csv('output_list.txt', sep=" ", header=None)
data.columns = ["a", "b", "c", "etc."]

Add sep=" " in your code, leaving a blank space between the quotes. So pandas can detect spaces between values and sort in columns. Data columns is for naming your columns.

WordPress: get author info from post id

<?php
  $field = 'display_name';
  the_author_meta($field);
?>

Valid values for the $field parameter include:

  • admin_color
  • aim
  • comment_shortcuts
  • description
  • display_name
  • first_name
  • ID
  • jabber
  • last_name
  • nickname
  • plugins_last_view
  • plugins_per_page
  • rich_editing
  • syntax_highlighting
  • user_activation_key
  • user_description
  • user_email
  • user_firstname
  • user_lastname
  • user_level
  • user_login
  • user_nicename
  • user_pass
  • user_registered
  • user_status
  • user_url
  • yim

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

Yet another approach is ISNULL().

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

The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.

select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'

Sum all the elements java arraylist

Two ways:

Use indexes:

double sum = 0;
for(int i = 0; i < m.size(); i++)
    sum += m.get(i);
return sum;

Use the "for each" style:

double sum = 0;
for(Double d : m)
    sum += d;
return sum;

Google Maps v2 - set both my location and zoom in

Its a late answer but I think it will help. Use this method:

protected void zoomMapInitial(LatLng finalPlace, LatLng currenLoc) {
    try {
        int padding = 200; // Space (in px) between bounding box edges and view edges (applied to all four sides of the bounding box)
        LatLngBounds.Builder bc = new LatLngBounds.Builder();

        bc.include(finalPlace);
        bc.include(currenLoc);
        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bc.build(), padding));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Use this method after loading the map. Cheers!

Fatal error: Call to undefined function imap_open() in PHP

For Xampp 7.3.9

PHP.ini line 913:

;extension=imap

You should remove the semicolon.

How to see what privileges are granted to schema of another user

Use example with from the post of Szilágyi Donát.

I use two querys, one to know what roles I have, excluding connect grant:

SELECT * FROM USER_ROLE_PRIVS WHERE GRANTED_ROLE != 'CONNECT'; -- Roles of the actual Oracle Schema

Know I like to find what privileges/roles my schema/user have; examples of my roles ROLE_VIEW_PAYMENTS & ROLE_OPS_CUSTOMERS. But to find the tables/objecst of an specific role I used:

SELECT * FROM ALL_TAB_PRIVS WHERE GRANTEE='ROLE_OPS_CUSTOMERS'; -- Objects granted at role.

The owner schema for this example could be PRD_CUSTOMERS_OWNER (or the role/schema inself).

Regards.

Xcode 6 Storyboard the wrong size?

You shall probably use the "Resolve Auto Layout Issues" (bottom right - triangle icon in the storyboard view) to add/reset to suggested constraints (Xcode 6.0.1).

INNER JOIN vs INNER JOIN (SELECT . FROM)

There won't be much difference. Howver version 2 is easier when you have some calculations, aggregations, etc that should be joined outside of it

--Version 2 
SELECT p.Name, s.OrderQty 
FROM Product p 
INNER JOIN 
(SELECT ProductID, SUM(OrderQty) as OrderQty FROM SalesOrderDetail GROUP BY ProductID
HAVING SUM(OrderQty) >1000) s 
on p.ProductID = s.ProdctId 

Detect click outside Angular component

ginalx's answer should be set as the default one imo: this method allows for many optimizations.

The problem

Say that we have a list of items and on every item we want to include a menu that needs to be toggled. We include a toggle on a button that listens for a click event on itself (click)="toggle()", but we also want to toggle the menu whenever the user clicks outside of it. If the list of items grows and we attach a @HostListener('document:click') on every menu, then every menu loaded within the item will start listening for the click on the entire document, even when the menu is toggled off. Besides the obvious performance issues, this is unnecessary.

You can, for example, subscribe whenever the popup gets toggled via a click and start listening for "outside clicks" only then.


isActive: boolean = false;

// to prevent memory leaks and improve efficiency, the menu
// gets loaded only when the toggle gets clicked
private _toggleMenuSubject$: BehaviorSubject<boolean>;
private _toggleMenu$: Observable<boolean>;

private _toggleMenuSub: Subscription;
private _clickSub: Subscription = null;


constructor(
 ...
 private _utilitiesService: UtilitiesService,
 private _elementRef: ElementRef,
){
 ...
 this._toggleMenuSubject$ = new BehaviorSubject(false);
 this._toggleMenu$ = this._toggleMenuSubject$.asObservable();

}

ngOnInit() {
 this._toggleMenuSub = this._toggleMenu$.pipe(
      tap(isActive => {
        logger.debug('Label Menu is active', isActive)
        this.isActive = isActive;

        // subscribe to the click event only if the menu is Active
        // otherwise unsubscribe and save memory
        if(isActive === true){
          this._clickSub = this._utilitiesService.documentClickedTarget
           .subscribe(target => this._documentClickListener(target));
        }else if(isActive === false && this._clickSub !== null){
          this._clickSub.unsubscribe();
        }

      }),
      // other observable logic
      ...
      ).subscribe();
}

toggle() {
    this._toggleMenuSubject$.next(!this.isActive);
}

private _documentClickListener(targetElement: HTMLElement): void {
    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this._toggleMenuSubject$.next(false);
    }    
 }

ngOnDestroy(){
 this._toggleMenuSub.unsubscribe();
}

And, in *.component.html:


<button (click)="toggle()">Toggle the menu</button>

git - Server host key not cached

I suspect that your GIT_SSH environment variable is set to %ProgramFiles(x86)%\putty\plink.exe. For some reason, PLink does not use the .ssh/known_hosts file in your user directory to store the remote hosts keys.

If this is actually your case, and it might be so on purpose if you want to use pageant, you need to use PLink to connect to the host first.

"$GIT_SSH" user@hostname

You should get a similar message

The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 86:7b:1b:12:85:35:8a:b7:98:b6:d2:97:5e:96:58:1d
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)

Once you have answered y to the question and successfully connected to the remote host, you should be all set. Go ahead and try your push again.

Proper way to return JSON using node or Express

You can make a helper for that: Make a helper function so that you can use it everywhere in your application

function getStandardResponse(status,message,data){
    return {
        status: status,
        message : message,
        data : data
     }
}

Here is my topic route where I am trying to get all topics

router.get('/', async (req, res) => {
    const topics = await Topic.find().sort('name');
    return res.json(getStandardResponse(true, "", topics));
});

Response we get

{
"status": true,
"message": "",
"data": [
    {
        "description": "sqswqswqs",
        "timestamp": "2019-11-29T12:46:21.633Z",
        "_id": "5de1131d8f7be5395080f7b9",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575031579309.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "sqswqswqs",
        "timestamp": "2019-11-29T12:50:35.627Z",
        "_id": "5de1141bc902041b58377218",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575031835605.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": " ",
        "timestamp": "2019-11-30T06:51:18.936Z",
        "_id": "5de211665c3f2c26c00fe64f",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575096678917.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "null",
        "timestamp": "2019-11-30T06:51:41.060Z",
        "_id": "5de2117d5c3f2c26c00fe650",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575096701051.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "swqdwqd wwwwdwq",
        "timestamp": "2019-11-30T07:05:22.398Z",
        "_id": "5de214b2964be62d78358f87",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575097522372.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "swqdwqd wwwwdwq",
        "timestamp": "2019-11-30T07:36:48.894Z",
        "_id": "5de21c1006f2b81790276f6a",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575099408870.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    }
      ]
}

How to pass params with history.push/Link/Redirect in react-router v4?

To use React 16.8+(withHooks) you can use this way

import React from 'react';
import { useHistory } from 'react-router-dom';

export default function SomeFunctionalComponent() {
let history = useHistory(); // should be called inside react component

const handleClickButton = () => {    
"funcionAPICALL"
       .then(response => {
             if (response.status >= 200 && response.status < 300) {
                 history.push('/template');
              });
}

return ( <div> Some component stuff 
    <p>To make API POST request and redirect to "/template" click a button API CALL</p>
    <button onClick={handleClickButton}>API CALL<button>
</div>)
} 

Source here to read more https://reacttraining.com/react-router/web/example/auth-workflow

Error handling in AngularJS http get then construct

You need to add an additional parameter:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })

Counting array elements in Perl

sub uniq {
    return keys %{{ map { $_ => 1 } @_ }};
}
my @my_array = ("a","a","b","b","c");
#print join(" ", @my_array), "\n";
my $a = join(" ", uniq(@my_array));
my @b = split(/ /,$a);
my $count = $#b;

Inject service in app.config

Alex provided the correct reason for not being able to do what you're trying to do, so +1. But you are encountering this issue because you're not quite using resolves how they're designed.

resolve takes either the string of a service or a function returning a value to be injected. Since you're doing the latter, you need to pass in an actual function:

resolve: {
  data: function (dbService) {
    return dbService.getData();
  }
}

When the framework goes to resolve data, it will inject the dbService into the function so you can freely use it. You don't need to inject into the config block at all to accomplish this.

Bon appetit!

Javascript Uncaught Reference error Function is not defined

If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:

$('#exampleBtn').click(function() {
  function();
});

How to launch Windows Scheduler by command-line?

Here is an example I just used:

at 8am /EVERY:M,T,W,Th,F,S,Su cmd /c c:\myapp.exe

The result was:

Added a new job with job ID = 1

Then, to check my work:

at

How to dynamically add a class to manual class names?

Here is the Best Option for Dynamic className , just do some concatenation like we do in Javascript.

     className={
        "badge " +
        (this.state.value ? "badge-primary " : "badge-danger ") +
        " m-4"
      }

Using PUT method in HTML form

According to the HTML standard, you can not. The only valid values for the method attribute are get and post, corresponding to the GET and POST HTTP methods. <form method="put"> is invalid HTML and will be treated like <form>, i.e. send a GET request.

Instead, many frameworks simply use a POST parameter to tunnel the HTTP method:

<form method="post" ...>
  <input type="hidden" name="_method" value="put" />
...

Of course, this requires server-side unwrapping.

show all tables in DB2 using the LIST command

select * from syscat.tables where type = 'T'

you may want to restrict the query to your tabschema

What's the best way to cancel event propagation between nested ng-click calls?

Sometimes, it may make most sense just to do this:

<widget ng-click="myClickHandler(); $event.stopPropagation()"/>

I chose to do it this way because I didn't want myClickHandler() to stop the event propagation in the many other places it was used.

Sure, I could've added a boolean parameter to the handler function, but stopPropagation() is much more meaningful than just true.

How to handle back button in activity

This is a simple way of doing something.

    @Override
        public void onBackPressed() {
            // do what you want to do when the "back" button is pressed.
            startActivity(new Intent(Activity.this, MainActivity.class));
            finish();
        }

I think there might be more elaborate ways of going about it, but I like simplicity. For example, I used the template above to make the user sign out of the application AND THEN go back to another activity of my choosing.

Unix epoch time to Java Date object

Better yet, use JodaTime. Much easier to parse strings and into strings. Is thread safe as well. Worth the time it will take you to implement it.

How to change the order of DataFrame columns?

Most of the answers did not generalize enough and pandas reindex_axis method is a little tedious, hence I offer a simple function to move an arbitrary number of columns to any position using a dictionary where key = column name and value = position to move to. If your dataframe is large pass True to 'big_data' then the function will return the ordered columns list. And you could use this list to slice your data.

def order_column(df, columns, big_data = False):

    """Re-Orders dataFrame column(s)
       Parameters : 
       df      -- dataframe
       columns -- a dictionary:
                  key   = current column position/index or column name
                  value = position to move it to  
       big_data -- boolean 
                  True = returns only the ordered columns as a list
                          the user user can then slice the data using this
                          ordered column
                  False = default - return a copy of the dataframe
    """
    ordered_col = df.columns.tolist()

    for key, value in columns.items():

        ordered_col.remove(key)
        ordered_col.insert(value, key)

    if big_data:

        return ordered_col

    return df[ordered_col]

# e.g.
df = pd.DataFrame({'chicken wings': np.random.rand(10, 1).flatten(), 'taco': np.random.rand(10,1).flatten(),
                          'coffee': np.random.rand(10, 1).flatten()})
df['mean'] = df.mean(1)

df = order_column(df, {'mean': 0, 'coffee':1 })

>>>

output

col = order_column(df, {'mean': 0, 'coffee':1 }, True)

col
>>>
['mean', 'coffee', 'chicken wings', 'taco']

# you could grab it by doing this

df = df[col]

You must add a reference to assembly 'netstandard, Version=2.0.0.0

You can add to your web.config in your project.

It wouldn't work when you add it to projects web.config because it works with MVC.

The Import android.support.v7 cannot be resolved

  1. Go to your project in the navigator, right click on properties.

  2. Go to the Java Build Path tab on the left.

  3. Go to the libraries tab on top.

  4. Click add external jars.

  5. Go to your ADT Bundle folder, go to sdk/extras/android/support/v7/appcompat/libs.

  6. Select the file android-support-v7-appcompat.jar

  7. Go to order and export and check the box next to your new jar.

  8. Click ok.

How to create file execute mode permissions in Git on Windows?

I have no touch and chmod command in my cmd.exe and git update-index --chmod=+x foo.sh doesn't work for me.

I finally resolve it by setting skip-worktree bit:

git update-index --skip-worktree --chmod=+x foo.sh

How to trim a file extension from a String in JavaScript?

If you know the length of the extension, you can use x.slice(0, -4) (where 4 is the three characters of the extension and the dot).

If you don't know the length @John Hartsock regex would be the right approach.

If you'd rather not use regular expressions, you can try this (less performant):

filename.split('.').slice(0, -1).join('.')

Note that it will fail on files without extension.

How to increment an iterator by 2?

std::advance( iter, 2 );

This method will work for iterators that are not random-access iterators but it can still be specialized by the implementation to be no less efficient than iter += 2 when used with random-access iterators.

LaTeX package for syntax highlighting of code in various languages

LGrind does this. It's a mature LaTeX package that's been around since adam was a cowboy and has support for many programming languages.

How to join a slice of strings into a single string?

This is still relevant in 2018.

To String

import strings
stringFiles := strings.Join(fileSlice[:], ",")

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")

How to track untracked content?

This worked out just fine for me:

git update-index --skip-worktree

If it doesn't work with the pathname, try the filename. Let me know if this worked for you too.

Bye!

ORA-00932: inconsistent datatypes: expected - got CLOB

The problem may lie in selected null values ??in combination with a CLOB-type column.

select valueVarchar c1 ,
       valueClob c2 ,
       valueVarchar c3 ,
       valueVvarchar c4
of Table_1
union
select valueVarchar c1 ,
       valueClob c2 ,
       valueVarchar c3 ,
       null c4
of table_2

I reworked the cursor. The first cursor is composed of four non-null columns. The second cursor selects three non-null columns. The null values ??were injected into the cursorForLoop .

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

Change your code to.

<?php
$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".$rows['user'];
?>

There was syntax error in your query.

Convert unix time to readable date in pandas dataframe

These appear to be seconds since epoch.

In [20]: df = DataFrame(data['values'])

In [21]: df.columns = ["date","price"]

In [22]: df
Out[22]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 358 entries, 0 to 357
Data columns (total 2 columns):
date     358  non-null values
price    358  non-null values
dtypes: float64(1), int64(1)

In [23]: df.head()
Out[23]: 
         date  price
0  1349720105  12.08
1  1349806505  12.35
2  1349892905  12.15
3  1349979305  12.19
4  1350065705  12.15
In [25]: df['date'] = pd.to_datetime(df['date'],unit='s')

In [26]: df.head()
Out[26]: 
                 date  price
0 2012-10-08 18:15:05  12.08
1 2012-10-09 18:15:05  12.35
2 2012-10-10 18:15:05  12.15
3 2012-10-11 18:15:05  12.19
4 2012-10-12 18:15:05  12.15

In [27]: df.dtypes
Out[27]: 
date     datetime64[ns]
price           float64
dtype: object

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

Just add

spring.flyway.enabled=false

in application.properties file if you do not want flyway to check the checksum every time you run the application.

Why can't I change my input value in React even with the onChange listener

In react, state will not change until you do it by using this.setState({});. That is why your console message showing old values.

Getting all file names from a folder using C#

DirectoryInfo d = new DirectoryInfo(@"D:\Test");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach(FileInfo file in Files )
{
  str = str + ", " + file.Name;
}

Hope this will help...

Rename multiple files in cmd

I tried pasting Endoro's command (Thanks Endoro) directly into the command prompt to add a prefix to files but encountered an error. Solution was to reduce %% to %, so:

for /f "delims=" %i in ('dir /b /a-d *.*') do ren "%~i" "Service.Enviro.%~ni%~xi"

How to insert programmatically a new line in an Excel cell in C#?

Using PEAR 'Spreadsheet_Excel_Writer' and 'OLE':

Only way I could get "\n" to work was making the cell $format->setTextWrap(); and then using "\n" would work.

Browse for a directory in C#

string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
    folderPath = folderBrowserDialog1.SelectedPath ;
}

How to get cell value from DataGridView in VB.Net?

To get the value of cell, use the following syntax,

datagridviewName(columnFirst, rowSecond).value

But the intellisense and MSDN documentation is wrongly saying rowFirst, colSecond approach...

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

How to override Bootstrap's Panel heading background color?

.panel-default >.panel-heading
{
    background: #ffffff;
}

This is what worked for me to change the color to white.

How to open a PDF file in an <iframe>?

It also important to make sure that the web server sends the file with Content-Disposition = inline. this might not be the case if you are reading the file yourself and send it's content to the browser:

in php it will look like this...

...headers...
header("Content-Disposition: inline; filename=doc.pdf");
...headers...

readfile('localfilepath.pdf')

Reading and writing binary file

If you want to do this the C++ way, do it like this:

#include <fstream>
#include <iterator>
#include <algorithm>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );
    std::ofstream output( "C:\\myfile.gif", std::ios::binary );

    std::copy( 
        std::istreambuf_iterator<char>(input), 
        std::istreambuf_iterator<char>( ),
        std::ostreambuf_iterator<char>(output));
}

If you need that data in a buffer to modify it or something, do this:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );

    // copies all data into buffer
    std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});

}

Best way to parse RSS/Atom feeds with PHP

Another great free parser - http://bncscripts.com/free-php-rss-parser/ It's very light ( only 3kb ) and simple to use!

How to set UITextField height?

swift3

@IBDesignable
class BigTextField: UITextField {
    override func didMoveToWindow() {
        super.didMoveToWindow()
        if window != nil {
            borderStyle = .roundedRect
        }
    }
}

Interface Builder

  • Replace UITextField with BigTextField.
  • Change the Border Style to none.