Programs & Examples On #Intermittent

Tags problems that aren't simply reproducable because they don't always occur.

Intellij Cannot resolve symbol on import

I had a similar issue with my imported Maven project. In one module, it cannot resolve symbol on import for part of the other module (yes, part of that module can be resolved).

I changed "Maven home directory" to a newer version solved my issue.

Update: Good for 1 hour, back to broken status...

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

See my post here

How are you? I had the same problem while i was trying connect to MSSQL Server remotely using jdbc (dbeaver on debian).

After a while, i found out that my firewall configuration was not correctly. So maybe it could help you!

Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.

Four exceptions must be configured in Windows Firewall to allow access to SQL Server:

A port exception for TCP Port 1433. In the New Inbound Rule Wizard dialog, use the following information to create a port exception: Select Port Select TCP and specify port 1433 Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule “SQL – TCP 1433" A port exception for UDP Port 1434. Click New Rule again and use the following information to create another port exception: Select Port Select UDP and specify port 1434 Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule “SQL – UDP 1434 A program exception for sqlservr.exe. Click New Rule again and use the following information to create a program exception: Select Program Click Browse to select ‘sqlservr.exe’ at this location: [C:\Program Files\Microsoft SQL Server\MSSQL11.\MSSQL\Binn\sqlservr.exe] where is the name of your SQL instance. Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule SQL – sqlservr.exe A program exception for sqlbrowser.exe Click New Rule again and use the following information to create another program exception: Select Program Click Browse to select sqlbrowser.exe at this location: [C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe]. Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule SQL - sqlbrowser.exe

Source: http://blog.citrix24.com/configure-sql-express-to-accept-remote-connections/

how to get curl to output only http response body (json) and no other headers etc

You are specifying the -i option:

-i, --include

(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...

Simply remove that option from your command line:

response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I'm familiar with this problem. The simplest workaround is to conditionally repeat the operation. I've never seen it fail twice in a row - unless there actually is an open file or a permissions issue, obviously!

rd /s /q c:\deleteme
if exist c:\deleteme rd /s /q c:\deleteme

how to resolve DTS_E_OLEDBERROR. in ssis

I faced the similar issue.

Deselect the check box ("In wizard deselect the checkbox stating "First row has columns names") and before running the wizard make sure you have opened your excel sheet.

Then run the wizard by deselecting the checkbox.

This resolved my issue.

What does a Status of "Suspended" and high DiskIO means from sp_who2?

This is a very broad question, so I am going to give a broad answer.

  1. A query gets suspended when it is requesting access to a resource that is currently not available. This can be a logical resource like a locked row or a physical resource like a memory data page. The query starts running again, once the resource becomes available. 
  2. High disk IO means that a lot of data pages need to be accessed to fulfill the request.

That is all that I can tell from the above screenshot. However, if I were to speculate, you probably have an IO subsystem that is too slow to keep up with the demand. This could be caused by missing indexes or an actually too slow disk. Keep in mind, that 15000 reads for a single OLTP query is slightly high but not uncommon.

java.net.SocketTimeoutException: Read timed out under Tomcat

Connection.Response resp = Jsoup.connect(url) //
                .timeout(20000) //
                .method(Connection.Method.GET) //
                .execute();

actually, the error occurs when you have slow internet so try to maximize the timeout time and then your code will definitely work as it works for me.

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

I had this error for some time and found a fix. This fix is for Asp.net application, Strange it failed only in IE non compatibility mode, but works in Firefox and Crome. Giving access to the webservice service folder for all/specific users solved the issue.

Add the following code in web.config file:

 <location path="YourWebserviceFolder">
  <system.web>
   <authorization>
    <allow users="*"/>
   </authorization>
  </system.web>
 </location>

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

How to Troubleshoot Intermittent SQL Timeout Errors

We experienced this with SQL Server 2012 / SP3, when running a query via an SqlCommand object from within a C# application. The Command was a simple invocation of a stored procedure having one table parameter; we were passing a list of about 300 integers. The procedure in turn called three user-defined functions and passed the table as a parameter to each of them. The CommandTimeout was set to 90 seconds.

When running precisely the same stored proc with the same argument from within SQL Server Management Studio, the query ran in 15 seconds. But when running it from our application using the above setup, the SqlCommand timed out. The same SqlCommand (with different but comparable data) had been running successfully for weeks, but now it failed with any table argument containing more than 20 or so integers. We did a trace and discovered that when run from the SqlCommand object, the database spent the entire 90 seconds acquiring locks, and would invoke the procedure only at about the moment of the timeout. We changed the CommandTimeout time, and no matter time what we selected the stored proc would be invoked only at the very end of that period. So we surmise that SQL Server was indefinitely acquiring the same locks over and over, and that only the timeout of the Command object caused SQL Server to stop its infinite loop and begin executing the query, by which time it was too late to succeed. A simulation of this same process on a similar server using similar data exhibited no such problem. Our solution was to reboot the entire database server, after which the problem disappeared.

So it appears that there is some problem in SQL Server wherein some resource gets cumulatively consumed and never released. Eventually when connecting via an SqlConnection and running an SqlCommand involving a table parameter, SQL Server goes into an infinite loop acquiring locks. The loop is terminated by the timeout of the SqlCommand object. The solution is to reboot, apparently restoring (temporary?) sanity to SQL Server.

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

I have encountered this error while updating records from table which has trigger enabled. For example - I have trigger 'Trigger1' on table 'Table1'. When I tried to update the 'Table1' using the update query - it throws the same error. THis is because if you are updating more than 1 record in your query, then 'Trigger1' will throw this error as it doesn't support updating multiple entries if it is enabled on same table. I tried disabling trigger before update and then performed update operation and it was completed without any error.

DISABLE TRIGGER Trigger1 ON Table1;
Update query --------
Enable TRIGGER Trigger1 ON Table1;

Untrack files from git temporarily

I am assuming that you are asking how to remove ALL the files in the build folder or the bin folder, Rather than selecting each files separately.

You can use this command:

git rm -r -f /build\*

Make sure that you are in the parent directory of the build directory.
This command will, recursively "delete" all the files which are in the bin/ or build/ folders. By the word delete I mean that git will pretend that those files are "deleted" and those files will not be tracked. The git really marks those files to be in delete mode.

Do make sure that you have your .gitignore ready for upcoming commits.
Documentation : git rm

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

All error codes are on "CFNetwork Errors Codes References" on the documentation (link)

A small extraction for CFURL and CFURLConnection Errors:

  kCFURLErrorUnknown   = -998,
  kCFURLErrorCancelled = -999,
  kCFURLErrorBadURL    = -1000,
  kCFURLErrorTimedOut  = -1001,
  kCFURLErrorUnsupportedURL = -1002,
  kCFURLErrorCannotFindHost = -1003,
  kCFURLErrorCannotConnectToHost    = -1004,
  kCFURLErrorNetworkConnectionLost  = -1005,
  kCFURLErrorDNSLookupFailed        = -1006,
  kCFURLErrorHTTPTooManyRedirects   = -1007,
  kCFURLErrorResourceUnavailable    = -1008,
  kCFURLErrorNotConnectedToInternet = -1009,
  kCFURLErrorRedirectToNonExistentLocation = -1010,
  kCFURLErrorBadServerResponse             = -1011,
  kCFURLErrorUserCancelledAuthentication   = -1012,
  kCFURLErrorUserAuthenticationRequired    = -1013,
  kCFURLErrorZeroByteResource        = -1014,
  kCFURLErrorCannotDecodeRawData     = -1015,
  kCFURLErrorCannotDecodeContentData = -1016,
  kCFURLErrorCannotParseResponse     = -1017,
  kCFURLErrorInternationalRoamingOff = -1018,
  kCFURLErrorCallIsActive               = -1019,
  kCFURLErrorDataNotAllowed             = -1020,
  kCFURLErrorRequestBodyStreamExhausted = -1021,
  kCFURLErrorFileDoesNotExist           = -1100,
  kCFURLErrorFileIsDirectory            = -1101,
  kCFURLErrorNoPermissionsToReadFile    = -1102,
  kCFURLErrorDataLengthExceedsMaximum   = -1103,

Entity Framework: There is already an open DataReader associated with this Command

You get this error, when the collection you are trying to iterate is kind of lazy loading (IQueriable).

foreach (var user in _dbContext.Users)
{    
}

Converting the IQueriable collection into other enumerable collection will solve this problem. example

_dbContext.Users.ToList()

Note: .ToList() creates a new set every-time and it can cause the performance issue if you are dealing with large data.

A transport-level error has occurred when receiving results from the server

If you are connected to your database via Microsoft SQL Server Management, close all your connections and retry. Had this error when connected to another Azure Database, and worked for me when closed it. Still don't know why ..

I/O error(socket error): [Errno 111] Connection refused

Use a packet sniffer like Wireshark to look at what happens. You need to see a SYN-flagged packet outgoing, a SYN+ACK-flagged incoming and then a ACK-flagged outgoing. After that, the port is considered open on the local side.

If you only see the first packet and the error message comes after several seconds of waiting, the other side is not answering at all (like in: unplugged cable, overloaded server, misguided packet was discarded) and your local network stack aborts the connection attempt. If you see RST packets, the host actually denies the connection. If you see "ICMP Port unreachable" or host unreachable packets, a firewall or the target host inform you of the port actually being closed.

Of course you cannot expect the service to be available at all times (consider all the points of failure in between you and the data), so you should try again later.

Oracle JDBC intermittent Connection Issue

There is a solution provided to this problem in some of the OTN forums (https://kr.forums.oracle.com/forums/thread.jspa?messageID=3699989). But, the root cause of the problem is not explained. Following is my attempt to explain the root cause of the problem.

The Oracle JDBC drivers communicate with the Oracle server in a secure way. The drivers use the java.security.SecureRandom class to gather entropy for securing the communication. This class relies on the native platform support for gathering the entropy.

Entropy is the randomness collected/generated by an operating system or application for use in cryptography or other uses that require random data. This randomness is often collected from hardware sources, either from the hardware noises, audio data, mouse movements or specially provided randomness generators. The kernel gathers the entropy and stores it is an entropy pool and makes the random character data available to the operating system processes or applications through the special files /dev/random and /dev/urandom.

Reading from /dev/random drains the entropy pool with requested amount of bits/bytes, providing a high degree of randomness often desired in cryptographic operations. In case, if the entropy pool is completely drained and sufficient entropy is not available, the read operation on /dev/random blocks until additional entropy is gathered. Due to this, applications reading from /dev/random may block for some random period of time.

In contrast to the above, reading from the /dev/urandom does not block. Reading from /dev/urandom, too, drains the entropy pool but when short of sufficient entropy, it does not block but reuses the bits from the partially read random data. This is said to be susceptible to cryptanalytical attacks. This is a theorotical possibility and hence it is discouraged to read from /dev/urandom to gather randomness in cryptographic operations.

The java.security.SecureRandom class, by default, reads from the /dev/random file and hence sometimes blocks for random period of time. Now, if the read operation does not return for a required amount of time, the Oracle server times out the client (the jdbc drivers, in this case) and drops the communication by closing the socket from its end. The client when tries to resume the communication after returning from the blocking call encounters the IO exception. This problem may occur randomly on any platform, especially, where the entropy is gathered from hardware noises.

As suggested in the OTN forum, the solution to this problem is to override the default behaviour of java.security.SecureRandom class to use the non-blocking read from /dev/urandom instead of the blocking read from /dev/random. This can be done by adding the following system property -Djava.security.egd=file:///dev/urandom to the JVM. Though this is a good solution for the applications like the JDBC drivers, it is discouraged for applications that perform core cryptographic operations like crytographic key generation.

Other solutions could be to use different random seeder implementations available for the platform that do not rely on hardware noises for gathering entropy. With this, you may still require to override the default behaviour of java.security.SecureRandom.

Increasing the socket timeout on the Oracle server side can also be a solution but the side effects should be assessed from the server point of view before attempting this.

Closing database connections in Java

It is enough to close just Statement and Connection. There is no need to explicitly close the ResultSet object.

Java documentation says about java.sql.ResultSet:

A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.


Thanks BalusC for comments: "I wouldn't rely on that. Some JDBC drivers fail on that."

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

Every service that is bound in activity must be unbind on app close.

So try using

 onPause(){
   unbindService(YOUR_SERVICE);
   super.onPause();
 }

Android WebView Cookie Problem

I would save that session cookie as a preference and forcefully repopulate the cookie manager with it. It sounds that session cookie in not surviving Activity restart

Using JQuery hover with HTML image map

I found this wonderful mapping script (mapper.js) that I have used in the past. What's different about it is you can hover over the map or a link on your page to make the map area highlight. Sadly it's written in javascript and requires a lot of in-line coding in the HTML - I would love to see this script ported over to jQuery :P

Also, check out all the demos! I think this example could almost be made into a simple online game (without using flash) - make sure you click on the different camera angles.

What's causing my java.net.SocketException: Connection reset?

The javadoc for SocketException states that it is

Thrown to indicate that there is an error in the underlying protocol such as a TCP error

In your case it seems that the connection has been closed by the server end of the connection. This could be an issue with the request you are sending or an issue at their end.

To aid debugging you could look at using a tool such as Wireshark to view the actual network packets. Also, is there an alternative client to your Java code that you could use to test the web service? If this was successful it could indicate a bug in the Java code.

As you are using Commons HTTP Client have a look at the Common HTTP Client Logging Guide. This will tell you how to log the request at the HTTP level.

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Don't know if this will be everybody's answer, but after some digging, here's what we came up with.

The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent

After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).

The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.

So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.

plot a circle with pyplot

#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np

def xy(r,phi):
  return r*np.cos(phi), r*np.sin(phi)

fig = plt.figure()
ax = fig.add_subplot(111,aspect='equal')  

phis=np.arange(0,6.28,0.01)
r =1.
ax.plot( *xy(r,phis), c='r',ls='-' )
plt.show()

Or, if you prefer, look at the paths, http://matplotlib.sourceforge.net/users/path_tutorial.html

Java, Calculate the number of days between two dates

try this code

     Calendar cal1 = new GregorianCalendar();
     Calendar cal2 = new GregorianCalendar();

     SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");

     Date date = sdf.parse("your first date");
     cal1.setTime(date)
     date = sdf.parse("your second date");
     cal2.setTime(date);

    //cal1.set(2008, 8, 1); 
     //cal2.set(2008, 9, 31);
     System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));

