Programs & Examples On #Jboss

JBoss Application Server (JBoss AS) is a free software/open-source Java EE-based, Cross-platform Application Server.

PersistenceContext EntityManager injection NullPointerException

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

HTTP response header content disposition for attachments

Try the Content-Disposition header

Content-Disposition: attachment; filename=<file name.ext> 

JBoss default password

The default credentials are:

login: admin
password: admin

But if you use EAP these credentials are turned off by default and there is no active user (security reasons :)). If you want to turn on these users, you have to edit the following file in your current profile: ./deploy/management/console-mgr.sar/web-console.war/WEB-INF/classes/web-console-users.properties. It should be enough to remove the # sign from the line with the user.

If you want to create a new user, don't forget to set up the correct groups in web-console-roles.properties file.

You can easily find information where these information are stored: just open the ./conf/login-config.xml file and find the proper security domain definition. In the case of the Web Console application, it will be web-console policy.

Also if you want to have access to JMX, you have unlock JMX Console. Just check the following files in the conf/props/ directory (in your profile): jmx-console-users.properties and jmx-console-roles.properties.

PSQLException: current transaction is aborted, commands ignored until end of transaction block

I got this error using Java and PostgreSQL doing an insert on a table. I will illustrate how you can reproduce this error:

org.postgresql.util.PSQLException: ERROR: 
current transaction is aborted, commands ignored until end of transaction block

Summary:

The reason you get this error is because you have entered a transaction and one of your SQL Queries failed, and you gobbled up that failure and ignored it. But that wasn't enough, THEN you used that same connection, using the SAME TRANSACTION to run another query. The exception gets thrown on the second, correctly formed query because you are using a broken transaction to do additional work. PostgreSQL by default stops you from doing this.

I'm using: PostgreSQL 9.1.6 on x86_64-redhat-linux-gnu, compiled by gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2), 64-bit".

My PostgreSQL driver is: postgresql-9.2-1000.jdbc4.jar

Using Java version: Java 1.7

Here is the table create statement to illustrate the Exception:

CREATE TABLE moobar
(
    myval   INT
);

Java program causes the error:

public void postgresql_insert()
{
    try  
    {
        connection.setAutoCommit(false);  //start of transaction.
        
        Statement statement = connection.createStatement();
        
        System.out.println("start doing statement.execute");
        
        statement.execute(
                "insert into moobar values(" +
                "'this SQL statement fails, and it " +
                "is gobbled up by the catch, okfine'); ");
     
        //The above line throws an exception because we try to cram
        //A string into an Int.  I Expect this, what happens is we gobble 
        //the Exception and ignore it like nothing is wrong.
        //But remember, we are in a TRANSACTION!  so keep reading.

        System.out.println("statement.execute done");
        
        statement.close();
        
    }
    catch (SQLException sqle)
    {
        System.out.println("keep on truckin, keep using " +
                "the last connection because what could go wrong?");
    }
    
    try{
        Statement statement = connection.createStatement();
        
        statement.executeQuery("select * from moobar");

        //This SQL is correctly formed, yet it throws the 
        //'transaction is aborted' SQL Exception, why?  Because:
        //A.  you were in a transaction.
        //B.  You ran a SQL statement that failed.
        //C.  You didn't do a rollback or commit on the affected connection.
        
    }
    catch (SQLException sqle)
    {
        sqle.printStackTrace();
    }   

}

The above code produces this output for me:

start doing statement.execute

keep on truckin, keep using the last connection because what could go wrong?

org.postgresql.util.PSQLException: 
  ERROR: current transaction is aborted, commands ignored until 
  end of transaction block

Workarounds:

You have a few options:

  1. Simplest solution: Don't be in a transaction. Set the connection.setAutoCommit(false); to connection.setAutoCommit(true);. It works because then the failed SQL is just ignored as a failed SQL statement. You are welcome to fail SQL statements all you want and PostgreSQL won't stop you.

  2. Stay being in a transaction, but when you detect that the first SQL has failed, either rollback/re-start or commit/restart the transaction. Then you can continue failing as many SQL queries on that database connection as you want.

  3. Don't catch and ignore the Exception that is thrown when a SQL statement fails. Then the program will stop on the malformed query.

  4. Get Oracle instead, Oracle doesn't throw an exception when you fail a query on a connection within a transaction and continue using that connection.

In defense of PostgreSQL's decision to do things this way... Oracle was making you soft in the middle letting you do dumb stuff and overlooking it.

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

You can view this dump from the UNIX console.

The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.

E.g.:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"

You can view the dump from the console on the mentioned path.

Hot deploy on JBoss - how do I make JBoss "see" the change?

I've been developing a project with Eclipse and Wildfly and the exploded EAR file was getting big due to deploying of all the 3rd party libraries I needed in the application. I was pointing the deployment to my Maven repository which I guess was recopying the jars each time. So redeploying the application when ever I changed Java code in the service layer was turning into a nightmare.

Then having turned to Hotswap agent this helped a lot as far as seeing changes to EJB code without redeploying the application.

However I have recently upgraded to Wildfly 10, Java 8 and JBoss Developer Studio 10 and during that process I took the time to move all my 3rd party application jars e.g. primefaces into Wildfly modules and I removed my Maven repo from my deployment config. Now redeploying the entire application which is a pretty big one via Eclipse takes just a few seconds and it is much much faster than before. I don't even feel the need to install Hotswap and don't want to risk it anyway right now.

So if you are building under Eclipse with Wildfly then keep you application clear of 3rd party libs using Wildfly Modules and you'll be much better off.

getResourceAsStream() is always returning null

To my knowledge the file has to be right in the folder where the 'this' class resides, i.e. not in WEB-INF/classes but nested even deeper (unless you write in a default package):

net/domain/pkg1/MyClass.java  
net/domain/pkg1/abc.txt

Putting the file in to your java sources should work, compiler copies that file together with class files.

JBoss debugging in Eclipse

You mean remote debug JBoss from Eclipse ?

From Configuring Eclipse for Remote Debugging:

Set the JAVA_OPTS variable as follows:

set JAVA_OPTS= -Xdebug -Xnoagent 
   -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n %JAVA_OPTS%

or:

JAVA_OPTS="-Xdebug -Xnoagent 
  -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n $JAVA_OPTS"

In the Debug frame, select the Remote Java Application node.

In the Connection Properties, specify localhost as the Host and specify the Port as the port that was specified in the run batch script of the JBoss server, 8787.

JBoss Debug

What is the difference between Tomcat, JBoss and Glassfish?

It seems a bit discouraging to use Tomcat when you read these answers. However what most fail to mention is that you can get to identical or almost identical use cases with tomcat but that requires you to add the libraries needed (through Maven or whatever include system you use).

I have been running tomcat with JPA, EJBs with very small configuration efforts.

javax.naming.NameNotFoundException

The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.

As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:

/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml

The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.

BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is

@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
   public void bussinesMethod(){

   }
}

No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.

Now in your client code you need to lookup "MyComponentName".

JBoss AS 7: How to clean up tmp?

Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :

-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache 
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440

How to increase heap size for jBoss server

What to change?

set "JAVA_OPTS=%JAVA_OPTS% -Xms1024m -Xmx2048m"

Where to change? (Normally)

bin/standalone.conf(Linux) standalone.conf.bat(Windows)

What if you are using custom script which overrides the existing settings? then?

setAppServerEnvironment.cmd/.sh (kind of file name will be there)

More information are already provided by one of our committee members! BalusC.

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

Best solution: Goto jboss-as-7.1.1.Final\standalone\deployments folder and delete all existing files....

Run again your problem will be solved

What version of JBoss I am running?

If you know the location of installed jboss folder then simply open it and look for version.txt file.

How to call a stored procedure from Java and JPA

If using EclipseLink you can use the @NamedStoredProcedureQuery or StoreProcedureCall to execute any stored procedure, including ones with output parameters, or out cursors. Support for stored functions and PLSQL data-types is also available.

See, http://en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Stored_Procedures

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

Sometimes it is the simple things. In my case, I had an invalid url. I had left out a colon before the at sign (@). I had "jdbc:oracle:thin@//localhost" instead of "jdbc:oracle:thin:@//localhost" Hope this helps someone else with this issue.

How to deploy a war file in JBoss AS 7?

open up console and navigate to bin folder and run

JBOSS_HOME/bin > stanalone.sh

Once it is up and running just copy past your war file in

standalone/deployments folder

Thats probably it for jboss 7.1

How to change webservice url endpoint?

To add some clarification here, when you create your service, the service class uses the default 'wsdlLocation', which was inserted into it when the class was built from the wsdl. So if you have a service class called SomeService, and you create an instance like this:

SomeService someService = new SomeService();

If you look inside SomeService, you will see that the constructor looks like this:

public SomeService() {
        super(__getWsdlLocation(), SOMESERVICE_QNAME);
}

So if you want it to point to another URL, you just use the constructor that takes a URL argument (there are 6 constructors for setting qname and features as well). For example, if you have set up a local TCP/IP monitor that is listening on port 9999, and you want to redirect to that URL:

URL newWsdlLocation = new URL("http://theServerName:9999/somePath");
SomeService someService = new SomeService(newWsdlLocation);

and that will call this constructor inside the service:

public SomeService(URL wsdlLocation) {
    super(wsdlLocation, SOMESERVICE_QNAME);
}

Address already in use: JVM_Bind java

please try following options for JVM binding exception:

  1. start and stop the server. and check the server process ids and kill and stop the server.
  2. go to control panel->administrative tool-> service-> check all server and stop all the servers and then start your own server.
  3. change the Browser which your using. for example if your using IE ,change it to Mozilla firefox.

JBoss vs Tomcat again

First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.

Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.

How to decide whether to use Tomcat or a full stack Java EE application server:

When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:

  1. JMS messaging for asynchronous integration
  2. Web Services engine (JAX-WS and/or JAX-RS)
  3. Management capabilities like JMX and a scripted administration interface
  4. Advanced security, e.g. out-of-the-box integration with 3rd party directories
  5. EAR file instead of "only" WAR file support
  6. all the other "great" Java EE features I can't remember :-)

In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.

Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.

my 2 cent

How to enable TLS 1.2 in Java 7

You should probably be looking to the configuration that controls the underlying platform TLS implementation via -Djdk.tls.client.protocols=TLSv1.2.

How do you join on the same table, twice, in mysql?

you'd use another join, something along these lines:

SELECT toD.dom_url AS ToURL, 
    fromD.dom_url AS FromUrl, 
    rvw.*

FROM reviews AS rvw

LEFT JOIN domain AS toD 
    ON toD.Dom_ID = rvw.rev_dom_for

LEFT JOIN domain AS fromD 
    ON fromD.Dom_ID = rvw.rev_dom_from

EDIT:

All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).

At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.

Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.

For more info about aliasing in SQL, read here.

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

In my case, I had the setting Override application root URL checked, on the Properties->Web tab. I was using that previously when I was running VS as an administrator, but now that I'm running it in a non-admin account, it causes the error.

Why would one mark local variables and method parameters as "final" in Java?

Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.

Finalizing local var's seems somewhat overkill IMO.

Multiple IF statements between number ranges

I suggest using vlookup function to get the nearest match.


Step 1

Prepare data range and name it: 'numberRange':

enter image description here

Select the range. Go to menu: Data ? Named ranges... ? define the new named range.

Step 2

Use this simple formula:

=VLOOKUP(A2,numberRange,2)

enter image description here


This way you can ommit errors, and easily correct the result.

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

Replace multiple characters in a C# string

A .NET Core version for replacing a defined set of string chars to a specific char. It leverages the recently introduced Span type and string.Create method.

The idea is to prepare a replacement array, so no actual comparison operations would be required for the each string char. Thus, the replacement process reminds the way a state machine works. In order to avoid initialization of all items of the replacement array, let's store oldChar ^ newChar (XOR'ed) values there, what gives the following benefits:

  • If a char is not changing: ch ^ ch = 0 - no need to initialize non-changing items
  • The final char can be found by XOR'ing: ch ^ repl[ch]:
    • ch ^ 0 = ch - not changed chars case
    • ch ^ (ch ^ newChar) = newChar - replaced char

So the only requirement would be to ensure that the replacement array is zero-ed when initialized. We'll be using ArrayPool<char> to avoid allocations each time the ReplaceAll method is called. And, in order to ensure that the arrays are zero-ed without expensive call to Array.Clear method, we'll be maintaining a pool dedicated for the ReplaceAll method. We'll be clearing the replacement array (exact items only) before returning it to the pool.

public static class StringExtensions
{
    private static readonly ArrayPool<char> _replacementPool = ArrayPool<char>.Create();

    public static string ReplaceAll(this string str, char newChar, params char[] oldChars)
    {
        // If nothing to do, return the original string.
        if (string.IsNullOrEmpty(str) ||
            oldChars is null ||
            oldChars.Length == 0)
        {
            return str;
        }

        // If only one character needs to be replaced,
        // use the more efficient `string.Replace`.
        if (oldChars.Length == 1)
        {
            return str.Replace(oldChars[0], newChar);
        }

        // Get a replacement array from the pool.
        var replacements = _replacementPool.Rent(char.MaxValue + 1);

        try
        {
            // Intialize the replacement array in the way that
            // all elements represent `oldChar ^ newChar`.
            foreach (var oldCh in oldChars)
            {
                replacements[oldCh] = (char)(newChar ^ oldCh);
            }

            // Create a string with replaced characters.
            return string.Create(str.Length, (str, replacements), (dst, args) =>
            {
                var repl = args.replacements;

                foreach (var ch in args.str)
                {
                    dst[0] = (char)(repl[ch] ^ ch);
                    dst = dst.Slice(1);
                }
            });
        }
        finally
        {
            // Clear the replacement array.
            foreach (var oldCh in oldChars)
            {
                replacements[oldCh] = char.MinValue;
            }

            // Return the replacement array back to the pool.
            _replacementPool.Return(replacements);
        }
    }
}