this function

     public int daysBetween(Date d1, Date d2){
             return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
     }

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

How to use support FileProvider for sharing content to other apps?

In my app FileProvider works just fine, and I am able to attach internal files stored in files directory to email clients like Gmail,Yahoo etc.

In my manifest as mentioned in the Android documentation I placed:

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.package.name.fileprovider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
    </provider>

And as my files were stored in the root files directory, the filepaths.xml were as follows:

 <paths>
<files-path path="." name="name" />

Now in the code:

 File file=new File(context.getFilesDir(),"test.txt");

 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);

 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                                     "Test");

 shareIntent.setType("text/plain");

 shareIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                                 new String[] {"email-address you want to send the file to"});

   Uri uri = FileProvider.getUriForFile(context,"com.package.name.fileprovider",
                                                   file);

                ArrayList<Uri> uris = new ArrayList<Uri>();
                uris.add(uri);

                shareIntent .putParcelableArrayListExtra(Intent.EXTRA_STREAM,
                                                        uris);


                try {
                   context.startActivity(Intent.createChooser(shareIntent , "Email:").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));                                                      


                }
                catch(ActivityNotFoundException e) {
                    Toast.makeText(context,
                                   "Sorry No email Application was found",
                                   Toast.LENGTH_SHORT).show();
                }
            }

This worked for me.Hope this helps :)

How to list the files inside a JAR file?

public static ArrayList<String> listItems(String path) throws Exception{
    InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(path);
    byte[] b = new byte[in.available()];
    in.read(b);
    String data = new String(b);
    String[] s = data.split("\n");
    List<String> a = Arrays.asList(s);
    ArrayList<String> m = new ArrayList<>(a);
    return m;
}

Constructor overloading in Java - best practice

Constructor overloading is like method overloading. Constructors can be overloaded to create objects in different ways.

The compiler differentiates constructors based on how many arguments are present in the constructor and other parameters like the order in which the arguments are passed.

For further details about java constructor, please visit https://tecloger.com/constructor-in-java/

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Bootstrap 3 collapsed menu doesn't close on click

Change this:

<li><a href="#one">One</a></li>

to this:

<li><a data-toggle="collapse" data-target=".navbar-collapse" href="#one">One</a></li>  

This simple change worked for me.

Ref: https://github.com/twbs/bootstrap/issues/9013

How do I get the base URL with PHP?

This is the best method i think so.

$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http");
$base_url .= "://".$_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

echo $base_url;

Replace invalid values with None in Pandas DataFrame

where is probably what you're looking for. So

data=data.where(data=='-', None) 

From the panda docs:

where [returns] an object of same shape as self and whose corresponding entries are from self where cond is True and otherwise are from other).

fcntl substitute on Windows

The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip.

In other words, porting a fcntl-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any.

There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.

If you provide more details about the fcntl calls people can find windows equivalents.

How to run a maven created jar file using just the command line

Just use the exec-maven-plugin.

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <mainClass>com.example.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Then you run you program:

mvn exec:java

Cleanest way to write retry logic?

Keep it simple with C# 6.0

public async Task<T> Retry<T>(Func<T> action, TimeSpan retryInterval, int retryCount)
{
    try
    {
        return action();
    }
    catch when (retryCount != 0)
    {
        await Task.Delay(retryInterval);
        return await Retry(action, retryInterval, --retryCount);
    }
}

Get public/external IP address?

Most of the answers have mentioned http://checkip.dyndns.org in solution. For us, it didn't worked out well. We have faced Timemouts a lot of time. Its really troubling if your program is dependent on the IP detection.

As a solution, we use the following method in one of our desktop applications:

    // Returns external/public ip
    protected string GetExternalIP()
    {
        try
        {
            using (MyWebClient client = new MyWebClient())
            {
                client.Headers["User-Agent"] =
                "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
                "(compatible; MSIE 6.0; Windows NT 5.1; " +
                ".NET CLR 1.1.4322; .NET CLR 2.0.50727)";

                try
                {
                    byte[] arr = client.DownloadData("http://checkip.amazonaws.com/");

                    string response = System.Text.Encoding.UTF8.GetString(arr);

                    return response.Trim();
                }
                catch (WebException ex)
                {
                    // Reproduce timeout: http://checkip.amazonaws.com:81/

                    // trying with another site
                    try
                    {
                        byte[] arr = client.DownloadData("http://icanhazip.com/");

                        string response = System.Text.Encoding.UTF8.GetString(arr);

                        return response.Trim();
                    }
                    catch (WebException exc)
                    { return "Undefined"; }
                }
            }
        }
        catch (Exception ex)
        {
            // TODO: Log trace
            return "Undefined";
        }
    }

Good part is, both sites return IP in plain format. So string operations are avoided.

To check your logic in catch clause, you can reproduce Timeout by hitting a non available port. eg: http://checkip.amazonaws.com:81/

Laravel: Get base url

To just get the app url, that you configured you can use :

Config::get('app.url')

syntax error when using command line in python

Running from the command line means running from the terminal or DOS shell. You are running it from Python itself.

Replace single quotes in SQL Server

Besides needing to escape the quote (by using double quotes), you've also confused the names of variables: You're using @var and @strip, instead of @CleanString and @strStrip...

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

Use mysql_fetch_array() with foreach() instead of while()

the most obvious way to make foreach a possibility includes materializing the whole resultset in an array, which will probably kill you memory-wise, sooner or later. you'd need to turn to iterators to avoid that problem. see http://www.php.net/~helly/php/ext/spl/

how to get the 30 days before date from Todays Date

In MS SQL Server, it is:

SELECT getdate() - 30;

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

A slightly more efficient version of the bytes2String method is

private static final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static String byteArray2Hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

How to make a transparent border using CSS?

use rgba (rgb with alpha transparency):

border: 10px solid rgba(0,0,0,0.5); // 0.5 means 50% of opacity

The alpha transparency variate between 0 (0% opacity = 100% transparent) and 1 (100 opacity = 0% transparent)

anaconda/conda - install a specific package version

To install a specific package:

conda install <pkg>=<version>

eg:

conda install matplotlib=1.4.3

Regular expression to match standard 10 digit phone number

try this for Pakistani users .Here's a fairly compact one I created.

((\+92)|0)[.\- ]?[0-9][.\- ]?[0-9][.\- ]?[0-9]

Tested against the following use cases.

+92 -345 -123 -4567
+92 333 123 4567
+92 300 123 4567
+92 321 123 -4567
+92 345 - 540 - 5883

MySQL trigger if condition exists

I think you mean to update it back to the OLD password, when the NEW one is not supplied.

DROP TRIGGER IF EXISTS upd_user;

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '') THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

However, this means a user can never blank out a password.


If the password field (already encrypted) is being sent back in the update to mySQL, then it will not be null or blank, and MySQL will attempt to redo the Password() function on it. To detect this, use this code instead

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

Note:

  1. Its not necessary to specify table name in Person.hbm.xml (........) when you are creating table with same as class name. Also applicable to fields.

  2. While creating "person" table in your respective database,make sure that whatever FILEDS names you specified in Person.hbm.xml must match with table COLUMNS names ELSE you wil get above error.

Rails 3.1 and Image Assets

You'll want to change the extension of your css file from .css.scss to .css.scss.erb and do:

background-image:url(<%=asset_path "admin/logo.png"%>);

You may need to do a "hard refresh" to see changes. CMD+SHIFT+R on OSX browsers.

In production, make sure

rm -rf public/assets    
bundle exec rake assets:precompile RAILS_ENV=production

happens upon deployment.

Assign a login to a user created without login (SQL Server)

You have an orphaned user and this can't be remapped with ALTER USER (yet) becauses there is no login to map to. So, you need run CREATE LOGIN first.

If the database level user is

  • a Windows Login, the mapping will be fixed automatcially via the AD SID
  • a SQL Login, use "sid" from sys.database_principals for the SID option for the login

Then run ALTER USER

Edit, after comments and updates

The sid from sys.database_principals is for a Windows login.

So trying to create and re-map to a SQL Login will fail

Run this to get the Windows login

SELECT SUSER_SNAME(0x0105000000000009030000001139F53436663A4CA5B9D5D067A02390)

Android: How to add R.raw to project?

The R class is written when you build the project in gradle. You should add the raw folder, then build the project. After that, the R class will be able to identify R.raw.*.

Can you issue pull requests from the command line on GitHub?

I ended up making my own, I find that it works better the other solutions that were around.

https://npmjs.org/package/pullr

File Explorer in Android Studio

It is very Simple brother Click on the Android Device monitor(ADM) just below the Help menu then the on ADM select your file explorer from left screen menu or for more details go here It may Help U thanx

CRON job to run on the last day of the month

Set up a cron job to run on the first day of the month. Then change the system's clock to be one day ahead.

How to enable multidexing with the new Android Multidex support library

Edit:

Android 5.0 (API level 21) and higher uses ART which supports multidexing. Therefore, if your minSdkVersion is 21 or higher, the multidex support library is not needed.


Modify your build.gradle:

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0"

         defaultConfig {
             minSdkVersion 14 //lower than 14 doesn't support multidex
             targetSdkVersion 22

             // Enabling multidex support.
             multiDexEnabled true
         }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
}

If you are running unit tests, you will want to include this in your Application class:

public class YouApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

}

Or just make your application class extend MultiDexApplication

public class Application extends MultiDexApplication {

}

For more info, this is a good guide.

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

This error you are receiving :

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

is because the number of elements in $values & $matches is not the same or $matches contains more than 1 element.

If $matches contains more than 1 element, than the insert will fail, because there is only 1 column name referenced in the query(hash)

If $values & $matches do not contain the same number of elements then the insert will also fail, due to the query expecting x params but it is receiving y data $matches.

I believe you will also need to ensure the column hash has a unique index on it as well.

Try the code here:

<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }


$matches = array('1');
$count = count($matches);
for($i = 0; $i < $count; ++$i) {
    $values[] = '?';
}

// INSERT INTO DATABASE
$sql = "INSERT INTO hashes (hash) VALUES (" . implode(', ', $values) . ") ON DUPLICATE KEY UPDATE hash='hash'";
$stmt = $dbh->prepare($sql);
$data = $stmt->execute($matches);

//Error reporting if something went wrong...
var_dump($dbh->errorInfo());

?>

You will need to adapt it a little.

Table structure I used is here:

CREATE TABLE IF NOT EXISTS `hashes` (
  `hashid` int(11) NOT NULL AUTO_INCREMENT,
  `hash` varchar(250) NOT NULL,
  PRIMARY KEY (`hashid`),
  UNIQUE KEY `hash1` (`hash`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Code was run on my XAMPP Server which is using PHP 5.3.8 with MySQL 5.5.16.

I hope this helps.

Difference between virtual and abstract methods

Abstract Method:

  • If an abstract method is defined in a class, then the class should declare as an abstract class.

  • An abstract method should contain only method definition, should not Contain the method body/implementation.

  • An abstract method must be over ride in the derived class.

Virtual Method:

  • Virtual methods can be over ride in the derived class but not mandatory.
  • Virtual methods must have the method body/implementation along with the definition.

Example:

public abstract class baseclass
        {
            public abstract decimal getarea(decimal Radius);

            public virtual decimal interestpermonth(decimal amount)
            {
                return amount*12/100;
            }

            public virtual decimal totalamount(decimal Amount,decimal principleAmount)
            {
                return Amount + principleAmount;
            }
        }

        public class derivedclass:baseclass
        {
            public override decimal getarea(decimal Radius)
            {
                return 2 * (22 / 7) * Radius;
            }

            public override decimal interestpermonth(decimal amount)
            {
                return amount * 14 / 100;
            }
        }

AES Encryption for an NSString on the iPhone

I waited a bit on @QuinnTaylor to update his answer, but since he didn't, here's the answer a bit more clearly and in a way that it will load on XCode7 (and perhaps greater). I used this in a Cocoa application, but it likely will work okay with an iOS application as well. Has no ARC errors.

Paste before any @implementation section in your AppDelegate.m or AppDelegate.mm file.

#import <CommonCrypto/CommonCryptor.h>

@implementation NSData (AES256)

- (NSData *)AES256EncryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or 
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                     keyPtr, kCCKeySizeAES256,
                                     NULL /* initialization vector (optional) */,
                                     [self bytes], dataLength, /* input */
                                     buffer, bufferSize, /* output */
                                     &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}

- (NSData *)AES256DecryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or 
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                     keyPtr, kCCKeySizeAES256,
                                     NULL /* initialization vector (optional) */,
                                     [self bytes], dataLength, /* input */
                                     buffer, bufferSize, /* output */
                                     &numBytesDecrypted);

    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}

@end

Paste these two functions in the @implementation class you desire. In my case, I chose @implementation AppDelegate in my AppDelegate.mm or AppDelegate.m file.