How do I check if a number is positive or negative in C#?

Native programmer's version. Behaviour is correct for little-endian systems.

bool IsPositive(int number)
{
   bool result = false;
   IntPtr memory = IntPtr.Zero;
   try
   {
       memory = Marshal.AllocHGlobal(4);
       if (memory == IntPtr.Zero)
           throw new OutOfMemoryException();

       Marshal.WriteInt32(memory, number);

       result = (Marshal.ReadByte(memory, 3) & 0x80) == 0;
   }
   finally
   {
       if (memory != IntPtr.Zero)
           Marshal.FreeHGlobal(memory);
   }
   return result;
}

Do not ever use this.

How to get the innerHTML of selectable jquery element?

$(function() {
        $("#select-image").selectable({
            selected: function( event, ui ) { 
                var $variable = $('.ui-selected').html(); 
                console.log($variable);
            }
        });
    });

or

$(function() {
        $("#select-image").selectable({
            selected: function( event, ui ) { 
                var $variable = $('.ui-selected').text(); 
                console.log($variable);
            }
        });
    });

or

$(function() {
        $("#select-image").selectable({
            selected: function( event, ui ) { 
                var $variable = $('.ui-selected').val(); 
                console.log($variable);
            }
        });
    });

batch file to check 64bit or 32bit OS

If $SYSTEM_os_arch==x86 ( 
  Echo OS is 32bit
 ) else ( 
  ECHO OS is 64bit
)

Which comment style should I use in batch files?

good question... I've been looking for this functionality for long too...

after several tests and tricks it seem the better solution is the more obvious one...

--> best way I found to do it, preventing parser integrity fail, is reusing REM:

echo this will show until the next REM &REM this will not show

you can also use multiline with the "NULL LABEL" trick... (dont forget the ^ at the end of the line for continuity)

::(^
this is a multiline^
comment... inside a null label!^
dont forget the ^caret at the end-of-line^
to assure continuity of text^ 
)

How to comment a block in Eclipse?

For Eclipse Editor

For Single Line (Toggle Effect)

Comment : Ctrl+Shift+c

Uncomment: Ctrl+Shift+c

For Multiple Lines (Toggle Effect) (Select the lines you want to comment)

comment : Ctrl+Shift+c

Uncomment: Ctrl+Shift+c

It is for all html , css , jsp , java . It gives toggle effect.

Google access token expiration time

Have a look at: https://developers.google.com/accounts/docs/OAuth2UserAgent#handlingtheresponse

It says:

Other parameters included in the response include expires_in and token_type. These parameters describe the lifetime of the token in seconds...

How to check type of variable in Java?

Java is a statically typed language, so the compiler does most of this checking for you. Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type).

The examples you gave (int, array, double) these are all primitives, and there are no sub-types of them. Thus, if you declare a variable to be an int:

int x;

You can be sure it will only ever hold int values.

If you declared a variable to be a List, however, it is possible that the variable will hold sub-types of List. Examples of these include ArrayList, LinkedList, etc.

If you did have a List variable, and you needed to know if it was an ArrayList, you could do the following:

List y;
...
if (y instanceof ArrayList) { 
  ...its and ArrayList...
}

However, if you find yourself thinking you need to do that, you may want to rethink your approach. In most cases, if you follow object-oriented principles, you will not need to do this. There are, of course, exceptions to every rule, though.

Javascript split regex question

or just use for date strings 2015-05-20 or 2015.05.20

date.split(/\.|-/);

Changing MongoDB data store directory

The following command will work for you, if you want to change default path. Just type this in bin directory of mongodb.

mongod --dbpath=yourdirectory\data\db

In case you want to move existing data too, then just copy all the folders from existing data\db directory to new directory before you execute the command.

And also stop existing mongodb services which are running.

jQuery's .click - pass parameters to user function

You need to use an anonymous function like this:

$('.leadtoscore').click(function() {
  add_event('shot')
});

You can call it like you have in the example, just a function name without parameters, like this:

$('.leadtoscore').click(add_event);

But the add_event method won't get 'shot' as it's parameter, but rather whatever click passes to it's callback, which is the event object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use .bind() and pass data, like this:

$('.leadtoscore').bind('click', { param: 'shot' }, add_event);

And access it in add_event, like this:

function add_event(event) {
  //event.data.param == "shot", use as needed
}

How to access iOS simulator camera

It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS version and any Simulator. You will have to use device for testing camera purpose.

How do I select last 5 rows in a table without sorting?

In SQL Server 2012 you can do this :

Declare @Count1 int ;

Select @Count1 = Count(*)
FROM    [Log] AS L

SELECT  
   *
FROM    [Log] AS L
ORDER BY L.id
OFFSET @Count - 5 ROWS
FETCH NEXT 5 ROWS ONLY;

Gson: Directly convert String to JsonObject (no POJO)

The simplest way is to use the JsonPrimitive class, which derives from JsonElement, as shown below:

JsonElement element = new JsonPrimitive(yourString);
JsonObject result = element.getAsJsonObject();

TypeError: unsupported operand type(s) for /: 'str' and 'str'

The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.

So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.

One way to convert a string to an integer is to use the int function. For example:

percent = (int(pyc) / int(tpy)) * 100

Create excel ranges using column numbers in vba?

I really like stackPusher's ConvertToLetter function as a solution. However, in working with it I noticed several errors occurring at very specific inputs due to some flaws in the math. For example, inputting 392 returns 'N\', 418 returns 'O\', 444 returns 'P\', etc.

I reworked the function and the result produces the correct output for all input up to 703 (which is the first triple-letter column index, AAA).

Function ConvertToLetter2(iCol As Integer) As String
    Dim First As Integer
    Dim Second As Integer
    Dim FirstChar As String
    Dim SecondChar As String

    First = Int(iCol / 26)
    If First = iCol / 26 Then
        First = First - 1
    End If
    If First = 0 Then
        FirstChar = ""
    Else
        FirstChar = Chr(First + 64)
    End If

    Second = iCol Mod 26
    If Second = 0 Then
        SecondChar = Chr(26 + 64)
    Else
        SecondChar = Chr(Second + 64)
    End If

    ConvertToLetter2 = FirstChar & SecondChar

End Function

How to compare two files in Notepad++ v6.6.8

Alternatively, you can install "SourceForge Notepad++ Compare Plugin 1.5.6". It provides compare functionality between two files and show the differences between two files.

Link to refer : https://sourceforge.net/projects/npp-compare/files/1.5.6/

Update a submodule to the latest commit

None of the above answers worked for me.

This was the solution, from the parent directory run:

git submodule update --init;
cd submodule-directory;
git pull;
cd ..;
git add submodule-directory;

now you can git commit and git push

What ports does RabbitMQ use?

PORT 4369: Erlang makes use of a Port Mapper Daemon (epmd) for resolution of node names in a cluster. Nodes must be able to reach each other and the port mapper daemon for clustering to work.

PORT 35197 set by inet_dist_listen_min/max Firewalls must permit traffic in this range to pass between clustered nodes

RabbitMQ Management console:

  • PORT 15672 for RabbitMQ version 3.x
  • PORT 55672 for RabbitMQ pre 3.x

PORT 5672 RabbitMQ main port.

For a cluster of nodes, they must be open to each other on 35197, 4369 and 5672.

For any servers that want to use the message queue, only 5672 is required.

Restricting JTextField input to Integers

When you type integer numbers to JtextField1 after key release it will go to inside try , for any other character it will throw NumberFormatException. If you set empty string to jTextField1 inside the catch so the user cannot type any other keys except positive numbers because JTextField1 will be cleared for each bad attempt.

 //Fields 
int x;
JTextField jTextField1;

 //Gui Code Here

private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {                                        
    try {
        x = Integer.parseInt(jTextField1.getText());
    } catch (NumberFormatException nfe) {
        jTextField1.setText("");
    }
}   

Angular 2 ngfor first, last, index loop

By this you can get any index in *ngFor loop in ANGULAR ...

<ul>
  <li *ngFor="let object of myArray; let i = index; let first = first ;let last = last;">
    <div *ngIf="first">
       // write your code...
    </div>

    <div *ngIf="last">
       // write your code...
    </div>
  </li>
</ul>

We can use these alias in *ngFor

  • index : number : let i = index to get all index of object.
  • first : boolean : let first = first to get first index of object.
  • last : boolean : let last = last to get last index of object.
  • odd : boolean : let odd = odd to get odd index of object.
  • even : boolean : let even = even to get even index of object.

Now() function with time trim

DateValue(CStr(Now()))

That's the best I've found. If you have the date as a string already you can just do:

DateValue("12/04/2012 04:56:15")

or

DateValue(*DateStringHere*)

Hope this helps someone...

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I scroll to a specific location on the page using jquery?

Using jquery.easing.min.js, With fixed IE console Errors

Html

<a class="page-scroll" href="#features">Features</a>
<section id="features" class="features-section">Features Section</section>


        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="js/jquery.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Scrolling Nav JavaScript -->
        <script src="js/jquery.easing.min.js"></script>

Jquery

//jQuery to collapse the navbar on scroll, you can use this code with in external file with name scrolling-nav.js
        $(window).scroll(function () {
            if ($(".navbar").offset().top > 50) {
                $(".navbar-fixed-top").addClass("top-nav-collapse");
            } else {
                $(".navbar-fixed-top").removeClass("top-nav-collapse");
            }
        });
        //jQuery for page scrolling feature - requires jQuery Easing plugin
        $(function () {
            $('a.page-scroll').bind('click', function (event) {
                var anchor = $(this);
                if ($(anchor).length > 0) {
                    var href = $(anchor).attr('href');
                    if ($(href.substring(href.indexOf('#'))).length > 0) {
                        $('html, body').stop().animate({
                            scrollTop: $(href.substring(href.indexOf('#'))).offset().top
                        }, 1500, 'easeInOutExpo');
                    }
                    else {
                        window.location = href;
                    }
                }
                event.preventDefault();
            });
        });

Regex to remove letters, symbols except numbers

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

Git: force user and password prompt

Since the question was labeled with Github, adding another remote like https_origin and add the https connection can force you always to enter the password:

git remote add https_origin https://github.com/.../...

document.getelementbyId will return null if element is not defined?

getElementById is defined by DOM Level 1 HTML to return null in the case no element is matched.

!==null is the most explicit form of the check, and probably the best, but there is no non-null falsy value that getElementById can return - you can only get null or an always-truthy Element object. So there's no practical difference here between !==null, !=null or the looser if (document.getElementById('xx')).

In jQuery, how do I select an element by its name attribute?

another way

$('input:radio[name=theme]').filter(":checked").val()

Ping all addresses in network, windows

Best Utility in terms of speed is Nmap.

write @ cmd prompt:

Nmap -sn -oG ip.txt 192.168.1.1-255

this will just ping all the ip addresses in the range given and store it in simple text file

It takes just 2 secs to scan 255 hosts using Nmap.

Try reinstalling `node-sass` on node 0.12?

I had the same issue as @Kos had, only for some reason I had to modify the gulp-sass package from the old package.json file I had. It then installed the dependencies currently and now it finally works!

In Perl, how to remove ^M from a file?

Little script I have for that. A modification of it helped to filter out some other non-printable characters in cross-platform legacy files.

#!/usr/bin/perl
# run this as
# convert_dos2unix.pl < input_file > output_file
undef $/;
$_ = <>;
s/\r//ge;
print;

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

How do I escape a string inside JavaScript code inside an onClick handler?

In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string.

\xXX is for chars < 127, and \uXXXX for Unicode, so armed with this knowledge you can create a robust JSEncode function for all characters that are out of the usual whitelist.

For example,

<a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a>

Why are static variables considered evil?

There's nothing wrong with static variables per se. It's just the Java syntax that's broken. Each Java class actually defines two structures- a singleton object which encapsulates static variables, and an instance. Defining both in the same source block is pure evil, and results in a code that's hard to read. Scala did that right.

Special characters like @ and & in cURL POST data

Just found another solutions worked for me. You can use '\' sign before your one special.

passwd=\@31\&3*J

Change background position with jQuery

$('#submenu li').hover(function(){
    $('#carousel').css('backgroundPosition', newValue);
});

How can I view the contents of an ElasticSearch index?

I can recommend Elasticvue, which is modern, free and open source. It allows accessing your ES instance via browser add-ons quite easily (supports Firefox, Chrome, Edge). But there are also further ways.

Just make sure you set cors values in elasticsearch.yml appropiate.

How to remove all subviews of a view in Swift?

EDIT: (thanks Jeremiah / Rollo)

By far the best way to do this in Swift for iOS is:

view.subviews.forEach({ $0.removeFromSuperview() }) // this gets things done
view.subviews.map({ $0.removeFromSuperview() }) // this returns modified array

^^ These features are fun!

let funTimes = ["Awesome","Crazy","WTF"]
extension String { 
    func readIt() {
        print(self)
    }
}

funTimes.forEach({ $0.readIt() })

//// END EDIT

Just do this:

for view in self.view.subviews {
    view.removeFromSuperview()
}

Or if you are looking for a specific class

for view:CustomViewClass! in self.view.subviews {
        if view.isKindOfClass(CustomViewClass) {
            view.doClassThing()
        }
    }