- (NSString *) encryptString:(NSString*)plaintext withKey:(NSString*)key {
    NSData *data = [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
    return [data base64EncodedStringWithOptions:kNilOptions];
}

- (NSString *) decryptString:(NSString *)ciphertext withKey:(NSString*)key {
    NSData *data = [[NSData alloc] initWithBase64EncodedString:ciphertext options:kNilOptions];
    return [[NSString alloc] initWithData:[data AES256DecryptWithKey:key] encoding:NSUTF8StringEncoding];
}

How can I reference a commit in an issue comment on GitHub?

Answer above is missing an example which might not be obvious (it wasn't to me).

Url could be broken down into parts

https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
                  \_____/\________/       \_______________________________________/
                   |        |                              |
            Account name    |                      Hash of revision
                        Project name              

Hash can be found here (you can click it and will get the url from browser).

enter image description here

Hope this saves you some time.

Use :hover to modify the css of another class?

You can do it by making the following CSS. you can put here the css you need to affect child class in case of hover on the root

_x000D_
_x000D_
.root:hover    .child {_x000D_
   _x000D_
}
_x000D_
_x000D_
_x000D_

Postgres: INSERT if does not exist already

How can I write an 'INSERT unless this row already exists' SQL statement?

There is a nice way of doing conditional INSERT in PostgreSQL:

INSERT INTO example_table
    (id, name)
SELECT 1, 'John'
WHERE
    NOT EXISTS (
        SELECT id FROM example_table WHERE id = 1
    );

CAVEAT This approach is not 100% reliable for concurrent write operations, though. There is a very tiny race condition between the SELECT in the NOT EXISTS anti-semi-join and the INSERT itself. It can fail under such conditions.

How to sort a List of objects by their date (java collections, List<Object>)

You can use this:

Collections.sort(list, org.joda.time.DateTimeComparator.getInstance());

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

If you are using CentOS linux system the Maven local repositary will be:

/root/.m2/repository/

You can remove .m2 and build your maven project in dev tool will fix the issue.

How to pause a vbscript execution?

With 'Enter' is better use ReadLine() or Read(2), because key 'Enter' generate 2 symbols. If user enter any text next Pause() also wil be skipped even with Read(2). So ReadLine() is better:

Sub Pause()
    WScript.Echo ("Press Enter to continue")
    z = WScript.StdIn.ReadLine()
End Sub

More examples look in http://technet.microsoft.com/en-us/library/ee156589.aspx

How to easily initialize a list of Tuples?

C# 6 adds a new feature just for this: extension Add methods. This has always been possible for VB.net but is now available in C#.

Now you don't have to add Add() methods to your classes directly, you can implement them as extension methods. When extending any enumerable type with an Add() method, you'll be able to use it in collection initializer expressions. So you don't have to derive from lists explicitly anymore (as mentioned in another answer), you can simply extend it.

public static class TupleListExtensions
{
    public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
            T1 item1, T2 item2)
    {
        list.Add(Tuple.Create(item1, item2));
    }

    public static void Add<T1, T2, T3>(this IList<Tuple<T1, T2, T3>> list,
            T1 item1, T2 item2, T3 item3)
    {
        list.Add(Tuple.Create(item1, item2, item3));
    }

    // and so on...
}

This will allow you to do this on any class that implements IList<>:

var numbers = new List<Tuple<int, string>>
{
    { 1, "one" },
    { 2, "two" },
    { 3, "three" },
    { 4, "four" },
    { 5, "five" },
};
var points = new ObservableCollection<Tuple<double, double, double>>
{
    { 0, 0, 0 },
    { 1, 2, 3 },
    { -4, -2, 42 },
};

Of course you're not restricted to extending collections of tuples, it can be for collections of any specific type you want the special syntax for.

public static class BigIntegerListExtensions
{
    public static void Add(this IList<BigInteger> list,
        params byte[] value)
    {
        list.Add(new BigInteger(value));
    }

    public static void Add(this IList<BigInteger> list,
        string value)
    {
        list.Add(BigInteger.Parse(value));
    }
}

var bigNumbers = new List<BigInteger>
{
    new BigInteger(1), // constructor BigInteger(int)
    2222222222L,       // implicit operator BigInteger(long)
    3333333333UL,      // implicit operator BigInteger(ulong)
    { 4, 4, 4, 4, 4, 4, 4, 4 },               // extension Add(byte[])
    "55555555555555555555555555555555555555", // extension Add(string)
};

C# 7 will be adding in support for tuples built into the language, though they will be of a different type (System.ValueTuple instead). So to it would be good to add overloads for value tuples so you have the option to use them as well. Unfortunately, there are no implicit conversions defined between the two.

public static class ValueTupleListExtensions
{
    public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
        ValueTuple<T1, T2> item) => list.Add(item.ToTuple());
}

This way the list initialization will look even nicer.

var points = new List<Tuple<int, int, int>>
{
    (0, 0, 0),
    (1, 2, 3),
    (-1, 12, -73),
};

But instead of going through all this trouble, it might just be better to switch to using ValueTuple exclusively.

var points = new List<(int, int, int)>
{
    (0, 0, 0),
    (1, 2, 3),
    (-1, 12, -73),
};

Stop executing further code in Java

return to come out of the method execution, break to come out of a loop execution and continue to skip the rest of the current loop. In your case, just return, but if you are in a for loop, for example, do break to stop the loop or continue to skip to next step in the loop

How to make a new List in Java

//simple example creating a list form a string array

String[] myStrings = new String[] {"Elem1","Elem2","Elem3","Elem4","Elem5"};

List mylist = Arrays.asList(myStrings );

//getting an iterator object to browse list items

Iterator itr= mylist.iterator();

System.out.println("Displaying List Elements,");

while(itr.hasNext())

  System.out.println(itr.next());

What does [object Object] mean? (JavaScript)

The alert() function can't output an object in a read-friendly manner. Try using console.log(object) instead, and fire up your browser's console to debug.

Nested ng-repeat

It's better to have a proper JSON format instead of directly using the one converted from XML.

[
  {
    "number": "2013-W45",
    "days": [
      {
        "dow": "1",
        "templateDay": "Monday",
        "jobs": [
          {
            "name": "Wakeup",
            "jobs": [
              {
                "name": "prepare breakfast",

              }
            ]
          },
          {
            "name": "work 9-5",

          }
        ]
      },
      {
        "dow": "2",
        "templateDay": "Tuesday",
        "jobs": [
          {
            "name": "Wakeup",
            "jobs": [
              {
                "name": "prepare breakfast",

              }
            ]
          }
        ]
      }
    ]
  }
]

This will make things much easier and easy to loop through.

Now you can write the loop as -

<div ng-repeat="week in myData">
   <div ng-repeat="day in week.days">
      {{day.dow}} - {{day.templateDay}}
      <b>Jobs:</b><br/> 
       <ul>
         <li ng-repeat="job in day.jobs"> 
           {{job.name}} 
         </li>
       </ul>
   </div>
</div>

Gaussian filter in MATLAB

You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).

You specify sigma and hsize in fspecial.

Code:

%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)

cannot call member function without object

You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this:

int main()
{
   Name_pairs np;
   cout << "Enter names and ages. Use 0 to cancel.\n";
   while(np.test())
   {
      np.read_names();
      np.read_ages();
   }
   np.print();
   keep_window_open();
}

string encoding and decoding?

You can't decode a unicode, and you can't encode a str. Try doing it the other way around.

Make Font Awesome icons in a circle?

This is the best and most precise solution I've found so far.

CSS:

.social .fa {
      margin-right: 1rem;
      border: 2px #fff solid;
      border-radius: 50%;
      height: 20px;
      width: 20px;
      line-height: 20px;
      text-align: center;
      padding: 0.5rem;
    }

How to append a char to a std::string?

I test the several propositions by running them into a large loop. I used microsoft visual studio 2015 as compiler and my processor is an i7, 8Hz, 2GHz.

    long start = clock();
    int a = 0;
    //100000000
    std::string ret;
    for (int i = 0; i < 60000000; i++)
    {
        ret.append(1, ' ');
        //ret += ' ';
        //ret.push_back(' ');
        //ret.insert(ret.end(), 1, ' ');
        //ret.resize(ret.size() + 1, ' ');
    }
    long stop = clock();
    long test = stop - start;
    return 0;

According to this test, results are :

     operation             time(ms)            note
------------------------------------------------------------------------
append                     66015
+=                         67328      1.02 time slower than 'append'
resize                     83867      1.27 time slower than 'append'
push_back & insert         90000      more than 1.36 time slower than 'append'

Conclusion

+= seems more understandable, but if you mind about speed, use append

Is it .yaml or .yml?

The nature and even existence of file extensions is platform-dependent (some obscure platforms don't even have them, remember) -- in other systems they're only conventional (UNIX and its ilk), while in still others they have definite semantics and in some cases specific limits on length or character content (Windows, etc.).

Since the maintainers have asked that you use ".yaml", that's as close to an "official" ruling as you can get, but the habit of 8.3 is hard to get out of (and, appallingly, still occasionally relevant in 2013).

Upload file to SFTP using PowerShell

Using PuTTY's pscp.exe (which I have in an $env:path directory):

pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*

jQuery - Add active class and remove active from other element on click

Try this one:

$(document).ready(function() {
    $(".tab").click(function () {
        $("this").addClass("active").siblings().removeClass("active");   
    });
});

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

Setting environment variable in react-native?

The specific method used to set environment variables will vary by CI service, build approach, platform and tools you're using.

If you're using Buddybuild for CI to build an app and manage environment variables, and you need access to config from JS, create a env.js.example with keys (with empty string values) for check-in to source control, and use Buddybuild to produce an env.js file at build time in the post-clone step, hiding the file contents from the build logs, like so:

#!/usr/bin/env bash

ENVJS_FILE="$BUDDYBUILD_WORKSPACE/env.js"

# Echo what's happening to the build logs
echo Creating environment config file

# Create `env.js` file in project root
touch $ENVJS_FILE

# Write environment config to file, hiding from build logs
tee $ENVJS_FILE > /dev/null <<EOF
module.exports = {
  AUTH0_CLIENT_ID: '$AUTH0_CLIENT_ID',
  AUTH0_DOMAIN: '$AUTH0_DOMAIN'
}
EOF

Tip: Don't forget to add env.js to .gitignore so config and secrets aren't checked into source control accidentally during development.

You can then manage how the file gets written using the Buddybuild variables like BUDDYBUILD_VARIANTS, for instance, to gain greater control over how your config is produced at build time.

Check if a string is html or not

zzzzBov's answer above is good, but it does not account for stray closing tags, like for example:

/<[a-z][\s\S]*>/i.test('foo </b> bar'); // false

A version that also catches closing tags could be this:

/<[a-z/][\s\S]*>/i.test('foo </b> bar'); // true

What is the difference between .py and .pyc files?

Python compiles the .py and saves files as .pyc so it can reference them in subsequent invocations.

There's no harm in deleting them, but they will save compilation time if you're doing lots of processing.

Get the records of last month in SQL server

You can get the last month records with this query

SELECT * FROM dbo.member d 
WHERE  CONVERT(DATE, date_created,101)>=CONVERT(DATE,DATEADD(m, datediff(m, 0, current_timestamp)-1, 0)) 
and CONVERT(DATE, date_created,101) < CONVERT(DATE, DATEADD(m, datediff(m, 0, current_timestamp)-1, 0),101) 

Statistics: combinations in Python

If your program has an upper bound to n (say n <= N) and needs to repeatedly compute nCr (preferably for >>N times), using lru_cache can give you a huge performance boost:

from functools import lru_cache

@lru_cache(maxsize=None)
def nCr(n, r):
    return 1 if r == 0 or r == n else nCr(n - 1, r - 1) + nCr(n - 1, r)

Constructing the cache (which is done implicitly) takes up to O(N^2) time. Any subsequent calls to nCr will return in O(1).

Concat strings by & and + in VB.Net

From a former string concatenater (sp?) you should really consider using String.Format instead of concatenation.

    Dim s1 As String
    Dim i As Integer
    s1 = "Hello"
    i = 1
    String.Format("{0} {1}", s1, i)

It makes things a lot easier to read and maintain and I believe makes your code look more professional. See: code better – use string.format. Although not everyone agrees When is it better to use String.Format vs string concatenation?

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I also had a similar issue. After copying and pasting to a sheet I wanted the cursor/ selected cell to be A1 not the range that I just pasted into.

Dim wkSheet as Worksheet
Set wkSheet = Worksheets(<sheetname>)

wkSheet("A1").Select

but got a 400 error which was actually a 1004 error

You need to activate the sheet before changing the selected cell this worked

Dim wkSheet as Worksheet
Set wkSheet = Worksheets(<sheetname>)

wkSheet.Activate
wkSheet("A1").Select

Mongoose query where value is not null

$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.

User.find({ "username": { "$ne": 'admin' } })

$nin

$nin selects the documents where: the field value is not in the specified array or the field does not exist.

User.find({ "groups": { "$nin": ['admin', 'user'] } })

How to use bitmask?

Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value.

An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this:

RRRR RGGG GGGB BBBB

You could then use bit masking to retrieve the colour components as follows:

  const unsigned short redMask   = 0xF800;
  const unsigned short greenMask = 0x07E0;
  const unsigned short blueMask  = 0x001F;

  unsigned short lightGray = 0x7BEF;

  unsigned short redComponent   = (lightGray & redMask) >> 11;
  unsigned short greenComponent = (lightGray & greenMask) >> 5;
  unsigned short blueComponent =  (lightGray & blueMask);

What's alternative to angular.copy in Angular

The simplest solution I've found is:

let yourDeepCopiedObject = _.cloneDeep(yourOriginalObject);

*IMPORTANT STEPS: You must install lodash to use this (which was unclear from other answers):

$ npm install --save lodash

$ npm install --save @types/lodash

and then import it in your ts file:

import * as _ from "lodash";

How to find cube root using Python?

The best way is to use simple math

>>> a = 8
>>> a**(1./3.)
2.0

EDIT

For Negative numbers

>>> a = -8
>>> -(-a)**(1./3.)
-2.0

Complete Program for all the requirements as specified

x = int(input("Enter an integer: "))
if x>0:
    ans = x**(1./3.)
    if ans ** 3 != abs(x):
        print x, 'is not a perfect cube!'
else:
    ans = -((-x)**(1./3.))
    if ans ** 3 != -abs(x):
        print x, 'is not a perfect cube!'

print 'Cube root of ' + str(x) + ' is ' + str(ans)

What is a user agent stylesheet?

What are the target browsers? Different browsers set different default CSS rules. Try including a CSS reset, such as the meyerweb CSS reset or normalize.css, to remove those defaults. Google "CSS reset vs normalize" to see the differences.

Error loading the SDK when Eclipse starts

This was my error message:

Error: Error Parsing C:\Android\sdk\system-images\android-22\android-wear\armeabi-v7a\devices.xml Invalid content was found starting with element 'd:Skin'. No child element is expected at this point.

There´s a kind of problem with android Wear packages for API 22, so my solution was deleting this two packages from the API 22

enter image description here

Can an Option in a Select tag carry multiple values?

I was actually wondering this today, and I achieved it by using the php explode function, like this:

HTML Form (in a file I named 'doublevalue.php':

    <form name="car_form" method="post" action="doublevalue_action.php">
            <select name="car" id="car">
                    <option value="">Select Car</option>
                    <option value="BMW|Red">Red BMW</option>
                    <option value="Mercedes|Black">Black Mercedes</option>
            </select>
            <input type="submit" name="submit" id="submit" value="submit">
    </form>

PHP action (in a file I named doublevalue_action.php)

    <?php
            $result = $_POST['car'];
            $result_explode = explode('|', $result);
            echo "Model: ". $result_explode[0]."<br />";
            echo "Colour: ". $result_explode[1]."<br />";
    ?>

As you can see in the first piece of code, we're creating a standard HTML select box, with 2 options. Each option has 1 value, which has a separator (in this instance, '|') to split the values (in this case, model and colour).

On the action page, I'm exploding the results into an array, then calling each one. As you can see, I've separated and labelled them so you can see the effect this is causing.

I hope this helps someone :)

Hadoop/Hive : Loading data from .csv on a local machine

You can load local CSV file to Hive only if:

  1. You are doing it from one of the Hive cluster nodes.
  2. You installed Hive client on non-cluster node and using hive or beeline for upload.

How to insert pandas dataframe via mysqldb into database?

You can do it by using pymysql:

For example, let's suppose you have a MySQL database with the next user, password, host and port and you want to write in the database 'data_2', if it is already there or not.

import pymysql
user = 'root'
passw = 'my-secret-pw-for-mysql-12ud'
host =  '172.17.0.2'
port = 3306
database = 'data_2'

If you already have the database created:

conn = pymysql.connect(host=host,
                       port=port,
                       user=user, 
                       passwd=passw,  
                       db=database,
                       charset='utf8')

data.to_sql(name=database, con=conn, if_exists = 'replace', index=False, flavor = 'mysql')

If you do NOT have the database created, also valid when the database is already there:

conn = pymysql.connect(host=host, port=port, user=user, passwd=passw)

conn.cursor().execute("CREATE DATABASE IF NOT EXISTS {0} ".format(database))
conn = pymysql.connect(host=host,
                       port=port,
                       user=user, 
                       passwd=passw,  
                       db=database,
                       charset='utf8')

data.to_sql(name=database, con=conn, if_exists = 'replace', index=False, flavor = 'mysql')

Similar threads:

  1. Writing to MySQL database with pandas using SQLAlchemy, to_sql
  2. Writing a Pandas Dataframe to MySQL

m2eclipse error

In this particular case, the solution was the right proxy configuration of eclipse (Window -> Preferences -> Network Connection), the company possessed a strict security system. I will leave the question, because there are answers that can help the community. Thank you very much for the answers above.

Command line input in Python

It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:

For interactive user input (or piped commands or redirected input)

Use raw_input in Python 2.x, and input in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)

For example:

user_input = raw_input("Some input please: ")

More details can be found here.

So, for example, you might have a script that looks like this

# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)

# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3

# Now do something with the above
print(user_input)

If you saved this in foo.py, you could just call the script from the command line, it would print out tok tiktok, then ask you for input. You could enter bar baz (followed by the enter key) and it would print bar baz. Here's what that would look like:

$ python foo.py
tok tiktok
Some input please: bar baz
bar baz

Here, $ represents the command-line prompt (so you don't actually type that), and I hit Enter after typing bar baz when it asked for input.

For command-line arguments

Suppose you have a script named foo.py and want to call it with arguments bar and baz from the command line like

$ foo.py bar baz

(Again, $ represents the command-line prompt.) Then, you can do that with the following in your script:

import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]

Here, the variable arg1 will contain the string 'bar', and arg2 will contain 'baz'. The object sys.argv is just a list containing everything from the command line. Note that sys.argv[0] is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:].

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

What's the difference between Thread start() and Runnable run()

If you do run() in main method, the thread of main method will invoke the run method instead of the thread you require to run.

The start() method creates new thread and for which the run() method has to be done

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

PostgreSQL Error: Relation already exists

In my case I was migrating from 9.5 to 9.6. So to restore a database, I was doing :

sudo -u postgres psql -d databse -f dump.sql

Of course it was executing on the old postgreSQL database where there are datas! If your new instance is on port 5433, the correct way is :

sudo -u postgres psql -d databse -f dump.sql -p 5433

Find methods calls in Eclipse project

Move the cursor to the method name. Right click and select References > Project or References > Workspace from the pop-up menu.

LaTeX: Prevent line break in a span of text

\mbox is the simplest answer. Regarding the update:

TeX prefers overlong lines to adding too much space between words on a line; I think the idea is that you will notice the lines that extend into the margin (and the black boxes it inserts after such lines), and will have a chance to revise the contents, whereas if there was too much space, you might not notice it.

Use \sloppy or \begin{sloppypar}...\end{sloppypar} to adjust this behavior, at least a little. Another possibility is \raggedright (or \begin{raggedright}...\end{raggedright}).

Android ADB device offline, can't issue commands

I tried dturvene and all the other solutions, but they didn't work. I needed one more step.

Run these commands

  1. adb kill-server
  2. android update sdk --no-ui
  3. adb start-server

To verify that it worked, run 'adb version' before and after the commands and make sure it is the latest. The reason for the adb kill-server command is that it it most likely running, and it can't be updated while it is running, so you have to kill it first.

Is it possible to GROUP BY multiple columns using MySQL?

group by fV.tier_id, f.form_template_id

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

Should it be LIBRARY_PATH instead of LD_LIBRARY_PATH. gcc checks for LIBRARY_PATH which can be seen with -v option

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

You can use ObjectMapper

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectClass object = objectMapper.readValue(data, ObjectClass.class);

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I coded up an equivalent C program to experiment, and I can confirm this strange behaviour. What's more, gcc believes the 64-bit integer (which should probably be a size_t anyway...) to be better, as using uint_fast32_t causes gcc to use a 64-bit uint.

I did a bit of mucking around with the assembly:
Simply take the 32-bit version, replace all 32-bit instructions/registers with the 64-bit version in the inner popcount-loop of the program. Observation: the code is just as fast as the 32-bit version!

This is obviously a hack, as the size of the variable isn't really 64 bit, as other parts of the program still use the 32-bit version, but as long as the inner popcount-loop dominates performance, this is a good start.

I then copied the inner loop code from the 32-bit version of the program, hacked it up to be 64 bit, fiddled with the registers to make it a replacement for the inner loop of the 64-bit version. This code also runs as fast as the 32-bit version.

My conclusion is that this is bad instruction scheduling by the compiler, not actual speed/latency advantage of 32-bit instructions.

(Caveat: I hacked up assembly, could have broken something without noticing. I don't think so.)

Get month name from number

I'll offer this in case (like me) you have a column of month numbers in a dataframe:

df['monthName'] = df['monthNumer'].apply(lambda x: calendar.month_name[x])

MySQL select one column DISTINCT, with corresponding other columns

SELECT DISTINCT(firstName), ID, LastName from tableName GROUP BY firstName

Would be the best bet IMO

Convert a String representation of a Dictionary to a dictionary?

To summarize:

import ast, yaml, json, timeit

descs=['short string','long string']
strings=['{"809001":2,"848545":2,"565828":1}','{"2979":1,"30581":1,"7296":1,"127256":1,"18803":2,"41619":1,"41312":1,"16837":1,"7253":1,"70075":1,"3453":1,"4126":1,"23599":1,"11465":3,"19172":1,"4019":1,"4775":1,"64225":1,"3235":2,"15593":1,"7528":1,"176840":1,"40022":1,"152854":1,"9878":1,"16156":1,"6512":1,"4138":1,"11090":1,"12259":1,"4934":1,"65581":1,"9747":2,"18290":1,"107981":1,"459762":1,"23177":1,"23246":1,"3591":1,"3671":1,"5767":1,"3930":1,"89507":2,"19293":1,"92797":1,"32444":2,"70089":1,"46549":1,"30988":1,"4613":1,"14042":1,"26298":1,"222972":1,"2982":1,"3932":1,"11134":1,"3084":1,"6516":1,"486617":1,"14475":2,"2127":1,"51359":1,"2662":1,"4121":1,"53848":2,"552967":1,"204081":1,"5675":2,"32433":1,"92448":1}']
funcs=[json.loads,eval,ast.literal_eval,yaml.load]

for  desc,string in zip(descs,strings):
    print('***',desc,'***')
    print('')
    for  func in funcs:
        print(func.__module__+' '+func.__name__+':')
        %timeit func(string)        
    print('')

Results:

*** short string ***

json loads:
4.47 µs ± 33.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
builtins eval:
24.1 µs ± 163 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
ast literal_eval:
30.4 µs ± 299 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
yaml load:
504 µs ± 1.29 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

*** long string ***

json loads:
29.6 µs ± 230 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
builtins eval:
219 µs ± 3.92 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
ast literal_eval:
331 µs ± 1.89 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
yaml load:
9.02 ms ± 92.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Conclusion: prefer json.loads

How to read a text file directly from Internet using Java?

Use an URL instead of File for any access that is not on your local computer.

URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner s = new Scanner(url.openStream());

Actually, URL is even more generally useful, also for local access (use a file: URL), jar files, and about everything that one can retrieve somehow.

The way above interprets the file in your platforms default encoding. If you want to use the encoding indicated by the server instead, you have to use a URLConnection and parse it's content type, like indicated in the answers to this question.


About your Error, make sure your file compiles without any errors - you need to handle the exceptions. Click the red messages given by your IDE, it should show you a recommendation how to fix it. Do not start a program which does not compile (even if the IDE allows this).

Here with some sample exception-handling:

try {
   URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
   Scanner s = new Scanner(url.openStream());
   // read from your scanner
}
catch(IOException ex) {
   // there was some connection problem, or the file did not exist on the server,
   // or your URL was not in the right format.
   // think about what to do now, and put it here.
   ex.printStackTrace(); // for now, simply output it.
}

Two dimensional array in python

You can first append elements to the initialized array and then for convenience, you can convert it into a numpy array.

import numpy as np
a = [] # declare null array
a.append(['aa1']) # append elements
a.append(['aa2'])
a.append(['aa3'])
print(a)
a_np = np.asarray(a) # convert to numpy array
print(a_np)

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

I found this implementation very easy to use. Also has a generous BSD-style license:

jsSHA: https://github.com/Caligatio/jsSHA

I needed a quick way to get the hex-string representation of a SHA-256 hash. It only took 3 lines:

var sha256 = new jsSHA('SHA-256', 'TEXT');
sha256.update(some_string_variable_to_hash);
var hash = sha256.getHash("HEX");

Make iframe automatically adjust height according to the contents without using scrollbar?

You can use this library, which both initially sizes your iframe correctly and also keeps it at the right size by detecting whenever the size of the iframe's content changes (either via regular checking in a setInterval or via MutationObserver) and resizing it.

https://github.com/davidjbradshaw/iframe-resizer

Their is also a React version.

https://github.com/davidjbradshaw/iframe-resizer-react

This works with both cross and same domain iframes.

Docker: Copying files from Docker container to host

TLDR;

$ docker run --rm -iv${PWD}:/host-volume my-image sh -s <<EOF
chown $(id -u):$(id -g) my-artifact.tar.xz
cp -a my-artifact.tar.xz /host-volume
EOF

Description

docker run with a host volume, chown the artifact, cp the artifact to the host volume:

$ docker build -t my-image - <<EOF
> FROM busybox
> WORKDIR /workdir
> RUN touch foo.txt bar.txt qux.txt
> EOF
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
 ---> 00f017a8c2a6
Step 2/3 : WORKDIR /workdir
 ---> Using cache
 ---> 36151d97f2c9
Step 3/3 : RUN touch foo.txt bar.txt qux.txt
 ---> Running in a657ed4f5cab
 ---> 4dd197569e44
Removing intermediate container a657ed4f5cab
Successfully built 4dd197569e44

$ docker run --rm -iv${PWD}:/host-volume my-image sh -s <<EOF
chown -v $(id -u):$(id -g) *.txt
cp -va *.txt /host-volume
EOF
changed ownership of '/host-volume/bar.txt' to 10335:11111
changed ownership of '/host-volume/qux.txt' to 10335:11111
changed ownership of '/host-volume/foo.txt' to 10335:11111
'bar.txt' -> '/host-volume/bar.txt'
'foo.txt' -> '/host-volume/foo.txt'
'qux.txt' -> '/host-volume/qux.txt'

$ ls -n
total 0
-rw-r--r-- 1 10335 11111 0 May  7 18:22 bar.txt
-rw-r--r-- 1 10335 11111 0 May  7 18:22 foo.txt
-rw-r--r-- 1 10335 11111 0 May  7 18:22 qux.txt

This trick works because the chown invocation within the heredoc the takes $(id -u):$(id -g) values from outside the running container; i.e., the docker host.

The benefits are:

  • you don't have to docker container run --name or docker container create --name before
  • you don't have to docker container rm after

How to silence output in a Bash script?

Redirect stderr to stdout

This will redirect the stderr (which is descriptor 2) to the file descriptor 1 which is the the stdout.

2>&1

Redirect stdout to File

Now when perform this you are redirecting the stdout to the file sample.s

myprogram > sample.s

Redirect stderr and stdout to File

Combining the two commands will result in redirecting both stderr and stdout to sample.s

myprogram > sample.s 2>&1

Redirect stderr and stdout to /dev/null

Redirect to /dev/null if you want to completely silent your application.

myprogram >/dev/null 2>&1

Configuring Hibernate logging using Log4j XML config file?

In response to homaxto's comment, this is what I have right now.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug"/>
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ABSOLUTE} [%t] %-5p %c{1} - %m%n"/>
        </layout>
    </appender>
    <appender name="rolling-file" class="org.apache.log4j.RollingFileAppender">
        <param name="file" value="Program-Name.log"/>
        <param name="MaxFileSize" value="500KB"/>
        <param name="MaxBackupIndex" value="4"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %-5p %l - %m%n"/>
        </layout>
    </appender>

    <logger name="org.hibernate">
        <level value="info" />
    </logger>

    <root>
        <priority value ="debug" />
        <appender-ref ref="console" />
        <appender-ref ref="rolling-file" />
    </root>