Java Swing - how to show a panel on top of another panel?

I think LayeredPane is your best bet here. You would need a third panel though to contain A and B. This third panel would be the layeredPane and then panel A and B could still have a nice LayoutManagers. All you would have to do is center B over A and there is quite a lot of examples in the Swing trail on how to do this. Tutorial for positioning without a LayoutManager.

public class Main {
    private JFrame frame = new JFrame();
    private JLayeredPane lpane = new JLayeredPane();
    private JPanel panelBlue = new JPanel();
    private JPanel panelGreen = new JPanel();
    public Main()
    {
        frame.setPreferredSize(new Dimension(600, 400));
        frame.setLayout(new BorderLayout());
        frame.add(lpane, BorderLayout.CENTER);
        lpane.setBounds(0, 0, 600, 400);
        panelBlue.setBackground(Color.BLUE);
        panelBlue.setBounds(0, 0, 600, 400);
        panelBlue.setOpaque(true);
        panelGreen.setBackground(Color.GREEN);
        panelGreen.setBounds(200, 100, 100, 100);
        panelGreen.setOpaque(true);
        lpane.add(panelBlue, new Integer(0), 0);
        lpane.add(panelGreen, new Integer(1), 0);
        frame.pack();
        frame.setVisible(true);
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main();
    }

}

You use setBounds to position the panels inside the layered pane and also to set their sizes.

Edit to reflect changes to original post You will need to add component listeners that detect when the parent container is being resized and then dynamically change the bounds of panel A and B.

Double array initialization in Java

It is called an array initializer and can be explained in the Java specification 10.6.

This can be used to initialize any array, but it can only be used for initialization (not assignment to an existing array). One of the unique things about it is that the dimensions of the array can be determined from the initializer. Other methods of creating an array require you to manually insert the number. In many cases, this helps minimize trivial errors which occur when a programmer modifies the initializer and fails to update the dimensions.

Basically, the initializer allocates a correctly sized array, then goes from left to right evaluating each element in the list. The specification also states that if the element type is an array (such as it is for your case... we have an array of double[]), that each element may, itself be an initializer list, which is why you see one outer set of braces, and each line has inner braces.

How to make flutter app responsive according to different screen size?

This class will help and then initialize the class with the init method.

import 'package:flutter/widgets.dart';

class SizeConfig {
  static MediaQueryData _mediaQueryData;
  static double screenWidth;
  static double screenHeight;
  static double blockSizeHorizontal;
  static double blockSizeVertical;
  static double _safeAreaHorizontal;
  static double _safeAreaVertical;
  static double safeBlockHorizontal;
  static double safeBlockVertical;

  void init(BuildContext context){
    _mediaQueryData = MediaQuery.of(context);
    screenWidth = _mediaQueryData.size.width;
    screenHeight = _mediaQueryData.size.height;
    blockSizeHorizontal = screenWidth/100;
    blockSizeVertical = screenHeight/100;
    _safeAreaHorizontal = _mediaQueryData.padding.left +
        _mediaQueryData.padding.right;
    _safeAreaVertical = _mediaQueryData.padding.top +
        _mediaQueryData.padding.bottom;
    safeBlockHorizontal = (screenWidth - _safeAreaHorizontal)/100;
    safeBlockVertical = (screenHeight - _safeAreaVertical)/100;
  }
}

then in your widgets dimension do this

Widget build(BuildContext context) {
    SizeConfig().init(context);
    return Container(
    height: SizeConfig.safeBlockVertical * 10, //10 for example
    width: SizeConfig.safeBlockHorizontal * 10, //10 for example
    );}

All the credits to this post author: https://medium.com/flutter-community/flutter-effectively-scale-ui-according-to-different-screen-sizes-2cb7c115ea0a

Is Eclipse the best IDE for Java?

Agreeing with the others. Netbeans is a pretty good IDE which also caters for other languages (PHP, Ruby, C/C++) if you're prone to using any of those. Then you get the added benefit of knowing your way around the IDE when deciding to pick up a new language.

To be fair however, I haven't had much time with the eclipse IDE.

How to throw std::exceptions with variable messages?

Use string literal operator if C++14 (operator ""s)

using namespace std::string_literals;

throw std::exception("Could not load config file '"s + configfile + "'"s);

or define your own if in C++11. For instance

std::string operator ""_s(const char * str, std::size_t len) {
    return std::string(str, str + len);
}

Your throw statement will then look like this

throw std::exception("Could not load config file '"_s + configfile + "'"_s);

which looks nice and clean.

Escape a string in SQL Server so that it is safe to use in LIKE expression

Rather than escaping all characters in a string that have particular significance in the pattern syntax given that you are using a leading wildcard in the pattern it is quicker and easier just to do.

SELECT * 
FROM YourTable
WHERE CHARINDEX(@myString , YourColumn) > 0

In cases where you are not using a leading wildcard the approach above should be avoided however as it cannot use an index on YourColumn.

Additionally in cases where the optimum execution plan will vary according to the number of matching rows the estimates may be better when using LIKE with the square bracket escaping syntax when compared to both CHARINDEX and the ESCAPE keyword.

How can I clear the terminal in Visual Studio Code?

Ctrl + Shift + P and select Terminal:clear

How can I test a PDF document if it is PDF/A compliant?

A list of PDF/A validators is on the pdfa.org web site here:

verapdf

A free online PDF/A validator is available here:

http://www.validatepdfa.com/

A report on the accuracy of many of these PDF/A validators is available from PDFLib:

https://www.pdflib.com/fileadmin/pdflib/pdf/pdfa/2009-05-04-Bavaria-report-on-PDFA-validation-accuracy.pdf

Se as well:

https://www.pdflib.com/knowledge-base/pdfa/

android: how to use getApplication and getApplicationContext from non activity / service class

Either pass in a Context (so you can access resources), or make the helper methods static.

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Its a CORS issue, your api cannot be accessed directly from remote or different origin, In order to allow other ip address or other origins from accessing you api, you should add the 'Access-Control-Allow-Origin' on the api's header, you can set its value to '*' if you want it to be accessible to all, or you can set specific domain or ips like 'http://siteA.com' or 'http://192. ip address ';

Include this on your api's header, it may vary depending on how you are displaying json data,

if your using ajax, to retrieve and display data your header would look like this,

$.ajax({
   url: '',
   headers: {  'Access-Control-Allow-Origin': 'http://The web site allowed to access' },
   data: data,
   type: 'dataType',
   /* etc */
   success: function(jsondata){

   }
})

How do you query for "is not null" in Mongo?

One liner is the best :

db.mycollection.find({ 'fieldname' : { $exists: true, $ne: null } });

Here,

mycollection : place your desired collection name

fieldname : place your desired field name

Explaination :

$exists : When is true, $exists matches the documents that contain the field, including documents where the field value is null. If is false, the query returns only the documents that do not contain the field.

$ne selects the documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field.

So in your provided case following query going to return all the documents with imageurl field exists and having not null value:

db.mycollection.find({ 'imageurl' : { $exists: true, $ne: null } });

Recursively looping through an object to build a property list

This version is packed in a function that accepts a custom delimiter, filter, and returns a flat dictionary:

function flatten(source, delimiter, filter) {
  var result = {}
  ;(function flat(obj, stack) {
    Object.keys(obj).forEach(function(k) {
      var s = stack.concat([k])
      var v = obj[k]
      if (filter && filter(k, v)) return
      if (typeof v === 'object') flat(v, s)
      else result[s.join(delimiter)] = v
    })
  })(source, [])
  return result
}
var obj = {
  a: 1,
  b: {
    c: 2
  }
}
flatten(obj)
// <- Object {a: 1, b.c: 2}
flatten(obj, '/')
// <- Object {a: 1, b/c: 2}
flatten(obj, '/', function(k, v) { return k.startsWith('a') })
// <- Object {b/c: 2}

Reading a file character by character in C

The problem here is twofold

  • a) you increment the pointer before you check the value read in, and
  • b) you ignore the fact that fgetc() returns an int instead of a char.

The first is easily fixed:

char *orig = code; // the beginning of the array
// ...
do {
  *code = fgetc(file);
} while(*code++ != EOF);
*code = '\0'; // nul-terminate the string
return orig; // don't return a pointer to the end

The second problem is more subtle -fgetc returns an int so that the EOF value can be distinguished from any possible char value. Fixing this uses a temporary int for the EOF check and probably a regular while loop instead of do / while.

How to get current CPU and RAM usage in Python?

"... current system status (current CPU, RAM, free disk space, etc.)" And "*nix and Windows platforms" can be a difficult combination to achieve.

The operating systems are fundamentally different in the way they manage these resources. Indeed, they differ in core concepts like defining what counts as system and what counts as application time.

"Free disk space"? What counts as "disk space?" All partitions of all devices? What about foreign partitions in a multi-boot environment?

I don't think there's a clear enough consensus between Windows and *nix that makes this possible. Indeed, there may not even be any consensus between the various operating systems called Windows. Is there a single Windows API that works for both XP and Vista?

How to create a file in memory for user to download, but not through server?

If the file contains text data, a technique I use is to put the text into a textarea element and have the user select it (click in textarea then ctrl-A) then copy followed by a paste to a text editor.

Unicode (UTF-8) reading and writing to files in Python

Now all you need in Python3 is open(Filename, 'r', encoding='utf-8')

[Edit on 2016-02-10 for requested clarification]

Python3 added the encoding parameter to its open function. The following information about the open function is gathered from here: https://docs.python.org/3/library/functions.html#open

open(file, mode='r', buffering=-1, 
      encoding=None, errors=None, newline=None, 
      closefd=True, opener=None)

Encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

So by adding encoding='utf-8' as a parameter to the open function, the file reading and writing is all done as utf8 (which is also now the default encoding of everything done in Python.)

How do I put a variable inside a string?

I had a need for an extended version of this: instead of embedding a single number in a string, I needed to generate a series of file names of the form 'file1.pdf', 'file2.pdf' etc. This is how it worked:

['file' + str(i) + '.pdf' for i in range(1,4)]

How do I create a comma-separated list from an array in PHP?

Sometimes you don't even need php for this in certain instances (List items each are in their own generic tag on render for example) You can always add commas to all elements but last-child via css if they are separate elements after being rendered from the script.

I use this a lot in backbone apps actually to trim some arbitrary code fat:

.likers a:not(:last-child):after { content: ","; }

Basically looks at the element, targets all except it's last element, and after each item it adds a comma. Just an alternative way to not have to use script at all if the case applies.

Powershell folder size of folders without listing Subdirectories

This simple solution worked for me as well.

powershell -c "Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum"

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

Finding index of character in Swift String

On the subject of turning a String.Index into an Int, this extension works for me:

public extension Int {
    /// Creates an `Int` from a given index in a given string
    ///
    /// - Parameters:
    ///    - index:  The index to convert to an `Int`
    ///    - string: The string from which `index` came
    init(_ index: String.Index, in string: String) {
        self.init(string.distance(from: string.startIndex, to: index))
    }
}

Example usage relevant to this question:

var testString = "abcdefg"

Int(testString.range(of: "c")!.lowerBound, in: testString)     // 2

testString = "???\u{1112}\u{1161}\u{11AB}"

Int(testString.range(of: "")!.lowerBound, in: testString) // 0
Int(testString.range(of: "???")!.lowerBound, in: testString)    // 1
Int(testString.range(of: "???")!.lowerBound, in: testString)    // 5

Important:

As you can tell, it groups extended grapheme clusters and joined characters differently than String.Index. Of course, this is why we have String.Index. You should keep in mind that this method considers clusters to be singular characters, which is closer to correct. If your goal is to split a string by Unicode codepoint, this is not the solution for you.

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

Same error

Installing collected packages: six, pyparsing, packaging, appdirs, setuptools
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 323, in clobber
    shutil.copyfile(srcfile, destfile)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 83, in copyfile
    with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/six.py'

and here I use --user without sudo to solve this issue

$ pip install --user scikit-image h5py keras pygame
Collecting scikit-image
  Downloading http://mirrors.aliyun.com/pypi/packages/65/69/27a1d55ce8f77c8ac757938707105b1070ff4f2ae47d2dc99461bfae4491/scikit_image-0.13.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (28.1MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 28.1MB 380kB/s
Collecting h5py
  Downloading http://mirrors.aliyun.com/pypi/packages/b7/cc/1c29b0815b12de2c92b5323cad60f724ac8f0e39d0166d0b9dfacbcb70dd/h5py-2.7.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.5MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 4.5MB 503kB/s
Requirement already satisfied: keras in /Library/Python/2.7/site-packages
Requirement already satisfied: pygame in /Library/Python/2.7/site-packages
Requirement already satisfied: matplotlib>=1.3.1 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from scikit-image)
Requirement already satisfied: six>=1.7.3 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: pillow>=2.1.0 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: networkx>=1.8 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: PyWavelets>=0.4.0 in /Library/Python/2.7/site-packages (from scikit-image)
Collecting scipy>=0.17.0 (from scikit-image)
  Downloading http://mirrors.aliyun.com/pypi/packages/72/eb/d398b9f63ee936575edc62520477d6c2353ed013bacd656bd0c8bc1d0fa7/scipy-0.19.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (16.2MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 16.2MB 990kB/s