</log4j:configuration>

The key part being

<logger name="org.hibernate">
    <level value="info" />
</logger>

Hope this helps.

Count number of 1's in binary representation

That will be the shortest answer in my SO life: lookup table.

Apparently, I need to explain a bit: "if you have enough memory to play with" means, we've got all the memory we need (nevermind technical possibility). Now, you don't need to store lookup table for more than a byte or two. While it'll technically be O(log(n)) rather than O(1), just reading a number you need is O(log(n)), so if that's a problem, then the answer is, impossible—which is even shorter.

Which of two answers they expect from you on an interview, no one knows.

There's yet another trick: while engineers can take a number and talk about O(log(n)), where n is the number, computer scientists will say that actually we're to measure running time as a function of a length of an input, so what engineers call O(log(n)) is actually O(k), where k is the number of bytes. Still, as I said before, just reading a number is O(k), so there's no way we can do better than that.

Pass a PHP variable value through an HTML form

Try that

First place

global $var;
$var = 'value';

Second place

global $var;
if (isset($_POST['save_exit']))
{
    echo $var; 
}

Or if you want to be more explicit you can use the globals array:

$GLOBALS['var'] = 'test';

// after that
echo $GLOBALS['var'];

And here is third options which has nothing to do with PHP global that is due to the lack of clarity and information in the question. So if you have form in HTML and you want to pass "variable"/value to another PHP script you have to do the following:

HTML form

<form action="script.php" method="post">
    <input type="text" value="<?php echo $var?>" name="var" />
    <input type="submit" value="Send" />
</form>

PHP script ("script.php")

<?php

$var = $_POST['var'];
echo $var;

?>

How to add a progress bar to a shell script?

I did a pure shell version for an embedded system taking advantage of:

  • /usr/bin/dd's SIGUSR1 signal handling feature.

    Basically, if you send a 'kill SIGUSR1 $(pid_of_running_dd_process)', it'll output a summary of throughput speed and amount transferred.

  • backgrounding dd and then querying it regularly for updates, and generating hash ticks like old-school ftp clients used to.

  • Using /dev/stdout as the destination for non-stdout friendly programs like scp

The end result allows you to take any file transfer operation and get progress update that looks like old-school FTP 'hash' output where you'd just get a hash mark for every X bytes.

This is hardly production quality code, but you get the idea. I think it's cute.

For what it's worth, the actual byte-count might not be reflected correctly in the number of hashes - you may have one more or less depending on rounding issues. Don't use this as part of a test script, it's just eye-candy. And, yes, I'm aware this is terribly inefficient - it's a shell script and I make no apologies for it.

Examples with wget, scp and tftp provided at the end. It should work with anything that has emits data. Make sure to use /dev/stdout for programs that aren't stdout friendly.

#!/bin/sh
#
# Copyright (C) Nathan Ramella ([email protected]) 2010 
# LGPLv2 license
# If you use this, send me an email to say thanks and let me know what your product
# is so I can tell all my friends I'm a big man on the internet!

progress_filter() {

        local START=$(date +"%s")
        local SIZE=1
        local DURATION=1
        local BLKSZ=51200
        local TMPFILE=/tmp/tmpfile
        local PROGRESS=/tmp/tftp.progress
        local BYTES_LAST_CYCLE=0
        local BYTES_THIS_CYCLE=0

        rm -f ${PROGRESS}

        dd bs=$BLKSZ of=${TMPFILE} 2>&1 \
                | grep --line-buffered -E '[[:digit:]]* bytes' \
                | awk '{ print $1 }' >> ${PROGRESS} &

        # Loop while the 'dd' exists. It would be 'more better' if we
        # actually looked for the specific child ID of the running 
        # process by identifying which child process it was. If someone
        # else is running dd, it will mess things up.

        # My PID handling is dumb, it assumes you only have one running dd on
        # the system, this should be fixed to just get the PID of the child
        # process from the shell.

        while [ $(pidof dd) -gt 1 ]; do

                # PROTIP: You can sleep partial seconds (at least on linux)
                sleep .5    

                # Force dd to update us on it's progress (which gets
                # redirected to $PROGRESS file.
                # 
                # dumb pid handling again
                pkill -USR1 dd

                local BYTES_THIS_CYCLE=$(tail -1 $PROGRESS)
                local XFER_BLKS=$(((BYTES_THIS_CYCLE-BYTES_LAST_CYCLE)/BLKSZ))

                # Don't print anything unless we've got 1 block or more.
                # This allows for stdin/stderr interactions to occur
                # without printing a hash erroneously.

                # Also makes it possible for you to background 'scp',
                # but still use the /dev/stdout trick _even_ if scp
                # (inevitably) asks for a password. 
                #
                # Fancy!

                if [ $XFER_BLKS -gt 0 ]; then
                        printf "#%0.s" $(seq 0 $XFER_BLKS)
                        BYTES_LAST_CYCLE=$BYTES_THIS_CYCLE
                fi
        done

        local SIZE=$(stat -c"%s" $TMPFILE)
        local NOW=$(date +"%s")

        if [ $NOW -eq 0 ]; then
                NOW=1
        fi

        local DURATION=$(($NOW-$START))
        local BYTES_PER_SECOND=$(( SIZE / DURATION ))
        local KBPS=$((SIZE/DURATION/1024))
        local MD5=$(md5sum $TMPFILE | awk '{ print $1 }')

        # This function prints out ugly stuff suitable for eval() 
        # rather than a pretty string. This makes it a bit more 
        # flexible if you have a custom format (or dare I say, locale?)

        printf "\nDURATION=%d\nBYTES=%d\nKBPS=%f\nMD5=%s\n" \
            $DURATION \
            $SIZE \
            $KBPS \
            $MD5
}

Examples:

echo "wget"
wget -q -O /dev/stdout http://www.blah.com/somefile.zip | progress_filter

echo "tftp"
tftp -l /dev/stdout -g -r something/firmware.bin 192.168.1.1 | progress_filter

echo "scp"
scp [email protected]:~/myfile.tar /dev/stdout | progress_filter

Errors in pom.xml with dependencies (Missing artifact...)

It seemed that a lot of dependencies were incorrect.

enter image description here

Download the whole POM here

A good place to look for the correct dependencies is the Maven Repository website.

Make one div visible and another invisible

You can use the display property of style. Intialy set the result section style as

style = "display:none"

Then the div will not be visible and there won't be any white space.

Once the search results are being populated change the display property using the java script like

document.getElementById("someObj").style.display = "block"

Using java script you can make the div invisible

document.getElementById("someObj").style.display = "none"

FB OpenGraph og:image not pulling images (possibly https?)

Once you update the meta tag make sure the content(image) link is absolute path and go here https://developers.facebook.com/tools/debug/sharing enter you site link and click on scrape again in next page

How do you add UI inside cells in a google spreadsheet using app script?

Buttons can be added to frozen rows as images. Assigning a function within the attached script to the button makes it possible to run the function. The comment which says you can not is of course a very old comment, possibly things have changed now.

Changing cursor to waiting in javascript/jquery

$('#some_id').click(function() {
  $("body").css("cursor", "progress");
  $.ajax({
    url: "test.html",
    context: document.body,
    success: function() {
      $("body").css("cursor", "default");
    }
  });
});

This will create a loading cursor till your ajax call succeeds.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

string filePath = HttpContext.Current.Server.MapPath("~/folderName/filename.extension");

OR

string filePath = HttpContext.Server.MapPath("~/folderName/filename.extension");

Can Twitter Bootstrap alerts fade in as well as out?

I got this way to close fading my Alert after 3 seconds. Hope it will be useful.

    setTimeout(function(){
    $('.alert').fadeTo("slow", 0.1, function(){
        $('.alert').alert('close')
    });     
    }, 3000)

error 1265. Data truncated for column when trying to load data from txt file

This error means that at least one row in your Pickup_withoutproxy2.txt file has a value in its first column that is larger than an int (your PickupId field).

An Int can only accept values between -2147483648 to 2147483647.

Review your data to see what's going on. You could try to load it into a temp table with a varchar data type if your txt file is extremely large and difficult to see. Easy enough to check for an int once loaded in the database.

Good luck.

How to append to a file in Node?

In addition to denysonique's answer, sometimes asynchronous type of appendFile and other async methods in NodeJS are used where promise returns instead of callback passing. To do it you need to wrap the function with promisify HOF or import async functions from promises namespace:

const { appendFile } = require('fs').promises;

await appendFile('path/to/file/to/append', dataToAppend, optionalOptions);

I hope it'll help

Get path of executable

This was my solution in Windows. It is called like this:

std::wstring sResult = GetPathOfEXE(64);

Where 64 is the minimum size you think the path will be. GetPathOfEXE calls itself recursively, doubling the size of the buffer each time until it gets a big enough buffer to get the whole path without truncation.

std::wstring GetPathOfEXE(DWORD dwSize)
{
    WCHAR* pwcharFileNamePath;
    DWORD dwLastError;
    HRESULT hrError;
    std::wstring wsResult;
    DWORD dwCount;

    pwcharFileNamePath = new WCHAR[dwSize];

    dwCount = GetModuleFileNameW(
        NULL,
        pwcharFileNamePath,
        dwSize
    );

    dwLastError = GetLastError();

    if (ERROR_SUCCESS == dwLastError)
    {
        hrError = PathCchRemoveFileSpec(
            pwcharFileNamePath,
            dwCount
        );

        if (S_OK == hrError)
        {
            wsResult = pwcharFileNamePath;

            if (pwcharFileNamePath)
            {
                delete pwcharFileNamePath;
            }

            return wsResult;
        }
        else if(S_FALSE == hrError)
        {
            wsResult = pwcharFileNamePath;

            if (pwcharFileNamePath)
            {
                delete pwcharFileNamePath;
            }

            //there was nothing to truncate off the end of the path
            //returning something better than nothing in this case for the user
            return wsResult;
        }
        else
        {
            if (pwcharFileNamePath)
            {
                delete pwcharFileNamePath;
            }

            std::ostringstream oss;
            oss << "could not get file name and path of executing process. error truncating file name off path. last error : " << hrError;
            throw std::runtime_error(oss.str().c_str());
        }
    }
    else if (ERROR_INSUFFICIENT_BUFFER == dwLastError)
    {
        if (pwcharFileNamePath)
        {
            delete pwcharFileNamePath;
        }

        return GetPathOfEXE(
            dwSize * 2
        );
    }
    else
    {
        if (pwcharFileNamePath)
        {
            delete pwcharFileNamePath;
        }

        std::ostringstream oss;
        oss << "could not get file name and path of executing process. last error : " << dwLastError;
        throw std::runtime_error(oss.str().c_str());
    }
}

How can I bring my application window to the front?

this works:

if (WindowState == FormWindowState.Minimized)
    WindowState = FormWindowState.Normal;
else
{
    TopMost = true;
    Focus();
    BringToFront();
    TopMost = false;
}

Playing Sound In Hidden Tag

That's how I achieved it, which is not visible (HORRIBLE SOUND....)

<!-- horrible is your mp3 file name any other supported format.-->
<audio controls autoplay hidden="" src="horrible.mp3" type ="audio/mp3"">your browser does not support Html5</audio>

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

String comparison in Python: is vs. ==

See This question

Your logic in reading

For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.

is slightly flawed.

If is applies then == will be True, but it does NOT apply in reverse. == may yield True while is yields False.

What does "commercial use" exactly mean?

If the usage of something is part of the process of you making money, then it's generally considered a commercial use. If the purpose of the site is to, through some means or another, directly or indirectly, make you money, then it's probably commercial use.

If, on the other hand, something is merely incidental (not part of the process of production/working, but instead simply tacked on to the side), there are potential grounds for it not to be considered commercial use.

Formatting Decimal places in R

You can format a number, say x, up to decimal places as you wish. Here x is a number with many decimal places. Suppose we wish to show up to 8 decimal places of this number:

x = 1111111234.6547389758965789345
y = formatC(x, digits = 8, format = "f")
# [1] "1111111234.65473890"

Here format="f" gives floating numbers in the usual decimal places say, xxx.xxx, and digits specifies the number of digits. By contrast, if you wanted to get an integer to display you would use format="d" (much like sprintf).

Get current index from foreach loop

You have two options here, 1. Use for instead for foreach for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:

int i = 0; // for index
foreach (var row in list)
{
    bool IsChecked;// assign value to this variable
    if (IsChecked)
    {    
       // use i value here                
    }
    i++; // will increment i in each iteration
}

How to detect query which holds the lock in Postgres?

From this excellent article on query locks in Postgres, one can get blocked query and blocker query and their information from the following query.

CREATE VIEW lock_monitor AS(
SELECT
  COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item,
  now() - blockeda.query_start AS waiting_duration, blockeda.pid AS blocked_pid,
  blockeda.query as blocked_query, blockedl.mode as blocked_mode,
  blockinga.pid AS blocking_pid, blockinga.query as blocking_query,
  blockingl.mode as blocking_mode
FROM pg_catalog.pg_locks blockedl
JOIN pg_stat_activity blockeda ON blockedl.pid = blockeda.pid
JOIN pg_catalog.pg_locks blockingl ON(
  ( (blockingl.transactionid=blockedl.transactionid) OR
  (blockingl.relation=blockedl.relation AND blockingl.locktype=blockedl.locktype)
  ) AND blockedl.pid != blockingl.pid)
JOIN pg_stat_activity blockinga ON blockingl.pid = blockinga.pid
  AND blockinga.datid = blockeda.datid
WHERE NOT blockedl.granted
AND blockinga.datname = current_database()
);

SELECT * from lock_monitor;

As the query is long but useful, the article author has created a view for it to simplify it's usage.

Create nice column output in python

Since Python 2.6+, you can use a format string in the following way to set the columns to a minimum of 20 characters and align text to right.

table_data = [
    ['a', 'b', 'c'],
    ['aaaaaaaaaa', 'b', 'c'], 
    ['a', 'bbbbbbbbbb', 'c']
]
for row in table_data:
    print("{: >20} {: >20} {: >20}".format(*row))

Output:

               a                    b                    c
      aaaaaaaaaa                    b                    c
               a           bbbbbbbbbb                    c

Why am I getting string does not name a type Error?

Your using declaration is in game.cpp, not game.h where you actually declare string variables. You intended to put using namespace std; into the header, above the lines that use string, which would let those lines find the string type defined in the std namespace.

As others have pointed out, this is not good practice in headers -- everyone who includes that header will also involuntarily hit the using line and import std into their namespace; the right solution is to change those lines to use std::string instead

Nginx no-www to www and www to no-www

If you are having trouble getting this working, you may need to add the IP address of your server. For example:

server {
listen XXX.XXX.XXX.XXX:80;
listen XXX.XXX.XXX.XXX:443 ssl;
ssl_certificate /var/www/example.com/web/ssl/example.com.crt;
ssl_certificate_key /var/www/example.com/web/ssl/example.com.key;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}

where XXX.XXX.XXX.XXX is the IP address (obviously).

Note: ssl crt and key location must be defined to properly redirect https requests

Don't forget to restart nginx after making the changes:

service nginx restart

Splitting string into multiple rows in Oracle

If you have Oracle APEX 5.1 or later installed, you can use the convenient APEX_STRING.split function, e.g.:

select q.Name, q.Project, s.column_value as Error
from mytable q,
     APEX_STRING.split(q.Error, ',') s

The second parameter is the delimiter string. It also accepts a 3rd parameter to limit how many splits you want it to perform.

https://docs.oracle.com/en/database/oracle/application-express/20.1/aeapi/SPLIT-Function-Signature-1.html#GUID-3BE7FF37-E54F-4503-91B8-94F374E243E6

Android Min SDK Version vs. Target SDK Version

When you set targetSdkVersion="xx", you are certifying that your app works properly (e.g., has been thoroughly and successfully tested) at API level xx.

A version of Android running at an API level above xx will apply compatibility code automatically to support any features you might be relying upon that were available at or prior to API level xx, but which are now obsolete at that Android version's higher level.

Conversely, if you are using any features that became obsolete at or prior to level xx, compatibility code will not be automatically applied by OS versions at higher API levels (that no longer include those features) to support those uses. In that situation, your own code must have special case clauses that test the API level and, if the OS level detected is a higher one that no longer has the given API feature, your code must use alternate features that are available at the running OS's API level.

If it fails to do this, then some interface features may simply not appear that would normally trigger events within your code, and you may be missing a critical interface feature that the user needs to trigger those events and to access their functionality (as in the example below).

As stated in other answers, you might set targetSdkVersion higher than minSdkVersion if you wanted to use some API features initially defined at higher API levels than your minSdkVersion, and had taken steps to ensure that your code could detect and handle the absence of those features at lower levels than targetSdkVersion.

In order to warn developers to specifically test for the minimum API level required to use a feature, the compiler will issue an error (not just a warning) if code contains a call to any method that was defined at a later API level than minSdkVersion, even if targetSdkVersion is greater than or equal to the API level at which that method was first made available. To remove this error, the compiler directive

@TargetApi(nn)

tells the compiler that the code within the scope of that directive (which will precede either a method or a class) has been written to test for an API level of at least nn prior to calling any method that depends upon having at least that API level. For example, the following code defines a method that can be called from code within an app that has a minSdkVersion of less than 11 and a targetSdkVersion of 11 or higher:

@TargetApi(11)
    public void refreshActionBarIfApi11OrHigher() {
      //If the API is 11 or higher, set up the actionBar and display it
      if(Build.VERSION.SDK_INT >= 11) {
        //ActionBar only exists at API level 11 or higher
        ActionBar actionBar = getActionBar();

        //This should cause onPrepareOptionsMenu() to be called.
        // In versions of the API prior to 11, this only occurred when the user pressed 
        // the dedicated menu button, but at level 11 and above, the action bar is 
        // typically displayed continuously and so you will need to call this
        // each time the options on your menu change.
        invalidateOptionsMenu();

        //Show the bar
        actionBar.show();
    }
}

You might also want to declare a higher targetSdkVersion if you had tested at that higher level and everything worked, even if you were not using any features from an API level higher than your minSdkVersion. This would be just to avoid the overhead of accessing compatibility code intended to adapt from the target level down to the min level, since you would have confirmed (through testing) that no such adaptation was required.

An example of a UI feature that depends upon the declared targetSdkVersion would be the three-vertical-dot menu button that appears on the status bar of apps having a targetSdkVersion less than 11, when those apps are running under API 11 and higher. If your app has a targetSdkVersion of 10 or below, it is assumed that your app's interface depends upon the existence of a dedicated menu button, and so the three-dot button appears to take the place of the earlier dedicated hardware and/or onscreen versions of that button (e.g., as seen in Gingerbread) when the OS has a higher API level for which a dedicated menu button on the device is no longer assumed. However, if you set your app's targetSdkVersion to 11 or higher, it is assumed that you have taken advantage of features introduced at that level that replace the dedicated menu button (e.g., the Action Bar), or that you have otherwise circumvented the need to have a system menu button; consequently, the three-vertical-dot menu "compatibility button" disappears. In that case, if the user can't find a menu button, she can't press it, and that, in turn, means that your activity's onCreateOptionsMenu(menu) override might never get invoked, which, again in turn, means that a significant part of your app's functionality could be deprived of its user interface. Unless, of course, you have implemented the Action Bar or some other alternative means for the user to access these features.

minSdkVersion, by contrast, states a requirement that a device's OS version have at least that API level in order to run your app. This affects which devices are able to see and download your app when it is on the Google Play app store (and possibly other app stores, as well). It's a way of stating that your app relies upon OS (API or other) features that were established at that level, and does not have an acceptable way to deal with the absence of those features.

An example of using minSdkVersion to ensure the presence of a feature that is not API-related would be to set minSdkVersion to 8 in order to ensure that your app will run only on a JIT-enabled version of the Dalvik interpreter (since JIT was introduced to the Android interpreter at API level 8). Since performance for a JIT-enabled interpreter can be as much as five times that of one lacking that feature, if your app makes heavy use of the processor then you might want to require API level 8 or above in order to ensure adequate performance.

Label axes on Seaborn Barplot

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:

enter image description here

JavaScript isset() equivalent

I always use this generic function to prevent errrors on primitive variables as well as arrays and objects.

isset = function(obj) {
  var i, max_i;
  if(obj === undefined) return false;
  for (i = 1, max_i = arguments.length; i < max_i; i++) {
    if (obj[arguments[i]] === undefined) {
        return false;
    }
    obj = obj[arguments[i]];
  }
  return true;
};

console.log(isset(obj));                   // returns false
var obj = 'huhu';
console.log(isset(obj));                   // returns true
obj = {hallo:{hoi:'hoi'}};
console.log(isset(obj, 'niet'));           // returns false
console.log(isset(obj, 'hallo'));          // returns true
console.log(isset(obj, 'hallo', 'hallo')); // returns false
console.log(isset(obj, 'hallo', 'hoi'));   // returns true

How do I use extern to share variables between source files?

An extern variable is a declaration (thanks to sbi for the correction) of a variable which is defined in another translation unit. That means the storage for the variable is allocated in another file.

Say you have two .c-files test1.c and test2.c. If you define a global variable int test1_var; in test1.c and you'd like to access this variable in test2.c you have to use extern int test1_var; in test2.c.

Complete sample:

$ cat test1.c 
int test1_var = 5;
$ cat test2.c
#include <stdio.h>

extern int test1_var;

int main(void) {
    printf("test1_var = %d\n", test1_var);
    return 0;
}
$ gcc test1.c test2.c -o test
$ ./test
test1_var = 5

How to listen for changes to a MongoDB collection?

After 3.6 one is allowed to use database the following database triggers types:

  • event-driven triggers - useful to update related documents automatically, notify downstream services, propagate data to support mixed workloads, data integrity & auditing
  • scheduled triggers - useful for scheduled data retrieval, propagation, archival and analytics workloads

Log into your Atlas account and select Triggers interface and add new trigger:

enter image description here

Expand each section for more settings or details.

How to send email from MySQL 5.1

I would be very concerned about putting the load of sending e-mails on my database server (small though it may be). I might suggest one of these alternatives:

  1. Have application logic detect the need to send an e-mail and send it.
  2. Have a MySQL trigger populate a table that queues up the e-mails to be sent and have a process monitor that table and send the e-mails.

How can you check for a #hash in a URL using JavaScript?

Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.

What most people seem to miss is that those same URL properties are also available to anchor elements:

// To process anchors on click    
jQuery('a').click(function () {
   if (this.hash) {
      // Clicked anchor has a hash
   } else {
      // Clicked anchor does not have a hash
   }
});

// To process anchors without waiting for an event
jQuery('a').each(function () {
   if (this.hash) {
      // Current anchor has a hash
   } else {
      // Current anchor does not have a hash
   }
});

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

pixels = np.array(pixels) in this line you reassign pixels. So, it may not a list anyhow. Though pixels is not a list it has no attributes append. Does it make sense?

type checking in javascript

You may also have a look on Runtyper - a tool that performs type checking of operands in === (and other operations).
For your example, if you have strict comparison x === y and x = 123, y = "123", it will automatically check typeof x, typeof y and show warning in console:

Strict compare of different types: 123 (number) === "123" (string)

How to write URLs in Latex?

You just need to escape characters that have special meaning: # $ % & ~ _ ^ \ { }

So

http://stack_overflow.com/~foo%20bar#link

would be

http://stack\_overflow.com/\~foo\%20bar\#link

Exception thrown inside catch block - will it be caught again?

Old post but "e" variable must be unique:

try {
  // Do something
} catch(IOException ioE) {
  throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
  // Will the ApplicationException be caught here?
}

Xcode source automatic formatting

That's Ctrl + i.

Or for low-tech, cut and then paste. It'll reformat on paste.

How to get the width and height of an android.widget.ImageView?

The simplest way is to get the width and height of an ImageView in onWindowFocusChanged method of the activity

 @Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);

    height = mImageView.getHeight();
    width = mImageView.getWidth();

}

H.264 file size for 1 hr of HD video

For a good quality x264 encoding of 1060i, done by a computer, not a mobile device, not in real time, you could use a bitrate at about 5 MBps. That means 2250 MB/hour of encoded material. Recommend you deinterlace the footage and compress as progressive.

CSS Box Shadow Bottom Only

You can use two elements, one inside the other, and give the outer one overflow: hidden and a width equal to the inner element together with a bottom padding so that the shadow on all the other sides are "cut off"

#outer {
    width: 100px;
    overflow: hidden;
    padding-bottom: 10px;
}

#outer > div {
    width: 100px;
    height: 100px;
    background: orange;

    -moz-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
}

Alternatively, float the outer element to cause it to shrink to the size of the inner element. See: http://jsfiddle.net/QJPd5/1/

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

Open button in new window?

If you strictly want to stick to using button,Then simply create an open window function as follows:

    <script>
function myfunction() {
    window.open("mynewpage.html");
}
</script>