Requirement already satisfied: numpy>=1.7 in /Library/Python/2.7/site-packages (from h5py)
Requirement already satisfied: theano in /Library/Python/2.7/site-packages (from keras)
Requirement already satisfied: pyyaml in /Library/Python/2.7/site-packages (from keras)
Requirement already satisfied: python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: tornado in /Library/Python/2.7/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: pyparsing>=1.5.6 in /Users/qiuwei/Library/Python/2.7/lib/python/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: nose in /Library/Python/2.7/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: olefile in /Library/Python/2.7/site-packages (from pillow>=2.1.0->scikit-image)
Requirement already satisfied: decorator>=3.4.0 in /Library/Python/2.7/site-packages (from networkx>=1.8->scikit-image)
Requirement already satisfied: singledispatch in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: certifi in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: backports_abc>=0.4 in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Installing collected packages: scipy, scikit-image, h5py
Successfully installed h5py-2.7.0 scikit-image-0.13.0 scipy-0.19.0 

Hope it will help someone who encounter similar issue!

Replace Fragment inside a ViewPager

tl;dr: Use a host fragment that is responsible for replacing its hosted content and keeps track of a back navigation history (like in a browser).

As your use case consists of a fixed amount of tabs my solution works well: The idea is to fill the ViewPager with instances of a custom class HostFragment, that is able to replace its hosted content and keeps its own back navigation history. To replace the hosted fragment you make a call to the method hostfragment.replaceFragment():

public void replaceFragment(Fragment fragment, boolean addToBackstack) {
    if (addToBackstack) {
        getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).addToBackStack(null).commit();
    } else {
        getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).commit();
    }
}

All that method does is to replace the frame layout with the id R.id.hosted_fragment with the fragment provided to the method.

Check my tutorial on this topic for further details and a complete working example on GitHub!

Postgres password authentication fails

Assuming, that you have root access on the box you can do:

sudo -u postgres psql

If that fails with a database "postgres" does not exists this block.

sudo -u postgres psql template1

Then sudo nano /etc/postgresql/11/main/pg_hba.conf file

local   all         postgres                          ident

For newer versions of PostgreSQL ident actually might be peer.

Inside the psql shell you can give the DB user postgres a password:

ALTER USER postgres PASSWORD 'newPassword';

Replace only some groups with Regex

If you don't want to change your pattern you can use the Group Index and Length properties of a matched group.

var text = "example-123-example";
var pattern = @"-(\d+)-";
var regex = new RegEx(pattern);
var match = regex.Match(text);

var firstPart = text.Substring(0,match.Groups[1].Index);    
var secondPart = text.Substring(match.Groups[1].Index + match.Groups[1].Length);
var fullReplace = firstPart + "AA" + secondPart;

How do I generate a random number between two variables that I have stored?

rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber

Iterating through struct fieldnames in MATLAB

Since fields or fns are cell arrays, you have to index with curly brackets {} in order to access the contents of the cell, i.e. the string.

Note that instead of looping over a number, you can also loop over fields directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.

teststruct = struct('a',3,'b',5,'c',9)

fields = fieldnames(teststruct)

for fn=fields'
  fn
  %# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
  teststruct.(fn{1})
end

Node Version Manager install - nvm command not found

In macOS, i had to source it using source ~/.nvm/nvm.sh command to fix this problem.

After that, add these lines

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm

onto ~/.bash_profile so that nvm will be sourced automatically upon login.

@Autowired and static method

You have to workaround this via static application context accessor approach:

@Component
public class StaticContextAccessor {

    private static StaticContextAccessor instance;

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void registerInstance() {
        instance = this;
    }

    public static <T> T getBean(Class<T> clazz) {
        return instance.applicationContext.getBean(clazz);
    }

}

Then you can access bean instances in a static manner.

public class Boo {

    public static void randomMethod() {
         StaticContextAccessor.getBean(Foo.class).doStuff();
    }

}

Finding partial text in range, return an index

This formula will do the job:

=INDEX(G:G,MATCH(FALSE,ISERROR(SEARCH(H1,G:G)),0)+3)

you need to enter it as an array formula, i.e. press Ctrl-Shift-Enter. It assumes that the substring you're searching for is in cell H1.

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

Normally, you run IE 32 bit.
However, on 64-bit versions of Windows, there is a separate link in the Start Menu to Internet Explorer (64 bit). There's no real reason to use it, though.

In Help, About, the 64-bit version of IE will say 64-bit Edition (just after the full version string).

The 32-bit and 64-bit versions of IE have separate addons lists (because 32-bit addons cannot be loaded in 64-bit IE, and vice-versa), so you should make sure that Java appears on both lists.

In general, you can tell whether a process is 32-bit or 64-bit by right-clicking the application in Task Manager and clicking Go To Process. 32-bit processes will end with *32.

How can I execute Python scripts using Anaconda's version of Python?

The instructions in the official Python documentation worked for me: https://docs.python.org/2/using/windows.html#executing-scripts

  1. Launch a command prompt.

  2. Associate the correct file group with .py scripts:

    assoc .py=Python.File
    

Redirect all Python files to the new executable:

    ftype Python.File=C:\Path\to\pythonw.exe "%1" %*

The example shows how to associate the .py extension with the .pyw executable, but it works if you want to associate the .py extension with the Anaconda Python executable. You need administrative rights. The name "Python.File" could be anything, you just have to make sure is the same name in the ftype command. When you finish and before you try double-clicking the .py file, you must change the "Open with" in the file properties. The file type will be now ".py" and it is opened with the Anaconda python.exe.

How do I perform an IF...THEN in an SQL SELECT?

You can find some nice examples in The Power of SQL CASE Statements, and I think the statement that you can use will be something like this (from 4guysfromrolla):

SELECT
    FirstName, LastName,
    Salary, DOB,
    CASE Gender
        WHEN 'M' THEN 'Male'
        WHEN 'F' THEN 'Female'
    END
FROM Employees

Android video streaming example

Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.

Input type DateTime - Value format?

This works for setting the value of the INPUT:

strftime('%Y-%m-%dT%H:%M:%S', time())

PHP array delete by value (not key)

here is one simple but understandable solution:

$messagesFiltered = [];
foreach ($messages as $message) {
    if (401 != $message) {
        $messagesFiltered[] = $message;
    }
}
$messages = $messagesFiltered;

Auto-click button element on page load using jQuery

You can use that and adjust the time you want to launch 1= onload 2000= 2 sec

_x000D_
_x000D_
$(document).ready(function(){
 $('#click').click(function(){
        alert('button clicked');
    });
  // set time out 2 sec
     setTimeout(function(){
        $('#click').trigger('click');
    }, 2000);
});
_x000D_
.container{
padding-top:50px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="col text-center">
<button id="click" class="btn btn-danger">Jquery Auto Click</button>
  </div>
   </div>
_x000D_
_x000D_
_x000D_

What is the difference between a static method and a non-static method?

Another scenario for Static method.

Yes, Static method is of the class not of the object. And when you don't want anyone to initialize the object of the class or you don't want more than one object, you need to use Private constructor and so the static method.

Here, we have private constructor and using static method we are creating a object.

Ex::

public class Demo {

        private static Demo obj = null;         
        private Demo() {
        }

        public static Demo createObj() {

            if(obj == null) {
               obj = new Demo();
            }
            return obj;
        }
}

Demo obj1 = Demo.createObj();

Here, Only 1 instance will be alive at a time.

Using boolean values in C

typedef enum {
    false = 0,
    true
} t_bool;

Duplicate AssemblyVersion Attribute

I have being struggling with this issue, but my problem was much easier to solve.

I had copied OBJ folder to "OBJ___" name to do some compilation tests.

So, I don't know why, this folder was being also compiled, creating the assembly attributes duplication.

I simply deleted the "OBJ___" folder and could compile successfuly.

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:

  1. uninstall the x86 versions of VC 11 vcredist_x64/86.exe for 2012 and 2013
  2. uninstall WAMP Server 2.5
  3. delete (maybe back up first) the WAMP folder
  4. restart windows
  5. reinstall WAMP 2.5

Hopefully like me you have a MySQL database backup handy!

increase legend font size ggplot2

A simpler but equally effective option would be:

+ theme_bw(base_size=X)

How can I simulate a click to an anchor tag?

Quoted from https://developer.mozilla.org/en/DOM/element.click

The click method is intended to be used with INPUT elements of type button, checkbox, radio, reset or submit. Gecko does not implement the click method on other elements that might be expected to respond to mouse–clicks such as links (A elements), nor will it necessarily fire the click event of other elements.

Non–Gecko DOMs may behave differently.

Unfortunately it sounds like you have already discovered the best solution to your problem.

As a side note, I agree that your solution seems less than ideal, but if you encapsulate the functionality inside a method (much like JQuery would do) it is not so bad.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I do some quick tests and have the following findings:

1) if using SynchronousQueue:

After the threads reach the maximum size, any new work will be rejected with the exception like below.

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]

at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)

2) if using LinkedBlockingQueue:

The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.

Java: Find .txt files in specified folder

You can use the listFiles() method provided by the java.io.File class.

import java.io.File;
import java.io.FilenameFilter;

public class Filter {

    public File[] finder( String dirName){
        File dir = new File(dirName);

        return dir.listFiles(new FilenameFilter() { 
                 public boolean accept(File dir, String filename)
                      { return filename.endsWith(".txt"); }
        } );

    }

}

jQuery - multiple $(document).ready ...?

It is important to note that each jQuery() call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.

This applies regardless of syntax. You can use jQuery(), jQuery(function() {}), $(document).ready(), whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.

This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.

Debugging Stored Procedure in SQL Server 2008

Well the answer was sitting right in front of me the whole time.

In SQL Server Management Studio 2008 there is a Debug button in the toolbar. Set a break point in a query window to step through.

I dismissed this functionality at the beginning because I didn't think of stepping INTO the stored procedure, which you can do with ease.

SSMS basically does what FinnNK mentioned with the MSDN walkthrough but automatically.

So easy! Thanks for your help FinnNK.

Edit: I should add a step in there to find the stored procedure call with parameters I used SQL Profiler on my database.

How do I pass variables and data from PHP to JavaScript?

After much research, I found the easiest method is to pass all kinds of variables easily.

In the server script, you have two variables, and you are trying to send them to the client scripts:

$php_var1 ="Hello world";
$php_var2 ="Helloow";
echo '<script>';
echo 'var js_variable1= ' . json_encode($php_var1) . ';';
echo 'var js_variable2= ' . json_encode($php_var2) . ';';
echo '</script>';

In any of your JavaScript code called on the page, simply call those variables.

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

There's a strong chance that the privileges to select from table1 have been granted to a role, and the role has been granted to you. Privileges granted to a role are not available to PL/SQL written by a user, even if the user has been granted the role.

You see this a lot for users that have been granted the dba role on objects owned by sys. A user with dba role will be able to, say, SELECT * from V$SESSION, but will not be able to write a function that includes SELECT * FROM V$SESSION.

The fix is to grant explicit permissions on the object in question to the user directly, for example, in the case above, the SYS user has to GRANT SELECT ON V_$SESSION TO MyUser;

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How do I make Git use the editor of my choice for commits?

For MAC, BBEdit:

First, open BBEdit, click on the BBEdit logo, and choose Install Command-Line Tools.

Then from the command line,

git config --global core.editor "BBEdit -w"

What's the best free C++ profiler for Windows?

I use AQTime, it is one of the best profiling tools I've ever used. It isn't free but you can get a 30 day trial, so if you plan on a optimizing and profiling only one project and 30 days are enough for you then I would recommend using this application. (http://www.automatedqa.com/downloads/aqtime/index.asp)

How can I access "static" class variables within class methods in Python?

class Foo(object):
     bar = 1
     def bah(self):
         print Foo.bar

f = Foo() 
f.bah()

How can I do an asc and desc sort using underscore.js?

Descending order using underscore can be done by multiplying the return value by -1.

//Ascending Order:
_.sortBy([2, 3, 1], function(num){
    return num;
}); // [1, 2, 3]


//Descending Order:
_.sortBy([2, 3, 1], function(num){
    return num * -1;
}); // [3, 2, 1]

If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.

//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){ 
    return s.charCodeAt() * -1;
});

How can I select the record with the 2nd highest salary in database Oracle?

select * FROM (
select EmployeeID, Salary
, dense_rank() over (order by Salary DESC) ranking
from Employee
)
WHERE ranking = 2;

dense_rank() is used for the salary has to be same.So it give the proper output instead of using rank().

SQL Case Expression Syntax?

I dug up the Oracle page for the same and it looks like this is the same syntax, just described slightly different.

Link: Oracle/PLSQL: Case Statement

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

I had to locate my MySQL data directory:

SHOW VARIABLES WHERE Variable_Name LIKE "%dir"

Then force remove that database:

sudo rm -rf

Absolute position of an element on the screen using jQuery

For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..

function AbsoluteCoordinates($element) {
    var sTop = $(window).scrollTop();
    var sLeft = $(window).scrollLeft();
    var w = $element.width();
    var h = $element.height();
    var offset = $element.offset(); 
    var $p = $element;
    while(typeof $p == 'object') {
        var pOffset = $p.parent().offset();
        if(typeof pOffset == 'undefined') break;
        offset.left = offset.left + (pOffset.left);
        offset.top = offset.top + (pOffset.top);
        $p = $p.parent();
    }

    var pos = {
          left: offset.left + sLeft,
          right: offset.left + w + sLeft,
          top:  offset.top + sTop,
          bottom: offset.top + h + sTop,
    }
    pos.tl = { x: pos.left, y: pos.top };
    pos.tr = { x: pos.right, y: pos.top };
    pos.bl = { x: pos.left, y: pos.bottom };
    pos.br = { x: pos.right, y: pos.bottom };
    //console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom  );
    return pos;
}

How to remove "onclick" with JQuery?