Then in your html do the following with your button:

Join

So you would have something like this:

 <body>
    <script>
function joinfunction() {
    window.open("mynewpage.html");
}
</script>
<button  onclick="myfunction()" type="button" class="btn btn-default subs-btn">Join</button>

How to convert datatype:object to float64 in python?

You can convert most of the columns by just calling convert_objects:

In [36]:

df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[36]:
Date         object
WD            int64
Manpower    float64
2nd          object
CTR          object
2ndU        float64
T1            int64
T2          int64
T3           int64
T4        float64
dtype: object

For column '2nd' and 'CTR' we can call the vectorised str methods to replace the thousands separator and remove the '%' sign and then astype to convert:

In [39]:

df['2nd'] = df['2nd'].str.replace(',','').astype(int)
df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
df.dtypes
Out[39]:
Date         object
WD            int64
Manpower    float64
2nd           int32
CTR         float64
2ndU        float64
T1            int64
T2            int64
T3            int64
T4           object
dtype: object
In [40]:

df.head()
Out[40]:
        Date  WD  Manpower   2nd   CTR  2ndU   T1    T2   T3     T4
0   2013/4/6   6       NaN  2645  5.27  0.29  407   533  454    368
1   2013/4/7   7       NaN  2118  5.89  0.31  257   659  583    369
2  2013/4/13   6       NaN  2470  5.38  0.29  354   531  473    383
3  2013/4/14   7       NaN  2033  6.77  0.37  396   748  681    458
4  2013/4/20   6       NaN  2690  5.38  0.29  361   528  541    381

Or you can do the string handling operations above without the call to astype and then call convert_objects to convert everything in one go.

UPDATE

Since version 0.17.0 convert_objects is deprecated and there isn't a top-level function to do this so you need to do:

df.apply(lambda col:pd.to_numeric(col, errors='coerce'))

See the docs and this related question: pandas: to_numeric for multiple columns

Difference in boto3 between resource, client, and session?

Here's some more detailed information on what Client, Resource, and Session are all about.

Client:

  • low-level AWS service access
  • generated from AWS service description
  • exposes botocore client to the developer
  • typically maps 1:1 with the AWS service API
  • all AWS service operations are supported by clients
  • snake-cased method names (e.g. ListBuckets API => list_buckets method)

Here's an example of client-level access to an S3 bucket's objects (at most 1000**):

import boto3

client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
    obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
    print(content['Key'], obj_dict['LastModified'])

** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.

Resource:

  • higher-level, object-oriented API
  • generated from resource description
  • uses identifiers and attributes
  • has actions (operations on resources)
  • exposes subresources and collections of AWS resources
  • does not provide 100% API coverage of AWS services

Here's the equivalent example using resource-level access to an S3 bucket's objects (all):

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
    print(obj.key, obj.last_modified)

Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.

You can see that the Resource version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client version of the code would actually be more complicated than shown above if you wanted to include pagination.

Session:

  • stores configuration information (primarily credentials and selected region)
  • allows you to create service clients and resources
  • boto3 creates a default session for you when needed

A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.

jQuery - how can I find the element with a certain id?

I don't know if this solves your problem but instead of:

$("#tbIntervalos").find("td").attr("id", horaInicial);

you can just do:

$("#tbIntervalos td#" + horaInicial);

How to create and handle composite primary key in JPA

The MyKey class (@Embeddable) should not have any relationships like @ManyToOne

Accessing post variables using Java Servlets

Here's a simple example. I didn't get fancy with the html or the servlet, but you should get the idea.

I hope this helps you out.

<html>
<body>
<form method="post" action="/myServlet">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>

Now for the Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {

    String userName = request.getParameter("username");
    String password = request.getParameter("password");
    ....
    ....
  }
}

Camera access through browser

Update 11/2020: The Google Developer link is (currently) dead. The original article with a LOT more explanations can still be found at web.archive.org.


This question is already a few years old but in that time some additional possibilities have evolved, like accessing the camera directly, displaying a preview and capturing snapshots (e.g. for QR code scanning).

This Google Developers article provides an in-depth explaination of all (?) the ways how to get image/camera data into a web application, from "work everywhere" (even in desktop browsers) to "work only on modern, up-to-date mobile devices with camera". Along with many useful tips.

Explained methods:

  • Ask for a URL: Easiest but least satisfying.

  • File input (covered by most other posts here): The data can then be attached to a or manipulated with JavaScript by listening for an onchange event on the input element and then reading the files property of the event target.

<input type="file" accept="image/*" id="file-input">
<script>
  const fileInput = document.getElementById('file-input');

  fileInput.addEventListener('change', (e) => doSomethingWithFiles(e.target.files));
</script>

The files property is a FileList object.

  • Drag and drop (useful for desktop browsers):
<div id="target">You can drag an image file here</div>
<script>
  const target = document.getElementById('target');

  target.addEventListener('drop', (e) => {
    e.stopPropagation();
    e.preventDefault();

    doSomethingWithFiles(e.dataTransfer.files);
  });

  target.addEventListener('dragover', (e) => {
    e.stopPropagation();
    e.preventDefault();

    e.dataTransfer.dropEffect = 'copy';
  });
</script>

You can get a FileList object from the dataTransfer.files property of the drop event.

  • Paste from clipboard
<textarea id="target">Paste an image here</textarea>
<script>
  const target = document.getElementById('target');

  target.addEventListener('paste', (e) => {
    e.preventDefault();
    doSomethingWithFiles(e.clipboardData.files);
  });
</script>

e.clipboardData.files is a FileList object again.

  • Access the camera interactively (necessary if application needs to give instant feedback on what it "sees", like QR codes): Detect camera support with const supported = 'mediaDevices' in navigator; and prompt the user for consent. Then show a realtime preview and copy snapshots to a canvas.
<video id="player" controls autoplay></video>
<button id="capture">Capture</button>
<canvas id="canvas" width=320 height=240></canvas>
<script>
  const player = document.getElementById('player');
  const canvas = document.getElementById('canvas');
  const context = canvas.getContext('2d');
  const captureButton = document.getElementById('capture');

  const constraints = {
    video: true,
  };

  captureButton.addEventListener('click', () => {
    // Draw the video frame to the canvas.
    context.drawImage(player, 0, 0, canvas.width, canvas.height);
  });

  // Attach the video stream to the video element and autoplay.
  navigator.mediaDevices.getUserMedia(constraints)
    .then((stream) => {
      player.srcObject = stream;
    });
</script>

Don't forget to stop the video stream with

player.srcObject.getVideoTracks().forEach(track => track.stop());

Update 11/2020: The Google Developer link is (currently) dead. The original article with a LOT more explanations can still be found at web.archive.org.

format statement in a string resource file

Quote from Android Docs:

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

SQL Server : Arithmetic overflow error converting expression to data type int

Change SUM(billableDuration) AS NumSecondsDelivered to

sum(cast(billableDuration as bigint)) or

sum(cast(billableDuration as numeric(12, 0))) according to your need.

The resultant type of of Sum expression is the same as the data type used. It throws error at time of overflow. So casting the column to larger capacity data type and then using Sum operation works fine.

Python Pandas - Find difference between two data frames

Using the lambda function you can filter the rows with _merge value “left_only” to get all the rows in df1 which are missing from df2

df3 = df1.merge(df2, how = 'outer' ,indicator=True).loc[lambda x :x['_merge']=='left_only']
df

Excel telling me my blank cells aren't blank

A revelation: Some blank cells are not actually blank! As I will show cells can have spaces, newlines and true empty:

example

To find these cells quickly you can do a few things.

  1. The =CODE(A1) formula will return a #VALUE! if the cell is truly empty, otherwise a number will return. This number is the ASCII number used in =CHAR(32).
  2. If you select the cell and click in the formula bar and use the cursor to select all. newline selection example

Removing these:

If you only have a space in the cells these can be removed easily using:

  1. Press ctrl + h to open find and replace.
  2. Enter one space in the find what, leave replace with empty and ensure you have match entire cell contents is ticked in the options.
  3. Press replace all.

If you have newlines this is more difficult and requires VBA:

  1. Right click on the sheet tab > view code.
  2. Then enter the following code. Remember the Chr(10) is a newline only replace this as required, e.g. " " & Char(10) is a space and a newline:

    Sub find_newlines()
        With Me.Cells
            Set c = .Find(Chr(10), LookIn:=xlValues, LookAt:=xlWhole)
            If Not c Is Nothing Then
                firstAddress = c.Address
                Do
                    c.Value = ""
                    Set c = .FindNext(c)
                    If c Is Nothing Then Exit Do
                Loop While c.Address <> firstAddress
            End If
        End With
    End Sub
    
  3. Now run your code pressing F5.


After file supplied: Select the range of interest for improved performance, then run the following:

Sub find_newlines()
    With Selection
        Set c = .Find("", LookIn:=xlValues, LookAt:=xlWhole)
        If Not c Is Nothing Then
            firstAddress = c.Address
            Do
                c.Value = ""
                Set c = .FindNext(c)
                If c Is Nothing Then Exit Do
            Loop While c.Address <> firstAddress
        End If
    End With
End Sub

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

I recommend: Twisted (http://twistedmatrix.com)

an event-driven networking engine written in Python and licensed under the open source MIT license.

It's cross-platform and was preinstalled on OS X 10.5 to 10.12. Amongst other things you can start up a simple web server in the current directory with:

twistd -no web --path=.

Details

Explanation of Options (see twistd --help for more):

-n, --nodaemon       don't daemonize, don't use default umask of 0077
-o, --no_save        do not save state on shutdown

"web" is a Command that runs a simple web server on top of the Twisted async engine. It also accepts command line options (after the "web" command - see twistd web --help for more):

  --path=             <path> is either a specific file or a directory to be
                      set as the root of the web server. Use this if you
                      have a directory full of HTML, cgi, php3, epy, or rpy
                      files or any other files that you want to be served up
                      raw.

There are also a bunch of other commands such as:

conch            A Conch SSH service.
dns              A domain name server.
ftp              An FTP server.
inetd            An inetd(8) replacement.
mail             An email service
... etc

Installation

Ubuntu

sudo apt-get install python-twisted-web (or python-twisted for the full engine)

Mac OS-X (comes preinstalled on 10.5 - 10.12, or is available in MacPorts and through Pip)

sudo port install py-twisted

Windows

installer available for download at http://twistedmatrix.com/

HTTPS

Twisted can also utilise security certificates to encrypt the connection. Use this with your existing --path and --port (for plain HTTP) options.

twistd -no web -c cert.pem -k privkey.pem --https=4433

How to do vlookup and fill down (like in Excel) in R?

You could use mapvalues() from the plyr package.

Initial data:

dat <- data.frame(HouseType = c("Semi", "Single", "Row", "Single", "Apartment", "Apartment", "Row"))

> dat
  HouseType
1      Semi
2    Single
3       Row
4    Single
5 Apartment
6 Apartment
7       Row

Lookup / crosswalk table:

lookup <- data.frame(type_text = c("Semi", "Single", "Row", "Apartment"), type_num = c(1, 2, 3, 4))
> lookup
  type_text type_num
1      Semi        1
2    Single        2
3       Row        3
4 Apartment        4

Create the new variable:

dat$house_type_num <- plyr::mapvalues(dat$HouseType, from = lookup$type_text, to = lookup$type_num)

Or for simple replacements you can skip creating a long lookup table and do this directly in one step:

dat$house_type_num <- plyr::mapvalues(dat$HouseType,
                                      from = c("Semi", "Single", "Row", "Apartment"),
                                      to = c(1, 2, 3, 4))

Result:

> dat
  HouseType house_type_num
1      Semi              1
2    Single              2
3       Row              3
4    Single              2
5 Apartment              4
6 Apartment              4
7       Row              3

Get all object attributes in Python?

Use the built-in function dir().

How to return a specific element of an array?

Make sure return type of you method is same what you want to return. Eg: `

  public int get(int[] r)
  {
     return r[0];
  }

`

Note : return type is int, not int[], so it is able to return int.

In general, prototype can be

public Type get(Type[] array, int index)
{
    return array[index];
}

Python: avoid new line with print command

You simply need to do:

print 'lakjdfljsdf', # trailing comma

However in:

print 'lkajdlfjasd', 'ljkadfljasf'

There is implicit whitespace (ie ' ').

You also have the option of:

import sys
sys.stdout.write('some data here without a new line')

How to create a button programmatically?

override func viewDidLoad() {

super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150));
    var image = UIImage(named: "BattleMapSplashScreen.png");
    imageView.image = image;
    self.view.addSubview(imageView);

}

C error: undefined reference to function, but it IS defined

I had this issue recently. In my case, I had my IDE set to choose which compiler (C or C++) to use on each file according to its extension, and I was trying to call a C function (i.e. from a .c file) from C++ code.

The .h file for the C function wasn't wrapped in this sort of guard:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

I could've added that, but I didn't want to modify it, so I just included it in my C++ file like so:

extern "C" {
#include "legacy_C_header.h"
}

(Hat tip to UncaAlby for his clear explanation of the effect of extern "C".)

css rotate a pseudo :after or :before content:""

Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block or display: inline-block to transform them:

_x000D_
_x000D_
#whatever:after {
  content: "\24B6";
  display: inline-block;
  transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
_x000D_
_x000D_

Best Java obfuscator?

If a computer can run it, a suitably motivated human can reverse-engineer it.

Setting top and left CSS attributes

div.style yields an object (CSSStyleDeclaration). Since it's an object, you can alternatively use the following:

div.style["top"] = "200px";
div.style["left"] = "200px";

This is useful, for example, if you need to access a "variable" property:

div.style[prop] = "200px";

Show message box in case of exception

There are many ways, for example:

Method one:

public string test()
{
string ErrMsg = string.Empty;
 try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception ex)
    {
        ErrMsg = ex.Message;
    }
return ErrMsg
}

Method two:

public void test(ref string ErrMsg )
{

    ErrMsg = string.Empty;
     try
        {
            int num = int.Parse("gagw");
        }
        catch (Exception ex)
        {
            ErrMsg = ex.Message;
        }
}

What do numbers using 0x notation mean?

In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16).

Thus, 0x400 = 4×(162) + 0×(161) + 0×(160) = 4×((24)2) = 22 × 28 = 210 = 1024, or one binary K.

And so 0x6400 = 0x4000 + 0x2400 = 0x19×0x400 = 25K

jQuery get the name of a select option

The Code is very Simple, Lets Put This Code

var name = $("#band_type_choices  option:selected").text();

Here You don't want to use $(this).find().text(), directly you can put your id name and add option:selected along with text().

This will return the result option name. Better Try this...

How to get a vCard (.vcf file) into Android contacts from website

There is now an import functionality on Android ICS 4.0.4.

First you must save your .vcf file on a storage (USB storage, or SDcard). Android will scan the selected storage to detect any .vcf file and will import it on the selected address book. The functionality is in the option menu of your contact list.

!Note: Be careful while doing this! Android will import EVERYTHING that is a .vcf in your storage. It's all or nothing, and the consequence can be trashing your address book.

Error - is not marked as serializable

Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:

Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable

Due to a class with an attribute IEnumerable<int> eg:

[Serializable]
class MySessionData{
    public int ID;
    public IEnumerable<int> RelatedIDs; //This can be an issue
}

Originally the problem instance of MySessionData was set from a non-serializable list:

MySessionData instance = new MySessionData(){ 
    ID = 123,
    RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};

The cause here is the concrete class that the Select<int>(...) returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int> to resolve it.

RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();

Push method in React Hooks (useState)?

To expand a little further, here are some common examples. Starting with:

const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);

Push element at end of array

setTheArray(prevArray => [...prevArray, newValue])

Push/update element at end of object

setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));

Push/update element at end of array of objects

setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);

Push element at end of object of arrays

let specificArrayInObject = theObject.array.slice();
specificArrayInObject.push(newValue);
const newObj = { ...theObject, [event.target.name]: specificArrayInObject };
theObject(newObj);

Here are some working examples too. https://codesandbox.io/s/reacthooks-push-r991u

Redraw datatables after using ajax to refresh the table content?

Try destroying the datatable with bDestroy:true like this:

$("#ajaxchange").click(function(){
    var campaign_id = $("#campaigns_id").val();
    var fromDate = $("#from").val();
    var toDate = $("#to").val();

    var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
    $.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
            function( data ) { 

                $("#ajaxresponse").html(data);

                oTable6 = $('#rankings').dataTable( {"bDestroy":true,
                    "sDom":'t<"bottom"filp><"clear">',
                    "bAutoWidth": false,
                    "sPaginationType": "full_numbers",
"aoColumns": [ 
        { "bSortable": false, "sWidth": "10px" },
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null
        ]

} 
);
            });

});

bDestroy: true will first destroy and datatable instance associated with that selector before reinitializing a new one.

Merge Two Lists in R

If lists always have the same structure, as in the example, then a simpler solution is

mapply(c, first, second, SIMPLIFY=FALSE)

How to sort a Pandas DataFrame by index?

Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

Note:

How to set full calendar to a specific start date when it's initialized for the 1st time?

In version 2.1.1 this works :

$('#calendar').fullCalendar({
// your calendar settings...
});

$('#calendar').fullCalendar('gotoDate', '2014-05-01');

Documentation about moment time/date format : http://fullcalendar.io/docs/utilities/Moment/ Documentation about the upgrades in version 2 : https://github.com/arshaw/fullcalendar/wiki/Upgrading-to-v2

How to INNER JOIN 3 tables using CodeIgniter

it should be like that,

$this->db->select('*');    
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id');
$this->db->join('table3', 'table1.id = table3.id');
$query = $this->db->get();

as per CodeIgniters active record framework

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL...

For example,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

How to show current user name in a cell?

Without VBA macro, you can use this tips to get the username from the path :

=MID(INFO("DIRECTORY"),10,LEN(INFO("DIRECTORY"))-LEN(MID(INFO("DIRECTORY"),FIND("\",INFO("DIRECTORY"),10),1000))-LEN("C:\Users\"))

How to round to 2 decimals with Python?

Not sure why, but '{:0.2f}'.format(0.5357706) gives me '0.54'. The only solution that works for me (python 3.6) is the following:

def ceil_floor(x):
    import math
    return math.ceil(x) if x < 0 else math.floor(x)

def round_n_digits(x, n):
    import math
    return ceil_floor(x * math.pow(10, n)) / math.pow(10, n)

round_n_digits(-0.5357706, 2) -> -0.53 
round_n_digits(0.5357706, 2) -> 0.53

sql delete statement where date is greater than 30 days

You could also use

SELECT * from Results WHERE date < NOW() - INTERVAL 30 DAY;

Adding an .env file to React Project

Webpack Users

If you are using webpack, you can install and use dotenv-webpack plugin, to do that follow steps below:

Install the package

yarn add dotenv-webpack

Create a .env file

// .env
API_KEY='my secret api key'

Add it to webpack.config.js file

// webpack.config.js
const Dotenv = require('dotenv-webpack');

module.exports = {
  ...
  plugins: [
    new Dotenv()
  ]
  ...
};

Use it in your code as

process.env.API_KEY

For more information and configuration information, visit here

How to set the UITableView Section title programmatically (iPhone/iPad)?

Use the UITableViewDataSource method

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

How to update multiple columns in single update statement in DB2

For the sake of completeness and the edge case of wanting to update all columns of a row, you can do the following, but consider that the number and types of the fields must match.

Using a data structure

exec sql UPDATE TESTFILE
         SET ROW = :DataDs
         WHERE CURRENT OF CURSOR; //If using a cursor for update

Source: rpgpgm.com

SQL only

UPDATE t1 SET ROW = (SELECT *
                     FROM   t2
                     WHERE  t2.c3 = t1.c3)

Source: ibm.com

Adding options to a <select> using jQuery?

That works well.

If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.

How do I get the current mouse screen coordinates in WPF?

To follow up on Rachel's answer.
Here's two ways in which you can get Mouse Screen Coordinates in WPF.

1.Using Windows Forms. Add a reference to System.Windows.Forms

public static Point GetMousePositionWindowsForms()
{
    var point = Control.MousePosition;
    return new Point(point.X, point.Y);
}

2.Using Win32

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);

[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
    public Int32 X;
    public Int32 Y;
};
public static Point GetMousePosition()
{
    var w32Mouse = new Win32Point();
    GetCursorPos(ref w32Mouse);

    return new Point(w32Mouse.X, w32Mouse.Y);
}

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.

let's play a bit ;) :

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168,  58,   2,   1],  # uninitialized memory counts as random, too ?  fun ;) 
       [  0, 100,   2,   0, 101],
       [  0,   0, 106,   2,   0],
       [131,   2,   0,  90,   3],
       [  0, 100,   1,   0,  83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))         # normal
array([[  0,  76,   0, 129,   0],
       [  0,   0,   0, 188,  27],
       [  0, 152,   0,   0,   0],
       [  0,   0, 134,  79,   0],
       [  0, 181,  36, 128,   0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))         # uniform
array([[19, 53,  2, 86, 82],
       [86, 73, 40, 64, 78],
       [34, 20, 62, 80,  7],
       [24, 92, 37, 60, 72],
       [40, 12, 27, 33, 18]], dtype=uint8)

to apply it to an existing image, just generate noise in the desired range, and add it:

img = ...
noise = ...

image = img + noise

How to stop app that node.js express 'npm start'

If you've already tried ctrl + c and it still doesn't work, you might want to try this. This has worked for me.

  1. Run command-line as an Administrator. Then run the command below to find the processID (PID) you want to kill. Type your port number in <yourPortNumber>

    netstat -ano | findstr :<yourPortNumber>

enter image description here

  1. Then you execute this command after you have identified the PID.

    taskkill /PID <typeYourPIDhere> /F

enter image description here

Kudos to @mit $ingh from http://www.callstack.in/tech/blog/windows-kill-process-by-port-number-157

How to manually update datatables table with new JSON data

SOLUTION: (Notice: this solution is for datatables version 1.10.4 (at the moment) not legacy version).

CLARIFICATION Per the API documentation (1.10.15), the API can be accessed three ways:

  1. The modern definition of DataTables (upper camel case):

    var datatable = $( selector ).DataTable();

  2. The legacy definition of DataTables (lower camel case):

    var datatable = $( selector ).dataTable().api();

  3. Using the new syntax.

    var datatable = new $.fn.dataTable.Api( selector );

Then load the data like so:

$.get('myUrl', function(newDataArray) {
    datatable.clear();
    datatable.rows.add(newDataArray);
    datatable.draw();
});

Use draw(false) to stay on the same page after the data update.

API references:

https://datatables.net/reference/api/clear()

https://datatables.net/reference/api/rows.add()

https://datatables.net/reference/api/draw()

Difference between $(this) and event.target?

http://api.jquery.com/on/ states:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.)

To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

If we have

<input type="button" class="btn" value ="btn1">
<input type="button" class="btn" value ="btn2">
<input type="button" class="btn" value ="btn3">

<div id="outer">
    <input type="button"  value ="OuterB" id ="OuterB">
    <div id="inner">
        <input type="button" class="btn" value ="InnerB" id ="InnerB">
    </div>
</div>

Check the below output:

<script>
    $(function(){
        $(".btn").on("click",function(event){
            console.log($(this));
            console.log($(event.currentTarget));
            console.log($(event.target));
        });


        $("#outer").on("click",function(event){
            console.log($(this));
            console.log($(event.currentTarget));
            console.log($(event.target));
        })
    })
</script>

Note that I use $ to wrap the dom element in order to create a jQuery object, which is how we always do.

You would find that for the first case, this ,event.currentTarget,event.target are all referenced to the same element.

While in the second case, when the event delegate to some wrapped element are triggered, event.target would be referenced to the triggered element, while this and event.currentTarget are referenced to where the event is delivered.

For this and event.currentTarget, they are exactly the same thing according to http://api.jquery.com/event.currenttarget/

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

The solution is already answered here above (long ago).

But the implicit question "why does it work in FF and IE but not in Chrome and Safari" is found in the error text "Not allowed to load local resource": Chrome and Safari seem to use a more strict implementation of sandboxing (for security reasons) than the other two (at this time 2011).

This applies for local access. In a (normal) server environment (apache ...) the file would simply not have been found.

What is the difference between the dot (.) operator and -> in C++?

The -> is simply syntactic sugar for a pointer dereference,

As others have said:

pointer->method();

is a simple method of saying:

(*pointer).method();

For more pointer fun, check out Binky, and his magic wand of dereferencing:

http://www.youtube.com/watch?v=UvoHwFvAvQE

Retrieving a property of a JSON object by index?

You could iterate over the object and assign properties to indexes, like this:

var lookup = [];
var i = 0;

for (var name in obj) {
    if (obj.hasOwnProperty(name)) {
        lookup[i] = obj[name];
        i++;
    }
}

lookup[2] ...

However, as the others have said, the keys are in principle unordered. If you have code which depends on the corder, consider it a hack. Make sure you have unit tests so that you will know when it breaks.

Deleting a local branch with Git

You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.

Can Selenium WebDriver open browser windows silently in the background?

Use it ...

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)

Add timer to a Windows Forms application

Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html

Then add a button or something on the form and inside its event, just open this app ie:

{

Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");

}

Create a button with rounded border

If you don't want to use OutlineButton and want to stick to normal RaisedButton, you can wrap your button in ClipRRect or ClipOval like:

ClipRRect(
  borderRadius: BorderRadius.circular(40),
  child: RaisedButton(
    child: Text("Button"),
    onPressed: () {},
  ),
),

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

Angular 4.3 - HttpClient set params

Couple of Easy Alternatives

Without using HttpParams Objects

let body = {
   params : {
    'email' : emailId,
    'password' : password
   }
}

this.http.post(url, body);

Using HttpParams Objects

let body = new HttpParams({
  fromObject : {
    'email' : emailId,
    'password' : password
  }
})

this.http.post(url, body);

React Modifying Textarea Values

I think you want something along the line of:

Parent:

<Editor name={this.state.fileData} />

Editor:

var Editor = React.createClass({
  displayName: 'Editor',
  propTypes: {
    name: React.PropTypes.string.isRequired
  },
  getInitialState: function() { 
    return {
      value: this.props.name
    };
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function() {
    return (
      <form id="noter-save-form" method="POST">
        <textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
        <input type="submit" value="Save" />
      </form>
    );
  }
});

This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html

Update for React 16.8:

import React, { useState } from 'react';

const Editor = (props) => {
    const [value, setValue] = useState(props.name);

    const handleChange = (event) => {
        setValue(event.target.value);
    };

    return (
        <form id="noter-save-form" method="POST">
            <textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
            <input type="submit" value="Save" />
        </form>
    );
}

Editor.propTypes = {
    name: PropTypes.string.isRequired
};

Convert stdClass object to array in PHP

There are two simple ways to convert stdClass Object to an Array

$array = get_object_vars($obj);

and other is

$array = json_decode(json_encode($obj), true);

or you can simply create array using foreach loop

$array = array();
foreach($obj as $key){
    $array[] = $key;
}
print_r($array);