Try this if you unbind the onclick event by ID Then use:

$('#youLinkID').attr('onclick','').unbind('click');

Try this if you unbind the onclick event by Class Then use:

$('.className').attr('onclick','').unbind('click');

Dynamic function name in javascript?

Thank you Marcosc! Building on his answer, if you want to rename any function, use this:

// returns the function named with the passed name
function namedFunction(name, fn) {
    return new Function('fn',
        "return function " + name + "(){ return fn.apply(this,arguments)}"
    )(fn)
}

Get the size of the screen, current web page and browser window

Full 2020

I am surprised that question have about 10 years and it looks like so far nobody has given a full answer (with 10 values) yet. So I carefully analyse OP question (especially picture) and have some remarks

  • center of coordinate system (0,0) is in the viewport (browser window without bars and main borders) top left corner and axes are directed to right and down (what was marked on OP picture) so the values of pageX, pageY, screenX, screenY must be negative (or zero if page is small or not scrolled)
  • for screenHeight/Width OP wants to count screen height/width including system menu bar (eg. in MacOs) - this is why we NOT use .availWidth/Height (which not count it)
  • for windowWidth/Height OP don't want to count size of scroll bars so we use .clientWidth/Height
  • the screenY - in below solution we add to position of top left browser corner (window.screenY) the height of its menu/tabls/url bar). But it is difficult to calculate that value if download-bottom bar appears in browser and/or if developer console is open on page bottom - in that case this value will be increased of size of that bar/console height in below solution. Probably it is impossible to read value of bar/console height to make correction (without some trick like asking user to close that bar/console before measurements...)
  • pageWidth - in case when pageWidth is smaller than windowWidth we need to manually calculate size of <body> children elements to get this value (we do example calculation in contentWidth in below solution - but in general this can be difficult for that case)
  • for simplicity I assume that <body> margin=0 - if not then you should consider this values when calculate pageWidth/Height and pageX/Y

_x000D_
_x000D_
function sizes() {
  let contentWidth = [...document.body.children].reduce( 
    (a, el) => Math.max(a, el.getBoundingClientRect().right), 0) 
    - document.body.getBoundingClientRect().x;

  return {
    windowWidth:  document.documentElement.clientWidth,
    windowHeight: document.documentElement.clientHeight,
    pageWidth:    Math.min(document.body.scrollWidth, contentWidth),
    pageHeight:   document.body.scrollHeight,
    screenWidth:  window.screen.width,
    screenHeight: window.screen.height,
    pageX:        document.body.getBoundingClientRect().x,
    pageY:        document.body.getBoundingClientRect().y,
    screenX:     -window.screenX,
    screenY:     -window.screenY - (window.outerHeight-window.innerHeight),
  }
}



// TEST

function show() {
  console.log(sizes());
}
_x000D_
body { margin: 0 }
.box { width: 3000px; height: 4000px; background: red; }
_x000D_
<div class="box">
  CAUTION: stackoverflow snippet gives wrong values for screenX-Y, 
  but if you copy this code to your page directly the values will be right<br>
  <button onclick="show()" style="">CALC</button>
</div>
_x000D_
_x000D_
_x000D_

I test it on Chrome 83.0, Safari 13.1, Firefox 77.0 and Edge 83.0 on MacOs High Sierra

How to get a list of all files that changed between two Git commits?

If you want to check the changed files you need to take care of many small things like which will be best to use , like if you want to check which of the files changed just type

git status -- it will show the files with changes

then if you want to know what changes are to be made it can be checked in ways ,

git diff -- will show all the changes in all files

it is good only when only one file is modified

and if you want to check particular file then use

git diff

How do I change selected value of select2 dropdown with JqGrid?

My Expected code :

$('#my-select').val('').change();

working perfectly thank to @PanPipes for the usefull one.

SQL query return data from multiple tables

Ok, I found this post very interesting and I would like to share some of my knowledge on creating a query. Thanks for this Fluffeh. Others who may read this and may feel that I'm wrong are 101% free to edit and criticise my answer. (Honestly, I feel very thankful for correcting my mistake(s).)

I'll be posting some of the frequently asked questions in MySQL tag.


Trick No. 1 (rows that matches to multiple conditions)

Given this schema

CREATE TABLE MovieList
(
    ID INT,
    MovieName VARCHAR(25),
    CONSTRAINT ml_pk PRIMARY KEY (ID),
    CONSTRAINT ml_uq UNIQUE (MovieName)
);

INSERT INTO MovieList VALUES (1, 'American Pie');
INSERT INTO MovieList VALUES (2, 'The Notebook');
INSERT INTO MovieList VALUES (3, 'Discovery Channel: Africa');
INSERT INTO MovieList VALUES (4, 'Mr. Bean');
INSERT INTO MovieList VALUES (5, 'Expendables 2');

CREATE TABLE CategoryList
(
    MovieID INT,
    CategoryName VARCHAR(25),
    CONSTRAINT cl_uq UNIQUE(MovieID, CategoryName),
    CONSTRAINT cl_fk FOREIGN KEY (MovieID) REFERENCES MovieList(ID)
);

INSERT INTO CategoryList VALUES (1, 'Comedy');
INSERT INTO CategoryList VALUES (1, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Drama');
INSERT INTO CategoryList VALUES (3, 'Documentary');
INSERT INTO CategoryList VALUES (4, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Action');

QUESTION

Find all movies that belong to at least both Comedy and Romance categories.

Solution

This question can be very tricky sometimes. It may seem that a query like this will be the answer:-

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName = 'Comedy' AND
        b.CategoryName = 'Romance'

SQLFiddle Demo

which is definitely very wrong because it produces no result. The explanation of this is that there is only one valid value of CategoryName on each row. For instance, the first condition returns true, the second condition is always false. Thus, by using AND operator, both condition should be true; otherwise, it will be false. Another query is like this,

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')

SQLFiddle Demo

and the result is still incorrect because it matches to record that has at least one match on the categoryName. The real solution would be by counting the number of record instances per movie. The number of instance should match to the total number of the values supplied in the condition.

SELECT  a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')
GROUP BY a.MovieName
HAVING COUNT(*) = 2

SQLFiddle Demo (the answer)


Trick No. 2 (maximum record for each entry)

Given schema,

CREATE TABLE Software
(
    ID INT,
    SoftwareName VARCHAR(25),
    Descriptions VARCHAR(150),
    CONSTRAINT sw_pk PRIMARY KEY (ID),
    CONSTRAINT sw_uq UNIQUE (SoftwareName)  
);

INSERT INTO Software VALUES (1,'PaintMe','used for photo editing');
INSERT INTO Software VALUES (2,'World Map','contains map of different places of the world');
INSERT INTO Software VALUES (3,'Dictionary','contains description, synonym, antonym of the words');

CREATE TABLE VersionList
(
    SoftwareID INT,
    VersionNo INT,
    DateReleased DATE,
    CONSTRAINT sw_uq UNIQUE (SoftwareID, VersionNo),
    CONSTRAINT sw_fk FOREIGN KEY (SOftwareID) REFERENCES Software(ID)
);

INSERT INTO VersionList VALUES (3, 2, '2009-12-01');
INSERT INTO VersionList VALUES (3, 1, '2009-11-01');
INSERT INTO VersionList VALUES (3, 3, '2010-01-01');
INSERT INTO VersionList VALUES (2, 2, '2010-12-01');
INSERT INTO VersionList VALUES (2, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 3, '2011-12-01');
INSERT INTO VersionList VALUES (1, 2, '2010-12-01');
INSERT INTO VersionList VALUES (1, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 4, '2012-12-01');

QUESTION

Find the latest version on each software. Display the following columns: SoftwareName,Descriptions,LatestVersion (from VersionNo column),DateReleased

Solution

Some SQL developers mistakenly use MAX() aggregate function. They tend to create like this,

SELECT  a.SoftwareName, a.Descriptions,
        MAX(b.VersionNo) AS LatestVersion, b.DateReleased
FROM    Software a
        INNER JOIN VersionList b
            ON a.ID = b.SoftwareID
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo

(most RDBMS generates a syntax error on this because of not specifying some of the non-aggregated columns on the group by clause) the result produces the correct LatestVersion on each software but obviously the DateReleased are incorrect. MySQL doesn't support Window Functions and Common Table Expression yet as some RDBMS do already. The workaround on this problem is to create a subquery which gets the individual maximum versionNo on each software and later on be joined on the other tables.

SELECT  a.SoftwareName, a.Descriptions,
        b.LatestVersion, c.DateReleased
FROM    Software a
        INNER JOIN
        (
            SELECT  SoftwareID, MAX(VersionNO) LatestVersion
            FROM    VersionList
            GROUP BY SoftwareID
        ) b ON a.ID = b.SoftwareID
        INNER JOIN VersionList c
            ON  c.SoftwareID = b.SoftwareID AND
                c.VersionNO = b.LatestVersion
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo (the answer)


So that was it. I'll be posting another soon as I recall any other FAQ on MySQL tag. Thank you for reading this little article. I hope that you have atleast get even a little knowledge from this.

UPDATE 1


Trick No. 3 (Finding the latest record between two IDs)

Given Schema

CREATE TABLE userList
(
    ID INT,
    NAME VARCHAR(20),
    CONSTRAINT us_pk PRIMARY KEY (ID),
    CONSTRAINT us_uq UNIQUE (NAME)  
);

INSERT INTO userList VALUES (1, 'Fluffeh');
INSERT INTO userList VALUES (2, 'John Woo');
INSERT INTO userList VALUES (3, 'hims056');

CREATE TABLE CONVERSATION
(
    ID INT,
    FROM_ID INT,
    TO_ID INT,
    MESSAGE VARCHAR(250),
    DeliveryDate DATE
);

INSERT INTO CONVERSATION VALUES (1, 1, 2, 'hi john', '2012-01-01');
INSERT INTO CONVERSATION VALUES (2, 2, 1, 'hello fluff', '2012-01-02');
INSERT INTO CONVERSATION VALUES (3, 1, 3, 'hey hims', '2012-01-03');
INSERT INTO CONVERSATION VALUES (4, 1, 3, 'please reply', '2012-01-04');
INSERT INTO CONVERSATION VALUES (5, 3, 1, 'how are you?', '2012-01-05');
INSERT INTO CONVERSATION VALUES (6, 3, 2, 'sample message!', '2012-01-05');

QUESTION

Find the latest conversation between two users.

Solution

SELECT    b.Name SenderName,
          c.Name RecipientName,
          a.Message,
          a.DeliveryDate
FROM      Conversation a
          INNER JOIN userList b
            ON a.From_ID = b.ID
          INNER JOIN userList c
            ON a.To_ID = c.ID
WHERE     (LEAST(a.FROM_ID, a.TO_ID), GREATEST(a.FROM_ID, a.TO_ID), DeliveryDate)
IN
(
    SELECT  LEAST(FROM_ID, TO_ID) minFROM,
            GREATEST(FROM_ID, TO_ID) maxTo,
            MAX(DeliveryDate) maxDate
    FROM    Conversation
    GROUP BY minFROM, maxTo
)

SQLFiddle Demo

Can't bind to 'dataSource' since it isn't a known property of 'table'

If you've tried everything mentioned here and it didn't work, make sure you also have added angular material to your project. If not, just run the following command in the terminal to add it:

ng add @angular/material

After it successfully gets added, wait for the project to get refreshed, and the error will be automatically gone.

Change select box option background color

enter image description here

Similar to some of the answers, but not really stated, is to add a class to the actual option tag and use css classes...this is currently working for me without issue on IE (see above ss).

<select id="reviewAction">
<option class="greenColor">Accept and Advance Status</option>
<option class="redColor">Return for Modifications</option>
</select>

CSS:

.greenColor{
    background-color: #33CC33;
}
.redColor{
    background-color: #E60000;
}

how to access the command line for xampp on windows

Thank you guys for this answers. But I think the accepted answer needs more clarity, As i found difficulty in getting the solution.

  1. We may set the environment variable as mentioned in the answer by w0rldart .

    In this case(after seting envmnt var) we may run the phpFile by opening start >> CMD and typing commands like,

    php.exe <path to file location>

    or

    php <path to file location>

    example:

    php.exe C:\xampp\htdocs\test.php
    
  2. you can open Start >> CMD as administrator and write like

    <path to php.exe in xampp's php folder> <path to file location>

    example:

    C:\xampp\php\php.exe C:\xampp\htdocs\test.php
    

    or

    C:\xampp\php\php C:\xampp\htdocs\test.php
    

Hopes this will help somebody.

Clear the form field after successful submission of php form

I have a simple form to submit testimonials, I also was having trouble clearing the form, what I did was after the query is submitted successfully I and before redirecting to another page I cleared the imputs $name =''; ect. The page submitted and redirected with no errors.

When to use 'raise NotImplementedError'?

As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.

There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.

Here's a Python 3 example:

class C(abc.ABC):
    @abc.abstractmethod
    def my_abstract_method(self, ...):
        ...

When instantiating C, you'll get an error because my_abstract_method is abstract. You need to implement it in a child class.

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

Subclass C and implement my_abstract_method.

class D(C):
    def my_abstract_method(self, ...):
        ...

Now you can instantiate D.

C.my_abstract_method does not have to be empty. It can be called from D using super().

An advantage of this over NotImplementedError is that you get an explicit Exception at instantiation time, not at method call time.

How do I create a user account for basic authentication?

Configure basic authentication using the instructions from microsoft. But for the Default Domain Name, type your computer name. To find your computer name, click start, right-click computer, click properties, and search for your computer name there :)

Next, create users like you would normally do on windows 7. or if you don't know how to do it, go control-panel, users, add account.....blah blah blah.... Get It?

Next go to iis and set permissions for the user you just created. Be carefull to set the permissions to make it exactly how you want it.

That's all! To login, the username and password!

NOTE: The username should be simple letters, not capital. I'm not sure about this, that's why i told you this.

How do you create a Swift Date object?

Swift doesn't have its own Date type, but you to use the existing Cocoa NSDate type, e.g:

class Date {

    class func from(year: Int, month: Int, day: Int) -> Date {
        let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!

        var dateComponents = DateComponents()
        dateComponents.year = year
        dateComponents.month = month
        dateComponents.day = day

        let date = gregorianCalendar.date(from: dateComponents)!
        return date
    }

    class func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone.default
        dateFormatter.dateFormat = format

        let date = dateFormatter.date(from: string)!
        return date
    }
}

Which you can use like:

var date = Date.parse("2014-05-20")
var date = Date.from(year: 2014, month: 05, day: 20)

How do I float a div to the center?

Simple solution:

<style>
.center {
    margin: auto;

}
</style>

<div class="center">
    <p> somthing goes here </p>
</div>

Try Online

How to force reloading a page when using browser back button?

Currently this is the most up to date way reload page if the user clicks the back button.

const [entry] = performance.getEntriesByType("navigation");

// Show it in a nice table in the developer console
console.table(entry.toJSON());

if (entry["type"] === "back_forward")
    location.reload();

See here for source

Accessing Google Spreadsheets with C# using Google Data API

http://code.google.com/apis/gdata/articles/dotnet_client_lib.html

This should get you started. I haven't played with it lately but I downloaded a very old version a while back and it seemed pretty solid. This one is updated to Visual Studio 2008 as well so check out the docs!

Run class in Jar file

Use java -cp myjar.jar com.mypackage.myClass.

  1. If the class is not in a package then simply java -cp myjar.jar myClass.

  2. If you are not within the directory where myJar.jar is located, then you can do:

    1. On Unix or Linux platforms:

      java -cp /location_of_jar/myjar.jar com.mypackage.myClass

    2. On Windows:

      java -cp c:\location_of_jar\myjar.jar com.mypackage.myClass

How best to determine if an argument is not sent to the JavaScript function

This is one of the few cases where I find the test:

if(! argument2) {  

}

works quite nicely and carries the correct implication syntactically.

(With the simultaneous restriction that I wouldn't allow a legitimate null value for argument2 which has some other meaning; but that would be really confusing.)

EDIT:

This is a really good example of a stylistic difference between loosely-typed and strongly-typed languages; and a stylistic option that javascript affords in spades.

My personal preference (with no criticism meant for other preferences) is minimalism. The less the code has to say, as long as I'm consistent and concise, the less someone else has to comprehend to correctly infer my meaning.

One implication of that preference is that I don't want to - don't find it useful to - pile up a bunch of type-dependency tests. Instead, I try to make the code mean what it looks like it means; and test only for what I really will need to test for.

One of the aggravations I find in some other peoples' code is needing to figure out whether or not they expect, in the larger context, to actually run into the cases they are testing for. Or if they are trying to test for everything possible, on the chance that they don't anticipate the context completely enough. Which means I end up needing to track them down exhaustively in both directions before I can confidently refactor or modify anything. I figure that there's a good chance they might have put those various tests in place because they foresaw circumstances where they would be needed (and which usually aren't apparent to me).

(I consider that a serious downside in the way these folks use dynamic languages. Too often people don't want to give up all the static tests, and end up faking it.)

I've seen this most glaringly in comparing comprehensive ActionScript 3 code with elegant javascript code. The AS3 can be 3 or 4 times the bulk of the js, and the reliability I suspect is at least no better, just because of the number (3-4X) of coding decisions that were made.

As you say, Shog9, YMMV. :D

How to check if a service is running via batch file and start it, if it is not running?

You can use the following command to see if a service is running or not:

sc query [ServiceName] | findstr /i "STATE"

When I run it for my NOD32 Antivirus, I get:

STATE                       : 4 RUNNING

If it was stopped, I would get:

STATE                       : 1 STOPPED

You can use this in a variable to then determine whether you use NET START or not.

The service name should be the service name, not the display name.

The type is defined in an assembly that is not referenced, how to find the cause?

The type 'Domain.tblUser' is defined in an assembly that is not referenced. You must add a reference to assembly 'Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

**Solved:**
 Add reference of my domain library layer to my web app libary layer

Note: Make sure your references are correct according to you DI container

Should Jquery code go in header or footer?

Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.

Write values in app.config file

private static string GetSetting(string key)
{
    return ConfigurationManager.AppSettings[key];
}

private static void SetSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save(ConfigurationSaveMode.Full, true);
    ConfigurationManager.RefreshSection("appSettings");
}

How to save SELECT sql query results in an array in C# Asp.net

Pretty easy:

 public void PrintSql_Array()
    {
        int[] numbers = new int[4];
        string[] names = new string[4];
        string[] secondNames = new string[4];
        int[] ages = new int[4];

        int cont = 0;

        string cs = @"Server=ADMIN\SQLEXPRESS; Database=dbYourBase; User id=sa; password=youpass";
        using (SqlConnection con = new SqlConnection(cs))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT * FROM tbl_Datos";
                con.Open();

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);

                foreach (DataRow row in dt.Rows)
                {
                    numbers[cont] = row.Field<int>(0);
                    names[cont] = row.Field<string>(1);
                    secondNames[cont] = row.Field<string>(2);
                    ages[cont] = row.Field<int>(3);

                    cont++;
                }

                for (int i = 0; i < numbers.Length; i++)
                {
                    Console.WriteLine("{0} | {1} {2} {3}", numbers[i], names[i], secondNames[i], ages[i]);
                }

                con.Close();
            }
        }
    }

Substring in VBA

You can first find the position of the string in this case ":"

'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")

Then use Left(StringToCut, NumberOfCharacterToCut)

Result = Left(StringToSearch, position -1)

Get the week start date and week end date from week number

This is my solution


    SET DATEFIRST 1;    /* change to use a different datefirst  */
    DECLARE @date DATETIME
    SET @date = CAST('2/6/2019' as date)

    SELECT  DATEADD(dd,0 - (DATEPART(dw, @date) - 1) ,@date) [dateFrom], 
            DATEADD(dd,6 - (DATEPART(dw, @date) - 1) ,@date) [dateTo]

How do I create a new user in a SQL Azure database?

You can simply create a contained user in SQL DB V12.

Create user containeduser with password = 'Password'

Contained user login is more efficient than login to the database using the login created by master. You can find more details @ http://www.sqlindepth.com/contained-users-in-sql-azure-db-v12/

'too many values to unpack', iterating over a dict. key=>string, value=>list

For Python 3.x iteritems has been removed. Use items instead.

for field, possible_values in fields.items():
    print(field, possible_values)

browser sessionStorage. share between tabs?

Using sessionStorage for this is not possible.

From the MDN Docs

Opening a page in a new tab or window will cause a new session to be initiated.

That means that you can't share between tabs, for this you should use localStorage

How do I change a single value in a data.frame?

To change a cell value using a column name, one can use

iris$Sepal.Length[3]=999

Print raw string from variable? (not getting the answers)

Replace back-slash with forward-slash using one of the below:

  • re.sub(r"\", "/", x)
  • re.sub(r"\", "/", x)

How can I get a specific parameter from location.search?

I used a variant of Alex's - but needed to to convert the param appearing multiple times to an array. There seem to be many options. I didn't want rely on another library for something this simple. I suppose one of the other options posted here may be better - I adapted Alex's because of the straight forwardness.

parseQueryString = function() {
    var str = window.location.search;
    var objURL = {};

    // local isArray - defer to underscore, as we are already using the lib
    var isArray = _.isArray

    str.replace(
        new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
        function( $0, $1, $2, $3 ){

            if(objURL[ $1 ] && !isArray(objURL[ $1 ])){
                // if there parameter occurs more than once, convert to an array on 2nd
                var first = objURL[ $1 ]
                objURL[ $1 ] = [first, $3]
            } else if(objURL[ $1 ] && isArray(objURL[ $1 ])){
                // if there parameter occurs more than once, add to array after 2nd
                objURL[ $1 ].push($3)
            }
            else
            {
                // this is the first instance
                objURL[ $1 ] = $3;
            }

        }
    );
    return objURL;
};

Links in <select> dropdown options

Maybe this will help:

<select onchange="location = this.value;">
 <option value="home.html">Home</option>
 <option value="contact.html">Contact</option>
 <option value="about.html">About</option>
</select>

UIView Infinite 360 degree rotation animation?

I has developed a shiny animation framework which can save you tone of time! Using it this animation can be created very easily:

private var endlessRotater: EndlessAnimator!
override func viewDidAppear(animated: Bool) 
{
    super.viewDidAppear(animated)
    let rotationAnimation = AdditiveRotateAnimator(M_PI).to(targetView).duration(2.0).baseAnimation(.CurveLinear)
    endlessRotater = EndlessAnimator(rotationAnimation)
    endlessRotater.animate()
}

to stop this animation simply set nil to endlessRotater.

If you are interested, please take a look: https://github.com/hip4yes/Animatics

Build android release apk on Phonegap 3.x CLI

Building PhoneGap Android app for deployment to the Google Play Store

These steps would work for Cordova, PhoneGap or Ionic. The only difference would be, wherever a call to cordova is placed, replace it with phonegap or ionic, for your particular scenario.

Once you are done with the development and are ready to deploy, follow these steps:

  1. Open a command line window (Terminal on macOS and Linux OR Command Prompt on Windows).

  2. Head over to the /path/to/your/project/, which we would refer to as the Project Root.

  3. While at the project root, remove the "Console" plugin from your set of plugins.

    The command is: cordova plugin rm cordova-plugin-console

  4. While still at the project root, use the cordova build command to create an APK for release distribution.

    The command is: cordova build --release android

  5. The above process creates a file called android-release-unsigned.apk in the folder ProjectRoot/platforms/android/build/outputs/apk/

  6. Sign and align the APK using the instructions at https://developer.android.com/studio/publish/app-signing.html#signing-manually

    At the end of this step the APK which you get can be uploaded to the Play Store.

Note: As a newbie or a beginner, the last step may be a bit confusing as it was to me. One may run into a few issues and may have some questions as to what these commands are and where to find them.

Q1. What are jarsigner and keytool?
Ans: The Android App Signing instructions do tell you specifically what jarsigner and keytool are all about BUT it doesn't tell you where to find them if you run into a 'command not found error' on the command line window.

Thus, if you've got the Java Development Kit(JDK) added to your PATH variable, simply running the commands as in the Guide would work. BUT, if you don't have it in your PATH, you can always access them from the bin folder of your JDK installation.

Q2. Where is zipalign?
Ans: There is a high probability to not find the zipalign command and receive the 'command not found error'. You'd probably be googling zipalign and where to find it?

The zipalign utility is present within the Android SDK installation folder. On macOS, the default location is at, user-name/Library/Android/sdk/. If you head over to the folder you would find a bunch of other folders like docs, platform-tools, build-tools, tools, add-ons...

Open the build-tools folder. cd build-tools. In here, there would be a number of folders which are versioned according to the build tool-chain you are using in the Android SDK Manager. ZipAlign is available in each of these folders. I personally go for the folder with the latest version on it. Open Any.

On macOS or Linux you may have to use ./zipalign rather than simply typing in zipalign as the documentation mentions. On Windows, zipalign is good enough.

Artisan, creating tables in database

Migration files must match the pattern *_*.php, or else they won't be found. Since users.php does not match this pattern (it has no underscore), this file will not be found by the migrator.

Ideally, you should be creating your migration files using artisan:

php artisan make:migration create_users_table

This will create the file with the appropriate name, which you can then edit to flesh out your migration. The name will also include the timestamp, to help the migrator determine the order of migrations.

You can also use the --create or --table switches to add a little bit more boilerplate to help get you started:

php artisan make:migration create_users_table --create=users

The documentation on migrations can be found here.

fe_sendauth: no password supplied

Do not use passwords. Use peer authentication instead:

postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb

Session timeout in ASP.NET

In my situation, it was Application Pool. It is set to restart when idle for xx mins. When I set it to not restart, it seems to use value from Web Config.

PHP check file extension

$file = $_FILES["file"] ["tmp_name"]; 
$check_ext = strtolower(pathinfo($file,PATHINFO_EXTENSION));
if ($check_ext == "fileext") {
    //code
}
else { 
    //code
}

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

Naming Conventions: What to name a boolean variable?

Haskell uses init to refer to all but the last element of a list (the inverse of tail, basically); would isInInit work, or is that too opaque?

Dynamic WHERE clause in LINQ

You can also use the PredicateBuilder from LinqKit to chain multiple typesafe lambda expressions using Or or And.

http://www.albahari.com/nutshell/predicatebuilder.aspx

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

In your home directory, you should edit .bash_profile if you have Git for Windows 2.21.0 or later (as of this writing).

You could direct .bash_profile to just source .bashrc, but if something happens to your .bash_profile, then it will be unclear why your .bashrc is again not working.

I put all my aliases and other environment stuff in .bash_profile, and I also added this line:

echo "Sourcing ~/.bash_profile - this version of Git Bash doesn't use .bashrc"

And THEN, in .bashrc I have

echo "This version of Git Bash doesn't use .bashrc. Use .bash_profile instead"

(Building on @harsel's response. I woulda commented, but I have no points yet.)

Why call git branch --unset-upstream to fixup?

Actually torek told you already how to use the tools much better than I would be able to do. However, in this case I think it is important to point out something peculiar if you follow the guidelines at http://octopress.org/docs/deploying/github/. Namely, you will have multiple github repositories in your setup. First of all the one with all the source code for your website in say the directory $WEBSITE, and then the one with only the static generated files residing in $WEBSITE/_deploy. The funny thing of the setup is that there is a .gitignore file in the $WEBSITE directory so that this setup actually works.

Enough introduction. In this case the error might also come from the repository in _deploy.

cd _deploy

git branch -a
* master
remotes/origin/master
remotes/origin/source

In .git/config you will normally need to find something like this:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = [email protected]:yourname/yourname.github.io.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

But in your case the branch master does not have a remote.

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = [email protected]:yourname/yourname.github.io.git
    fetch = +refs/heads/*:refs/remotes/origin/*

Which you can solve by:

cd _deploy
git branch --set-upstream-to=origin/master

So, everything is as torek told you, but it might be important to point out that this very well might concern the _deploy directory rather than the root of your website.

PS: It might be worth to use a shell such as zsh with a git plugin to not be bitten by this thing in the future. It will immediately show that _deploy concerns a different repository.

Value cannot be null. Parameter name: source

It could be as silly as in my case where savechanges was erroring bcoz the db did not have foreign keys and associations were added to EDM tables. I added foreign keys in the db and regenerated EDM for a fix.

The errors I was seeing are as follows: Case 1 -> when using DBContext for EDM Message=Value cannot be null. Parameter name: source at System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate)

Case 2 -> when using ObjectContext for EDM Message=Unable to update the EntitySet 'Contact' because it has a DefiningQuery and no element exists in the element to support the current operation.

(Just wanted to throw it in there in case it helps someone).

How can I get useful error messages in PHP?

using @inexistent_function_call(); in your code will cause the intepreter to quietly die and abort the script parsing. You should check for invalid functions and try not to use the error-supressing operator(the @ char )

Send array with Ajax to PHP script

Data in jQuery ajax() function accepts anonymous objects as its input, see documentation. So example of what you're looking for is:

dataString = {key: 'val', key2: 'val2'};
$.ajax({
        type: "POST",
        url: "script.php",
        data: dataString, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

You may also write POST/GET query on your own, like key=val&key2=val2, but you'd have to handle escaping yourself which is impractical.

TypeError: $ is not a function when calling jQuery function

What worked for me. The first library to import is the query library and right then call the jQuery.noConflict() method.

<head>
 <script type="text/javascript" src="jquery.min.js"/>
 <script>
  var jq = jQuery.noConflict();
  jq(document).ready(function(){
  //.... your code here
    });
 </script>

What tools do you use to test your public REST API?

We test our own with our own unit tests and oftentimes a dedicated client app.

Laravel PHP Command Not Found

Solution on link http://tutsnare.com/laravel-command-not-found-ubuntu-mac/

In terminal

# download installer
composer global require "laravel/installer=~1.1"
#setting up path
export PATH="~/.composer/vendor/bin:$PATH" 
# check laravel command
laravel 

# download installer
composer global require "laravel/installer=~1.1"

nano ~/.bashrc

#add

alias laravel='~/.composer/vendor/bin/laravel'

source ~/.bashrc

laravel

# going to html dir to create project there
cd /var/www/html/
# install project in blog dir.
laravel new blog

In angular $http service, How can I catch the "status" of error?

Response status comes as second parameter in callback, (from docs):

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

How to change resolution (DPI) of an image?

This article talks about modifying the EXIF data without the re-saving/re-compressing (and thus loss of information -- it actually uses a "trick"; there may be more direct libraries) required by the SetResolution approach. This was found on a quick google search, but I wanted to point out that all you need to do is modify the stored EXIF data.

Also: .NET lib for EXIF modification and another SO question. Google owns when you know good search terms.

Adding one day to a date

Try this

echo date('Y-m-d H:i:s',date(strtotime("+1 day", strtotime("2009-09-30 20:24:00"))));

How do you install an APK file in the Android emulator?

Goto Shell/Terminal/, reach at android-sdk/tools directory then

adb install fileName.apk // (u can run this command on windows)
or 
./adb install fileName.apk  //( u can run this command on linux)

What's the best way to set a single pixel in an HTML5 canvas?

To complete Phrogz very thorough answer, there is a critical difference between fillRect() and putImageData().
The first uses context to draw over by adding a rectangle (NOT a pixel), using the fillStyle alpha value AND the context globalAlpha and the transformation matrix, line caps etc..
The second replaces an entire set of pixels (maybe one, but why ?)
The result is different as you can see on jsperf.


Nobody wants to set one pixel at a time (meaning drawing it on screen). That is why there is no specific API to do that (and rightly so).
Performance wise, if the goal is to generate a picture (for example a ray-tracing software), you always want to use an array obtained by getImageData() which is an optimized Uint8Array. Then you call putImageData() ONCE or a few times per second using setTimeout/seTInterval.

python how to "negate" value : if true return false, if false return true

Use the not boolean operator:

nyval = not myval

not returns a boolean value (True or False):

>>> not 1
False
>>> not 0
True

If you must have an integer, cast it back:

nyval = int(not myval)

However, the python bool type is a subclass of int, so this may not be needed:

>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True

How to create timer events using C++ 11?

If you are on Windows, you can use the CreateThreadpoolTimer function to schedule a callback without needing to worry about thread management and without blocking the current thread.

template<typename T>
static void __stdcall timer_fired(PTP_CALLBACK_INSTANCE, PVOID context, PTP_TIMER timer)
{
    CloseThreadpoolTimer(timer);
    std::unique_ptr<T> callable(reinterpret_cast<T*>(context));
    (*callable)();
}

template <typename T>
void call_after(T callable, long long delayInMs)
{
    auto state = std::make_unique<T>(std::move(callable));
    auto timer = CreateThreadpoolTimer(timer_fired<T>, state.get(), nullptr);
    if (!timer)
    {
        throw std::runtime_error("Timer");
    }

    ULARGE_INTEGER due;
    due.QuadPart = static_cast<ULONGLONG>(-(delayInMs * 10000LL));

    FILETIME ft;
    ft.dwHighDateTime = due.HighPart;
    ft.dwLowDateTime = due.LowPart;

    SetThreadpoolTimer(timer, &ft, 0 /*msPeriod*/, 0 /*msWindowLength*/);
    state.release();
}

int main()
{
    auto callback = []
    {
        std::cout << "in callback\n";
    };

    call_after(callback, 1000);
    std::cin.get();
}

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

Creating and returning Observable from Angular 2 Service

I would like to add that if the object that is created is static and not coming through http something like that can be done:

public fetchModel(uuid: string = undefined): Observable<string> {
      if(!uuid) { //static data
        return Observable.of(new TestModel()).map(o => JSON.stringify(o));
      }
      else {
        return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
                .map(res => res.text());
      }
    }

Edit: For Angular 7.x.x mapping needs to be done using pipe() as described here (https://stackoverflow.com/a/54085359/986160):

import {of,  Observable } from 'rxjs';
import { map } from 'rxjs/operators';
[...]
public fetchModel(uuid: string = undefined): Observable<string> {
      if(!uuid) { //static data
        return of(new TestModel());
      }
      else {
        return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
                .pipe(map((res:any) => res)) //already contains json
      }
    }

from answer to my question about observers and static data: https://stackoverflow.com/a/35219772/986160

How do you use a variable in a regular expression?

"ABABAB".replace(/B/g, "A");

As always: don't use regex unless you have to. For a simple string replace, the idiom is:

'ABABAB'.split('B').join('A')

Then you don't have to worry about the quoting issues mentioned in Gracenotes's answer.

How do I supply an initial value to a text field?

TextEdittingController _controller = new TextEdittingController(text: "your Text");

or

@override
  void initState() {
    super.initState();
    _Controller.text = "Your Text";
    }

HTML form with multiple "actions"

the best way (for me) to make it it's the next infrastructure:

<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>

with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.

Getting files by creation date in .NET

this could work for you.

using System.Linq;

DirectoryInfo info = new DirectoryInfo("PATH_TO_DIRECTORY_HERE");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
{
    // DO Something...
}

Type datetime for input parameter in procedure

You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.

The ISO-8601 format for a DATETIME when using only the date is: YYYYMMDD (no dashes or antyhing!)

For a DATETIME with the time portion, it's YYYY-MM-DDTHH:MM:SS (with dashes, and a T in the middle to separate date and time portions).

If you want to convert a string to a DATE for SQL Server 2008 or newer, you can use YYYY-MM-DD (with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.

So in your case, you should try:

declare @a datetime
declare @b datetime 

set @a = '2012-04-06T12:23:45'   -- 6th of April, 2012
set @b = '2012-08-06T21:10:12'   -- 6th of August, 2012

exec LogProcedure 'AccountLog', N'test', @a, @b

Furthermore - your stored proc has problem, since you're concatenating together datetime and string into a string, but you're not converting the datetime to string first, and also, you're forgetting the close quotes in your statement after both dates.

So change this line here to this:

IF @DateFirst <> '' and @DateLast <> ''
   SET @FinalSQL  = @FinalSQL + '  OR CONVERT(Date, DateLog) >= ''' + 
                    CONVERT(VARCHAR(50), @DateFirst, 126) +   -- convert @DateFirst to string for concatenation!
                    ''' AND CONVERT(Date, DateLog) <=''' +  -- you need closing quotes after @DateFirst!
                    CONVERT(VARCHAR(50), @DateLast, 126) + ''''      -- convert @DateLast to string and also: closing tags after that missing!

With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.

Checking if a variable is not nil and not zero in ruby

I believe the following is good enough for ruby code. I don't think I could write a unit test that shows any difference between this and the original.

if discount != 0
end

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

RookieRick is right, using DataGridTemplateColumn instead of DataGridComboBoxColumn gives a much simpler XAML.

Moreover, putting the CompanyItem list directly accessible from the GridItem allows you to get rid of the RelativeSource.

IMHO, this give you a very clean solution.

XAML:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
    <DataGrid.Resources>
        <DataTemplate x:Key="CompanyDisplayTemplate" DataType="vm:GridItem">
            <TextBlock Text="{Binding Company}" />
        </DataTemplate>
        <DataTemplate x:Key="CompanyEditingTemplate" DataType="vm:GridItem">
            <ComboBox SelectedItem="{Binding Company}" ItemsSource="{Binding CompanyList}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" />
        <DataGridTemplateColumn CellTemplate="{StaticResource CompanyDisplayTemplate}"
                                CellEditingTemplate="{StaticResource CompanyEditingTemplate}" />
    </DataGrid.Columns>
</DataGrid>

View model:

public class GridItem
{
    public string Name { get; set; }
    public CompanyItem Company { get; set; }
    public IEnumerable<CompanyItem> CompanyList { get; set; }
}

public class CompanyItem
{
    public int ID { get; set; }
    public string Name { get; set; }

    public override string ToString() { return Name; }
}

public class ViewModel
{
    readonly ObservableCollection<CompanyItem> companies;

    public ViewModel()
    {
        companies = new ObservableCollection<CompanyItem>{
            new CompanyItem { ID = 1, Name = "Company 1" },
            new CompanyItem { ID = 2, Name = "Company 2" }
        };

        GridItems = new ObservableCollection<GridItem> {
            new GridItem { Name = "Jim", Company = companies[0], CompanyList = companies}
        };
    }

    public ObservableCollection<GridItem> GridItems { get; set; }
}

How to set upload_max_filesize in .htaccess?

php_value upload_max_filesize 30M is correct.

You will have to contact your hosters -- some don't allow you to change values in php.ini

Java - checking if parseInt throws exception

Check if it is integer parseable

public boolean isInteger(String string) {
    try {
        Integer.valueOf(string);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

or use Scanner

Scanner scanner = new Scanner("Test string: 12.3 dog 12345 cat 1.2E-3");

while (scanner.hasNext()) {
    if (scanner.hasNextDouble()) {
        Double doubleValue = scanner.nextDouble();
    } else {
        String stringValue = scanner.next();
    }
}

or use Regular Expression like

private static Pattern doublePattern = Pattern.compile("-?\\d+(\\.\\d*)?");

public boolean isDouble(String string) {
    return doublePattern.matcher(string).matches();
}

Show/hide div if checkbox selected

You would need to always consider the state of all checkboxes!

You could increase or decrease a number on checking or unchecking, but imagine the site loads with three of them checked.

So you always need to check all of them:

<script type="text/javascript">
<!--
function showMe (it, box) {
  // consider all checkboxes with same name
  var checked = amountChecked(box.name);

  var vis = (checked >= 3) ? "block" : "none";
  document.getElementById(it).style.display = vis;
}

function amountChecked(name) {
  var all = document.getElementsByName(name);

  // count checked
  var result = 0;
  all.forEach(function(el) {
    if (el.checked) result++;
  });

  return result;
}
//-->
</script>

DLL and LIB files - what and why?

A DLL is a library of functions that are shared among other executable programs. Just look in your windows/system32 directory and you will find dozens of them. When your program creates a DLL it also normally creates a lib file so that the application *.exe program can resolve symbols that are declared in the DLL.

A .lib is a library of functions that are statically linked to a program -- they are NOT shared by other programs. Each program that links with a *.lib file has all the code in that file. If you have two programs A.exe and B.exe that link with C.lib then each A and B will both contain the code in C.lib.

How you create DLLs and libs depend on the compiler you use. Each compiler does it differently.

Reverse HashMap keys and values in Java

private <A, B> Map<B, A> invertMap(Map<A, B> map) {
    Map<B, A> reverseMap = new HashMap<>();
    for (Map.Entry<A, B> entry : map.entrySet()) {
        reverseMap.put(entry.getValue(), entry.getKey());
    }
    return reverseMap;
}

It's important to remember that put replaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.

What is the difference between 'git pull' and 'git fetch'?

Git allows chronologically older commits to be applied after newer commits. Because of this, the act of transferring commits between repositories is split into two steps:

  1. Copying new commits from remote branch to copy of this remote branch inside local repo.

    (repo to repo operation) master@remote >> remote/origin/master@local

  2. Integrating new commits to local branch

    (inside-repo operation) remote/origin/master@local >> master@local

There are two ways of doing step 2. You can:

  1. Fork local branch after last common ancestor and add new commits parallel to commits which are unique to local repository, finalized by merging commit, closing the fork.
  2. Insert new commits after last common ancestor and reapply commits unique to local repository.

In git terminology, step 1 is git fetch, step 2 is git merge or git rebase

git pull is git fetch and git merge

Can I concatenate multiple MySQL rows into one field?

Try this:

DECLARE @Hobbies NVARCHAR(200) = ' '

SELECT @Hobbies = @Hobbies + hobbies + ',' FROM peoples_hobbies WHERE person_id = 5;

TL;DR;

set @sql='';
set @result='';
set @separator=' union \r\n';
SELECT 
@sql:=concat('select ''',INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME  ,''' as col_name,',
INFORMATION_SCHEMA.COLUMNS.CHARACTER_MAXIMUM_LENGTH ,' as def_len ,' ,
'MAX(CHAR_LENGTH(',INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME , '))as  max_char_len',
' FROM ',
INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
) as sql_piece, if(@result:=if(@result='',@sql,concat(@result,@separator,@sql)),'','') as dummy
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE 
INFORMATION_SCHEMA.COLUMNS.DATA_TYPE like '%char%'
and INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA='xxx' 
and INFORMATION_SCHEMA.COLUMNS.TABLE_NAME='yyy';
select @result;

'any' vs 'Object'

Object appears to be a more specific declaration than any. From the TypeScript spec (section 3):

All types in TypeScript are subtypes of a single top type called the Any type. The any keyword references this type. The Any type is the one type that can represent any JavaScript value with no constraints. All other types are categorized as primitive types, object types, or type parameters. These types introduce various static constraints on their values.

Also:

The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list.

Objects do not allow the same flexibility.

For example:

var myAny : any;

myAny.Something(); // no problemo

var myObject : Object;

myObject.Something(); // Error: The property 'Something' does not exist on value of type 'Object'.

Static methods - How to call a method from another method?

class.method should work.

class SomeClass:
  @classmethod
  def some_class_method(cls):
    pass

  @staticmethod
  def some_static_method():
    pass

SomeClass.some_class_method()
SomeClass.some_static_method()

Generate ER Diagram from existing MySQL database, created for CakePHP

Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).

This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.

Python Dictionary contains List as Value - How to update?

Probably something like this:

original_list = dictionary.get('C1')
new_list = []
for item in original_list:
  new_list.append(item+10)
dictionary['C1'] = new_list

How to convert Blob to String and String to Blob in java

And here is my solution, that always works for me

StringBuffer buf = new StringBuffer();
String temp;
BufferedReader bufReader = new BufferedReader(new InputStreamReader(myBlob.getBinaryStream()));
    while ((temp=bufReader.readLine())!=null) {
        bufappend(temp);
    }

CreateProcess error=206, The filename or extension is too long when running main() method

How many people sad above, there are a lot of plugins to gradle execute a by pass in this problem like:

plugins {
  id "ua.eshepelyuk.ManifestClasspath" version "1.0.0"
}

or

plugins {
  id "com.github.ManifestClasspath" version "0.1.0-RELEASE"
}

But the better solution that I found was kill the JVM process and everything is done.

gradient descent using python and numpy

Below you can find my implementation of gradient descent for linear regression problem.

At first, you calculate gradient like X.T * (X * w - y) / N and update your current theta with this gradient simultaneously.

  • X: feature matrix
  • y: target values
  • w: weights/values
  • N: size of training set

Here is the python code:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import random

def generateSample(N, variance=100):
    X = np.matrix(range(N)).T + 1
    Y = np.matrix([random.random() * variance + i * 10 + 900 for i in range(len(X))]).T
    return X, Y

def fitModel_gradient(x, y):
    N = len(x)
    w = np.zeros((x.shape[1], 1))
    eta = 0.0001

    maxIteration = 100000
    for i in range(maxIteration):
        error = x * w - y
        gradient = x.T * error / N
        w = w - eta * gradient
    return w

def plotModel(x, y, w):
    plt.plot(x[:,1], y, "x")
    plt.plot(x[:,1], x * w, "r-")
    plt.show()

def test(N, variance, modelFunction):
    X, Y = generateSample(N, variance)
    X = np.hstack([np.matrix(np.ones(len(X))).T, X])
    w = modelFunction(X, Y)
    plotModel(X, Y, w)


test(50, 600, fitModel_gradient)
test(50, 1000, fitModel_gradient)
test(100, 200, fitModel_gradient)

test1 test2 test2

Convert multidimensional array into single array

If you come across a multidimensional array that is pure data, like this one below, then you can use a single call to array_merge() to do the job via reflection:

$arrayMult = [ ['a','b'] , ['c', 'd'] ];
$arraySingle = call_user_func_array('array_merge', $arrayMult);
// $arraySingle is now = ['a','b', 'c', 'd'];

GET and POST methods with the same Action name in the same Controller

I like to accept a form post for my POST actions, even if I don't need it. For me it just feels like the right thing to do as you're supposedly posting something.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        //Code...
        return View();
    }

    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
        //Code...
        return View();
    }
}

Convert string (without any separator) to list

Did you try list(x)??

 y = '+123-456-7890'
 c =list(y)
 c

['+', '1', '2', '3', '-', '4', '5', '6', '-', '7', '8', '9', '0']

Use space as a delimiter with cut command

I have an answer (I admit somewhat confusing answer) that involvessed, regular expressions and capture groups:

  • \S* - first word
  • \s* - delimiter
  • (\S*) - second word - captured
  • .* - rest of the line

As a sed expression, the capture group needs to be escaped, i.e. \( and \).

The \1 returns a copy of the captured group, i.e. the second word.

$ echo "alpha beta gamma delta" | sed 's/\S*\s*\(\S*\).*/\1/'
beta

When you look at this answer, its somewhat confusing, and, you may think, why bother? Well, I'm hoping that some, may go "Aha!" and will use this pattern to solve some complex text extraction problems with a single sed expression.

Good way to encapsulate Integer.parseInt()

What behaviour do you expect when it's not a number?

If, for example, you often have a default value to use when the input is not a number, then a method such as this could be useful:

public static int parseWithDefault(String number, int defaultVal) {
  try {
    return Integer.parseInt(number);
  } catch (NumberFormatException e) {
    return defaultVal;
  }
}

Similar methods can be written for different default behaviour when the input can't be parsed.

WAMP shows error 'MSVCR100.dll' is missing when install

Re/installing .NET framework did not worked for me. Some less professional soft wares like tuneup utilities manipulate or constantly keep in use .NET framework files. like that .dll . I learned it while i was trying to uninstall .NET updates before re-installation.

  • Dont forget to uninstall wamp from control panel before reinstalling it.
  • Uninstalling .NET updates of windows. (controlPanel->uninstall a
  • program->view updates) Uninstalling soft wares that prevents
  • uninstalling .NETs . Finished successfully uninstalling .NET
  • framework updates. Check windows updates. Install updates that shows up AFTER check (.NET framework update. 3update for me under win7x64)
  • install wamp (finished flawlessly for me)

Append value to empty vector in R?

Appending to an object in a for loop causes the entire object to be copied on every iteration, which causes a lot of people to say "R is slow", or "R loops should be avoided".

As BrodieG mentioned in the comments: it is much better to pre-allocate a vector of the desired length, then set the element values in the loop.

Here are several ways to append values to a vector. All of them are discouraged.

Appending to a vector in a loop

# one way
for (i in 1:length(values))
  vector[i] <- values[i]
# another way
for (i in 1:length(values))
  vector <- c(vector, values[i])
# yet another way?!?
for (v in values)
  vector <- c(vector, v)
# ... more ways

help("append") would have answered your question and saved the time it took you to write this question (but would have caused you to develop bad habits). ;-)

Note that vector <- c() isn't an empty vector; it's NULL. If you want an empty character vector, use vector <- character().

Pre-allocate the vector before looping

If you absolutely must use a for loop, you should pre-allocate the entire vector before the loop. This will be much faster than appending for larger vectors.

set.seed(21)
values <- sample(letters, 1e4, TRUE)
vector <- character(0)
# slow
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.340   0.000   0.343 
vector <- character(length(values))
# fast(er)
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.024   0.000   0.023 

Django URL Redirect

Another way of doing it is using HttpResponsePermanentRedirect like so:

In view.py

def url_redirect(request):
    return HttpResponsePermanentRedirect("/new_url/")

In the url.py

url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"),

React hooks useState Array

use state is not always needed you can just simply do this

let paymentList = [
    {"id":249,"txnid":"2","fname":"Rigoberto"}, {"id":249,"txnid":"33","fname":"manuel"},]

then use your data in a map loop like this in my case it was just a table and im sure many of you are looking for the same. here is how you use it.

<div className="card-body">
            <div className="table-responsive">
                <table className="table table-striped">
                    <thead>
                        <tr>
                            <th>Transaction ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            paymentList.map((payment, key) => (
                                <tr key={key}>
                                    <td>{payment.txnid}</td>
                                    <td>{payment.fname}</td>
                                </tr>
                            ))
                        }
                    </tbody>
                </table>
            </div>
        </div>

Can we set a Git default to fetch all tags during a remote pull?

I use this with magit on kernel.org

[remote "upstream"]
    url = <redacted>
    fetch = +refs/heads/*:refs/remotes/upstream/*
    tagOpt = --tags

Toad for Oracle..How to execute multiple statements?

If you have Multiple Insert Statements then Toad has a simple Way to execute all the Insert Statements.

Right Click On the Highlighted Insert Statements --> Select Execute Menu --> Execute Script

This will automatically start running the Insert Statements

Does calling clone() on an array also clone its contents?

clone() creates a shallow copy. Which means the elements will not be cloned. (What if they didn't implement Cloneable?)

You may want to use Arrays.copyOf(..) for copying arrays instead of clone() (though cloning is fine for arrays, unlike for anything else)

If you want deep cloning, check this answer


A little example to illustrate the shallowness of clone() even if the elements are Cloneable:

ArrayList[] array = new ArrayList[] {new ArrayList(), new ArrayList()};
ArrayList[] clone = array.clone();
for (int i = 0; i < clone.length; i ++) {
    System.out.println(System.identityHashCode(array[i]));
    System.out.println(System.identityHashCode(clone[i]));
    System.out.println(System.identityHashCode(array[i].clone()));
    System.out.println("-----");
}

Prints:

4384790  
4384790
9634993  
-----  
1641745  
1641745  
11077203  
-----  

How to make a DIV not wrap?

you can use

display: table;

for your container and therfore avoid the overflow: hidden;. It should do the job if you used it just for warpping purpose.

Firefox 'Cross-Origin Request Blocked' despite headers

Ubuntu Firefox giving CORS failed error when my request took more than 10 seconds to process.

Nothing to do with CORS. Problem is with ubuntu firefox configuration.

I have updated network.notify.changed to false which made this fix.


Mozilla Bugs Reference:

https://bugzilla.mozilla.org/show_bug.cgi?id=1238377

https://bugzilla.mozilla.org/show_bug.cgi?id=1235509

font size in html code

just write the css attributes in a proper manner i.e:

font-size:35px;

How can I add a PHP page to WordPress?

If you wanted to create your own .php file and interact with WordPress without 404 headers and keeping your current permalink structure there is no need for a template file for that one page.

I found that this approach works best, in your .php file:

<?php
    require_once(dirname(__FILE__) . '/wp-config.php');
    $wp->init();
    $wp->parse_request();
    $wp->query_posts();
    $wp->register_globals();
    $wp->send_headers();

    // Your WordPress functions here...
    echo site_url();
?>

Then you can simply perform any WordPress functions after this. Also, this assumes that your .php file is within the root of your WordPress site where your wp-config.php file is located.

This, to me, is a priceless discovery as I was using require_once(dirname(__FILE__) . '/wp-blog-header.php'); for the longest time as WordPress even tells you that this is the approach that you should use to integrate WordPress functions, except, it causes 404 headers, which is weird that they would want you to use this approach. Integrating WordPress with Your Website

I know many people have answered this question, and it already has an accepted answer, but here is a nice approach for a .php file within the root of your WordPress site (or technically anywhere you want in your site), that you can browse to and load without 404 headers!


Update: There is a way to use wp-blog-header.php without 404 headers, but this requires that you add in the headers manually. Something like this will work in the root of your WordPress installation:

<?php
    require_once(dirname(__FILE__) . '/wp-blog-header.php');
    header("HTTP/1.1 200 OK");
    header("Status: 200 All rosy");

    // Your WordPress functions here...
    echo site_url();
?>

Just to update you all on this, a little less code needed for this approach, but it's up to you on which one you use.

Change Image of ImageView programmatically in Android

qImageView.setImageResource(R.drawable.img2);

I think this will help you