Programs & Examples On #Anonymous inner class

Anonymous Inner Classes are local classes that are declared and instantiated inline.

How are Anonymous inner classes used in Java?

Yes, anonymous inner classes is definitely one of the advantages of Java.

With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.

But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).

Remove 'standalone="yes"' from generated XML

You can use: marshaller.setProperty("jaxb.fragment", Boolean.TRUE);

It works for me on Java 8

Get first date of current month in java

Works Like a charm!

public static String  getCurrentMonthFirstDate(){
    Calendar c = Calendar.getInstance();   
    c.set(Calendar.DAY_OF_MONTH, 1);
    DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
    //System.out.println(df.format(c.getTime())); 
    return df.format(c.getTime());
}

//Correction :output =02-01-2018enter image description here

convert month from name to number

If you want number of month from string name then

$month = 'August';
$year = 2019;
echo date('m',strtotime($month.' '.$year));

Gives 08

Or If you want the Full name of the month then

echo date('F')

OR if you want the half name of the month then

echo date('M')

How to change root logging level programmatically for logback

using logback 1.1.3 I had to do the following (Scala code):

import ch.qos.logback.classic.Logger
import org.slf4j.LoggerFactory    
...
val root: Logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger]

Convert NaN to 0 in javascript

Using a double-tilde (double bitwise NOT) - ~~ - does some interesting things in JavaScript. For instance you can use it instead of Math.floor or even as an alternative to parseInt("123", 10)! It's been discussed a lot over the web, so I won't go in why it works here, but if you're interested: What is the "double tilde" (~~) operator in JavaScript?

We can exploit this property of a double-tilde to convert NaN to a number, and happily that number is zero!

console.log(~~NaN); // 0

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Rather than using Absolute path for IEDriverServer.exe, its better to use relative path in accordance to the project.

        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
        File fil = new File("iDrivers\\IEDriverServer.exe");
        System.setProperty("webdriver.ie.driver", fil.getAbsolutePath());
        WebDriver driver = new InternetExplorerDriver(capabilities);        
        driver.get("https://www.irctc.co.in");          

TCP vs UDP on video stream

Besides all the other reasons, UDP can use multicast. Supporting 1000s of TCP users all transmitting the same data wastes bandwidth. However, there is another important reason for using TCP.

TCP can much more easily pass through firewalls and NATs. Depending on your NAT and operator, you may not even be able to receive a UDP stream due to problems with UDP hole punching.

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Wait until page is loaded with Selenium WebDriver for Python

Have you tried driver.implicitly_wait. It is like a setting for the driver, so you only call it once in the session and it basically tells the driver to wait the given amount of time until each command can be executed.

driver = webdriver.Chrome()
driver.implicitly_wait(10)

So if you set a wait time of 10 seconds it will execute the command as soon as possible, waiting 10 seconds before it gives up. I've used this in similar scroll-down scenarios so I don't see why it wouldn't work in your case. Hope this is helpful.

To be able to fix this answer, I have to add new text. Be sure to use a lower case 'w' in implicitly_wait.

How to check the input is an integer or not in Java?

You can try this way

 String input = "";
 try {
   int x = Integer.parseInt(input); 
   // You can use this method to convert String to int, But if input 
   //is not an int  value then this will throws NumberFormatException. 
   System.out.println("Valid input");
 }catch(NumberFormatException e) {
   System.out.println("input is not an int value"); 
   // Here catch NumberFormatException
   // So input is not a int.
 } 

How to navigate through a vector using iterators? (C++)

In C++-11 you can do:

std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
{
   // access by value, the type of i is int
   std::cout << i << ' ';
}
std::cout << '\n';

See here for variations: https://en.cppreference.com/w/cpp/language/range-for

Javascript counting number of objects in object

The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either Lo-Dash or Underscore in your page.

Then you can use either _.size(object) or _.keys(object).length

For your obj.Data, you could test this with:

console.log( _.size(obj.Data) );

or:

console.log( _.keys(obj.Data).length );

Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)

Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:

function ObjectLength( object ) {
    var length = 0;
    for( var key in object ) {
        if( object.hasOwnProperty(key) ) {
            ++length;
        }
    }
    return length;
};

You can test this with:

console.log( ObjectLength(obj.Data) );

That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:

function ObjectLength_Modern( object ) {
    return Object.keys(object).length;
}

function ObjectLength_Legacy( object ) {
    var length = 0;
    for( var key in object ) {
        if( object.hasOwnProperty(key) ) {
            ++length;
        }
    }
    return length;
}

var ObjectLength =
    Object.keys ? ObjectLength_Modern : ObjectLength_Legacy;

and as before, test it with:

console.log( ObjectLength(obj.Data) );

This code uses Object.keys(object).length in modern browsers and falls back to counting in a loop for old browsers.

But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.

I set up a jsPerf that compares the speed of these various approaches. Please run it in any browsers you have handy to add to the tests.

Thanks to Barmar for suggesting Object.keys for newer browsers in his answer.

How to line-break from css, without using <br />?

Use overflow-wrap: break-word; like :

.yourelement{
overflow-wrap: break-word;
}

How to parse a JSON file in swift?

Swift 3

let parsedResult: [String: AnyObject]
do {      
    parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:AnyObject]       
} catch {        
    // Display an error or return or whatever
}

data - it's Data type (Structure) (i.e. returned by some server response)

Unable to start Service Intent

I hope I can help someone with this info as well: I moved my service class into another package and I fixed the references. The project was perfectly fine, BUT the service class could not be found by the activity.

By watching the log in logcat I noticed the warning about the issue: the activity could not find the service class, but the funny thing was that the package was incorrect, it contained a "/" char. The compiler was looking for

com.something./service.MyService

instead of

com.something.service.MyService

I moved the service class out from the package and back in and everything worked just fine.

Current time in microseconds in java

tl;dr

Java 9 and later: Up to nanoseconds resolution when capturing the current moment. That’s 9 digits of decimal fraction.

Instant.now()   

2017-12-23T12:34:56.123456789Z

To limit to microseconds, truncate.

Instant                // Represent a moment in UTC. 
.now()                 // Capture the current moment. Returns a `Instant` object. 
.truncatedTo(          // Lop off the finer part of this moment. 
    ChronoUnit.MICROS  // Granularity to which we are truncating. 
)                      // Returns another `Instant` object rather than changing the original, per the immutable objects pattern. 

2017-12-23T12:34:56.123456Z

In practice, you will see only microseconds captured with .now as contemporary conventional computer hardware clocks are not accurate in nanoseconds.

Details

The other Answers are somewhat outdated as of Java 8.

java.time

Java 8 and later comes with the java.time framework. These new classes supplant the flawed troublesome date-time classes shipped with the earliest versions of Java such as java.util.Date/.Calendar and java.text.SimpleDateFormat. The framework is defined by JSR 310, inspired by Joda-Time, extended by the ThreeTen-Extra project.

The classes in java.time resolve to nanoseconds, much finer than the milliseconds used by both the old date-time classes and by Joda-Time. And finer than the microseconds asked in the Question.

enter image description here

Clock Implementation

While the java.time classes support data representing values in nanoseconds, the classes do not yet generate values in nanoseconds. The now() methods use the same old clock implementation as the old date-time classes, System.currentTimeMillis(). We have the new Clock interface in java.time but the implementation for that interface is the same old milliseconds clock.

So you could format the textual representation of the result of ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) to see nine digits of a fractional second but only the first three digits will have numbers like this:

2017-12-23T12:34:56.789000000Z

New Clock In Java 9

The OpenJDK and Oracle implementations of Java 9 have a new default Clock implementation with finer granularity, up to the full nanosecond capability of the java.time classes.

See the OpenJDK issue, Increase the precision of the implementation of java.time.Clock.systemUTC(). That issue has been successfully implemented.

2017-12-23T12:34:56.123456789Z

On a MacBook Pro (Retina, 15-inch, Late 2013) with macOS Sierra, I get the current moment in microseconds (up to six digits of decimal fraction).

2017-12-23T12:34:56.123456Z

Hardware Clock

Remember that even with a new finer Clock implementation, your results may vary by computer. Java depends on the underlying computer hardware’s clock to know the current moment.

  • The resolution of the hardware clocks vary widely. For example, if a particular computer’s hardware clock supports only microseconds granularity, any generated date-time values will have only six digits of fractional second with the last three digits being zeros.
  • The accuracy of the hardware clocks vary widely. Just because a clock generates a value with several digits of decimal fraction of a second, those digits may be inaccurate, just approximations, adrift from actual time as might be read from an atomic clock. In other words, just because you see a bunch of digits to the right of the decimal mark does not mean you can trust the elapsed time between such readings to be true to that minute degree.

How to create a link to another PHP page

Just try like this:

HTML in PHP :

$link_address1 = 'index.php';
echo "<a href='".$link_address1."'>Index Page</a>";

$link_address2 = 'page2.php';
echo "<a href='".$link_address2."'>Page 2</a>";

Easiest way

$link_address1 = 'index.php';
echo "<a href='$link_address1'>Index Page</a>";

$link_address2 = 'page2.php';
echo "<a href='$link_address2'>Page 2</a>";

Mocking HttpClient in unit tests

One of my colleagues noticed that most of the HttpClient methods all call SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) under the hood, which is a virtual method off of HttpMessageInvoker:

So by far the easiest way to mock out HttpClient was to simply mock that particular method:

var mockClient = new Mock<HttpClient>();
mockClient.Setup(client => client.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>())).ReturnsAsync(_mockResponse.Object);

and your code can call most (but not all) of the HttpClient class methods, including a regular

httpClient.SendAsync(req)

Check here to confirm https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpClient.cs

How to evaluate a math expression given in string form?

You can also try the BeanShell interpreter:

Interpreter interpreter = new Interpreter();
interpreter.eval("result = (7+21*6)/(32-27)");
System.out.println(interpreter.get("result"));

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Capture keyboardinterrupt in Python without try-except

Yes, you can install an interrupt handler using the module signal, and wait forever using a threading.Event:

import signal
import sys
import time
import threading

def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
forever = threading.Event()
forever.wait()

Drawing a simple line graph in Java

Hovercraft Full Of Eels' answer is very good, but i had to change it a bit in order to get it working on my program:

int y1 = (int) ((this.height - 2 * BORDER_GAP) - (values.get(i) * yScale - BORDER_GAP));

instead of

int y1 = (int) (scores.get(i) * yScale + BORDER_GAP);

because if i used his way the graphic would be upside down

(you'd see it if you used hardcoded values (e.g 1,3,5,7,9) instead of random values)

When to catch java.lang.Error?

Ideally we should not handle/catch errors. But there may be cases where we need to do, based on requirement of framework or application. Say i have a XML Parser daemon which implements DOM Parser which consumes more Memory. If there is a requirement like Parser thread should not be died when it gets OutOfMemoryError, instead it should handle it and send a message/mail to administrator of application/framework.

"The import org.springframework cannot be resolved."

The only solution worked for me is add maven-compiler-plugin to the pom.xml

<project ...>
    ...
    <build>
        ...
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <fork>true</fork>
                    <executable>C:\Program Files\Java\jdk1.7.0_79\bin\javac</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>
    ...
</project>

LaTeX Optional Arguments

All of the above show hard it can be to make a nice, flexible (or forbid an overloaded) function in LaTeX!!! (that TeX code looks like greek to me)

well, just to add my recent (albeit not as flexible) development, here's what I've recently used in my thesis doc, with

\usepackage{ifthen}  % provides conditonals...

Start the command, with the "optional" command set blank by default:

\newcommand {\figHoriz} [4] []  {

I then have the macro set a temporary variable, \temp{}, differently depending on whether or not the optional argument is blank. This could be extended to any passed argument.

\ifthenelse { \equal {#1} {} }  %if short caption not specified, use long caption (no slant)
    { \def\temp {\caption[#4]{\textsl{#4}}} }   % if #1 == blank
    { \def\temp {\caption[#1]{\textsl{#4}}} }   % else (not blank)

Then I run the macro using the \temp{} variable for the two cases. (Here it just sets the short-caption to equal the long caption if it wasn't specified by the user).

\begin{figure}[!]
    \begin{center}
        \includegraphics[width=350 pt]{#3}
        \temp   %see above for caption etc.
        \label{#2}
    \end{center}
\end{figure}
}

In this case I only check for the single, "optional" argument that \newcommand{} provides. If you were to set it up for, say, 3 "optional" args, you'd still have to send the 3 blank args... eg.

\MyCommand {first arg} {} {} {}

which is pretty silly, I know, but that's about as far as I'm going to go with LaTeX - it's just not that sensical once I start looking at TeX code... I do like Mr. Robertson's xparse method though, perhaps I'll try it...

Adding onClick event dynamically using jQuery

try this approach if you know your object client name ( it is not important that it is Button or TextBox )

$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');

try this ones if you want add onClick event to a server object with JQuery

$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');

Display back button on action bar

Try this, In your onCreate()

 getActionBar().setHomeButtonEnabled(true);
 getActionBar().setDisplayHomeAsUpEnabled(true);

And for clickevent,

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; goto parent activity.
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

Should Jquery code go in header or footer?

Put Scripts at the Bottom

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.

An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

EDIT: Firefox does support the DEFER attribute since version 3.6.

Sources:

How to delete all the rows in a table using Eloquent?

Solution who works with Lumen 5.5 with foreign keys constraints :

$categories = MusicCategory::all();
foreach($categories as $category)
{
$category->delete();

}
return response()->json(['error' => false]);

Push Notifications in Android Platform

Here I have written few steps for How to Get RegID and Notification starting from scratch

  1. Create/Register App on Google Cloud
  2. Setup Cloud SDK with Development
  3. Configure project for GCM
  4. Get Device Registration ID
  5. Send Push Notifications
  6. Receive Push Notifications

You can find complete tutorial in below URL link

Getting Started with Android Push Notification : Latest Google Cloud Messaging (GCM) - step by step complete tutorial

enter image description here

Code snip to get Registration ID (Device Token for Push Notification).

Configure project for GCM


Update AndroidManifest file

For enable GCM in our project we need to add few permission in our manifest file Go to AndroidManifest.xml and add below code Add Permission

<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

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

<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

Add GCM Broadcast Receiver declaration

add GCM Broadcast Receiver declaration in your application tag

<application
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" ]]>
            <intent-filter]]>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="" />
            </intent-filter]]>

        </receiver]]>
     
<application/>

Add GCM Servie declaration

<application
     <service android:name=".GcmIntentService" />
<application/>

Get Registration ID (Device Token for Push Notification)

Now Go to your Launch/Splash Activity

Add Constants and Class Variables

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;

Update OnCreate and OnResume methods

@Override
protected void onCreate(Bundle savedInstanceState)
{
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_launch);
     context = getApplicationContext();
         if (checkPlayServices()) 
     {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(context);

            if (regid.isEmpty())
            {
                registerInBackground();
            }
            else
            {
            Log.d(TAG, "No valid Google Play Services APK found.");
            }
      }
 }

@Override protected void onResume()
{
       super.onResume();       checkPlayServices();
}


# Implement GCM Required methods (Add below methods in LaunchActivity)

private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.d(TAG, "This device is not supported - Google Play Services.");
                finish();
            }
            return false;
        }
        return true;
 }

private String getRegistrationId(Context context) 
{
   final SharedPreferences prefs = getGCMPreferences(context);
   String registrationId = prefs.getString(PROPERTY_REG_ID, "");
   if (registrationId.isEmpty()) {
       Log.d(TAG, "Registration ID not found.");
       return "";
   }
   int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
   int currentVersion = getAppVersion(context);
   if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

private SharedPreferences getGCMPreferences(Context context) 
{
    return getSharedPreferences(LaunchActivity.class.getSimpleName(),
                Context.MODE_PRIVATE);
}

private static int getAppVersion(Context context) 
{
     try 
     {
         PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
      } 
      catch (NameNotFoundException e) 
      {
            throw new RuntimeException("Could not get package name: " + e);
      }
}


private void registerInBackground() 
{     new AsyncTask() {
     Override
     protected Object doInBackground(Object... params) 
     {
          String msg = "";
          try 
          {
               if (gcm == null) 
               {
                        gcm = GoogleCloudMessaging.getInstance(context);
               }
               regid = gcm.register(SENDER_ID);               Log.d(TAG, "########################################");
               Log.d(TAG, "Current Device's Registration ID is: "+msg);     
          } 
          catch (IOException ex) 
          {
              msg = "Error :" + ex.getMessage();
          }
          return null;
     }     protected void onPostExecute(Object result) 
     { //to do here };
  }.execute(null, null, null);
}

Note : please store REGISTRATION_KEY, it is important for sending PN Message to GCM also keep in mine this will be unique for all device, by using this only GCM will send Push Notification.

Receive Push Notifications

Add GCM Broadcast Receiver Class

As we have already declared “GcmBroadcastReceiver.java” in our Manifest file, So lets create this class update receiver class code this way

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) 
    {        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
        Toast.makeText(context, “wow!! received new push notification", Toast.LENGTH_LONG).show();
    }
}

Add GCM Service Class

As we have already declared “GcmBroadcastReceiver.java” in our Manifest file, So lets create this class update receiver class code this way

public class GcmIntentService extends IntentService
{     public static final int NOTIFICATION_ID = 1;     private NotificationManager mNotificationManager;     private final static String TAG = "GcmIntentService";     public GcmIntentService() {
     super("GcmIntentService");     
     }     @Override
     protected void onHandleIntent(Intent intent) {
          Bundle extras = intent.getExtras();
          Log.d(TAG, "Notification Data Json :" + extras.getString("message"));

          GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
          String messageType = gcm.getMessageType(intent);          if (!extras.isEmpty()) {          if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
               .equals(messageType)) {
               sendNotification("Send error: " + extras.toString());
          } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
          .equals(messageType)) {
          sendNotification("Deleted messages on server: "
          + extras.toString());          // If it's a regular GCM message, do some work.
          } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
          .equals(messageType)) {
          // This loop represents the service doing some work.
          for (int i = 0; i < 5; i++) {
               Log.d(TAG," Working... " + (i + 1) + "/5 @ "
               + SystemClock.elapsedRealtime());               try {
                    Thread.sleep(5000);
               } catch (InterruptedException e) {
               }
             }
             Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
             sendNotification(extras.getString("message"));
           }
        }        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
     }     // Put the message into a notification and post it.
     // This is just one simple example of what you might choose to do with
     // a GCM message.
     private void sendNotification(String msg) {          mNotificationManager = (NotificationManager) this
          .getSystemService(Context.NOTIFICATION_SERVICE);
          PendingIntent contentIntent = PendingIntent.getActivity(this, 0,          new Intent(this, LaunchActivity.class), 0);

          NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(          this)
          .setSmallIcon(R.drawable.icon)
          .setContentTitle("Ocutag Snap")
          .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
          .setContentText(msg)
          .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

          mBuilder.setContentIntent(contentIntent);          mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
     }
}

Unable to add window -- token null is not valid; is your activity running?

You need to pass your activity in the constructor

 PopupWindow popupWindow = new PopupWindow(YourActivity.this)

How to insert multiple rows from array using CodeIgniter framework?

Use insert batch in codeigniter to insert multiple row of data.

$this->db->insert_batch('tabname',$data_array); // $data_array holds the value to be inserted

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

In order to not have the Cannot recover key exception, I had to apply the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files to the installation of Java that was running my application. Version 8 of those files can be found here or the latest version should be listed on this page. The download includes a file that explains how to apply the policy files.


Since JDK 8u151 it isn't necessary to add policy files. Instead the JCE jurisdiction policy files are controlled by a Security property called crypto.policy. Setting that to unlimited with allow unlimited cryptography to be used by the JDK. As the release notes linked to above state, it can be set by Security.setProperty() or via the java.security file. The java.security file could also be appended to by adding -Djava.security.properties=my_security.properties to the command to start the program as detailed here.


Since JDK 8u161 unlimited cryptography is enabled by default.

Create a new file in git bash

If you are using the Git Bash shell, you can use the following trick:

> webpage.html

This is actually the same as:

echo "" > webpage.html

Then, you can use git add webpage.html to stage the file.

Convert floating point number to a certain precision, and then copy to string

To set precision with 9 digits, get:

print "%.9f" % numvar

Return precision with 2 digits:

print "%.2f" % numvar 

Return precision with 2 digits and float converted value:

numvar = 4.2345
print float("%.2f" % numvar) 

How can I remove a substring from a given String?

replaceAll(String regex, String replacement)

Above method will help to get the answer.

String check = "Hello World";
check = check.replaceAll("o","");

When to use EntityManager.find() vs EntityManager.getReference() with JPA

Because a reference is 'managed', but not hydrated, it can also allow you to remove an entity by ID, without needing to load it into memory first.

As you can't remove an unmanaged entity, it's just plain silly to load all fields using find(...) or createQuery(...), only to immediately delete it.

MyLargeObject myObject = em.getReference(MyLargeObject.class, objectId);
em.remove(myObject);

How to get a substring of text?

Since you tagged it Rails, you can use truncate:

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate

Example:

 truncate(@text, :length => 17)

Excerpt is nice to know too, it lets you display an excerpt of a text Like so:

 excerpt('This is an example', 'an', :radius => 5)
 # => ...s is an exam...

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-excerpt

How to make <input type="file"/> accept only these types?

for powerpoint and pdf files:

<html>
<input type="file" placeholder="Do you have a .ppt?" name="pptfile" id="pptfile" accept="application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/vnd.openxmlformats-officedocument.presentationml.presentation"/>
</html>

Bootstrap 4, How do I center-align a button?

Here is the full HTML that I use to center by button in Bootsrap form after closing form-group:

<div class="form-row text-center">
    <div class="col-12">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
 </div>

Send data from a textbox into Flask?

All interaction between server(your flask app) and client(browser) going by request and response. When user hit button submit in your form his browser send request with this form to your server (flask app), and you can get content of the form like:

request.args.get('form_name')

How to read all files in a folder from Java?

nice usage of java.io.FileFilter as seen on https://stackoverflow.com/a/286001/146745

File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {          
    public boolean accept(File file) {
        return file.isFile();
    }
});

Onclick event to remove default value in a text input field

You actually want to show a placeholder, HTML 5 offer this feature and it's very sweet !

Try this out :

<input name="Name" placeholder="Enter Your Name">

Log4Net configuring log level

Yes. It is done with a filter on the appender.

Here is the appender configuration I normally use, limited to only INFO level.

<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="${HOMEDRIVE}\\PI.Logging\\PI.ECSignage.${COMPUTERNAME}.log" />
  <appendToFile value="true" />
  <maxSizeRollBackups value="30" />
  <maximumFileSize value="5MB" />
  <rollingStyle value="Size" />     <!--A maximum number of backup files when rolling on date/time boundaries is not supported. -->
  <staticLogFileName value="false" />
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss.ffff} [%2thread] %-5level %20.20type{1}.%-25method at %-4line| (%-30.30logger) %message%newline" />
  </layout>

  <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="INFO" />
        <levelMax value="INFO" />
  </filter>
</appender>    

Android Eclipse - Could not find *.apk

On my machine (Windows7, 64bit) I could fix this by setting my execution environment to a 32bit variant of the jdk (I used 1.6.0_23). And I tried a lot of things before...

How can I detect when an Android application is running in the emulator?

This code works for me

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tm.getNetworkOperatorName();
if("Android".equals(networkOperator)) {
    // Emulator
}
else {
    // Device
}

In case that device does not have sim card, It retuns empty string:""

Since Android emulator always retuns "Android" as network operator, I use above code.

Explode string by one or more spaces or tabs

@OP it doesn't matter, you can just split on a space with explode. Until you want to use those values, iterate over the exploded values and discard blanks.

$str = "A      B      C      D";
$s = explode(" ",$str);
foreach ($s as $a=>$b){    
    if ( trim($b) ) {
     print "using $b\n";
    }
}

Empty set literal?

No, there's no literal syntax for the empty set. You have to write set().

How to select the last record from MySQL table using SQL syntax

You could also do something like this:

SELECT tb1.* FROM Table tb1 WHERE id = (SELECT MAX(tb2.id) FROM Table tb2);

Its useful when you want to make some joins.

Why dict.get(key) instead of dict[key]?

A gotcha to be aware of when using .get():

If the dictionary contains the key used in the call to .get() and its value is None, the .get() method will return None even if a default value is supplied.

For example, the following returns None, not 'alt_value' as may be expected:

d = {'key': None}
assert None is d.get('key', 'alt_value')

.get()'s second value is only returned if the key supplied is NOT in the dictionary, not if the return value of that call is None.

How do you store Java objects in HttpSession?

The request object is not the session.

You want to use the session object to store. The session is added to the request and is were you want to persist data across requests. The session can be obtained from

HttpSession session = request.getSession(true);

Then you can use setAttribute or getAttribute on the session.

A more up to date tutorial on jsp sessions is: http://courses.coreservlets.com/Course-Materials/pdf/csajsp2/08-Session-Tracking.pdf

Center Align on a Absolutely Positioned Div

If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:

div#wrapper {
    position: absolute;
    width: 100%;
    text-align: center;
}

Remember that in order to position an element absolutely, the parent element must be positioned relatively.

How do I compare a value to a backslash?

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):
    do_stuff()

How to align form at the center of the page in html/css

Or you can just use the <center></center> tags.

Creating a list/array in excel using VBA to get a list of unique names in a column

I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.

Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes

Convert XML to JSON (and back) using Javascript

I think this is the best one: Converting between XML and JSON

Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit.

"installation of package 'FILE_PATH' had non-zero exit status" in R

The .zip file provided by the authors is not a valid R package, and they do state that the source is for "direct use" in R (by which I assume they mean it's necessary to load the included functions manually). The non-zero exit status simply indicates that there was an error during the installation of the "package".

You can extract the archive manually and then load the functions therein with, e.g., source('bivpois.table.R'), or you can download the .RData file they provide and load that into the workspace with load('.RData'). This does not install the functions as part of a package; rather, it loads the functions into your global environment, making them temporarily available.

You can download, extract, and load the .RData from R as follows:

download.file('http://stat-athens.aueb.gr/~jbn/papers/files/14/14_bivpois_RDATA.zip', 
              f <- tempfile())
unzip(f, exdir=tempdir())
load(file.path(tempdir(), '.RData'))

If you want the .RData file to be available in the current working directory, to be loaded in the future, you could use the following instead:

download.file('http://stat-athens.aueb.gr/~jbn/papers/files/14/14_bivpois_RDATA.zip', 
              f <- tempfile())
unzip(f, exdir=tempdir())
file.copy(file.path(tempdir(), '.RData'), 'bivpois.RData')
# the above copies the .RData file to a file called bivpois.RData in your current 
# working directory.
load('bivpois.RData')

In future R sessions, you can just call load('bivpois.RData').

Differentiate between function overloading and function overriding

Overloading means having methods with same name but different signature Overriding means rewriting the virtual method of the base class.............

What is the difference between Step Into and Step Over in a debugger

step into will dig into method calls
step over will just execute the line and go to the next one

Getting results between two dates in PostgreSQL

Looking at the dates for which it doesn't work -- those where the day is less than or equal to 12 -- I'm wondering whether it's parsing the dates as being in YYYY-DD-MM format?

VBA: Conditional - Is Nothing

In my sample code, I was setting my object to nothing, and I couldn't get the "not" part of the if statement to work with the object. I tried if My_Object is not nothing and also if not My_Object is nothing. It may be just a syntax thing I can't figure out but I didn't have time to mess around, so I did a little workaround like this:

if My_Object is Nothing Then
    'do nothing
Else
    'Do something
End if

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How to filter a data frame

You are missing a comma in your statement.

Try this:

data[data[, "Var1"]>10, ]

Or:

data[data$Var1>10, ]

Or:

subset(data, Var1>10)

As an example, try it on the built-in dataset, mtcars

data(mtcars)

mtcars[mtcars[, "mpg"]>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2


mtcars[mtcars$mpg>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

subset(mtcars, mpg>25)

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

Does adding a duplicate value to a HashSet/HashMap replace the previous value

The first thing you need to know is that HashSet acts like a Set, which means you add your object directly to the HashSet and it cannot contain duplicates. You just add your value directly in HashSet.

However, HashMap is a Map type. That means every time you add an entry, you add a key-value pair.

In HashMap you can have duplicate values, but not duplicate keys. In HashMap the new entry will replace the old one. The most recent entry will be in the HashMap.

Understanding Link between HashMap and HashSet:

Remember, HashMap can not have duplicate keys. Behind the scene HashSet uses a HashMap.

When you attempt to add any object into a HashSet, this entry is actually stored as a key in the HashMap - the same HashMap that is used behind the scene of HashSet. Since this underlying HashMap needs a key-value pair, a dummy value is generated for us.

Now when you try to insert another duplicate object into the same HashSet, it will again attempt to be insert it as a key in the HashMap lying underneath. However, HashMap does not support duplicates. Hence, HashSet will still result in having only one value of that type. As a side note, for every duplicate key, since the value generated for our entry in HashSet is some random/dummy value, the key is not replaced at all. it will be ignored as removing the key and adding back the same key (the dummy value is the same) would not make any sense at all.

Summary:

HashMap allows duplicate values, but not keys. HashSet cannot contains duplicates.

To play with whether the addition of an object is successfully completed or not, you can check the boolean value returned when you call .add() and see if it returns true or false. If it returned true, it was inserted.

img src SVG changing the styles with CSS

You will first have to inject the SVG into the HTML DOM.

There is an open source library called SVGInject that does this for you. It uses the onload attribute to trigger the injection.

Here is a minimal example using SVGInject:

<html>
  <head>
    <script src="svg-inject.min.js"></script>
  </head>
  <body>
    <img src="image.svg" onload="SVGInject(this)" />
  </body>
</html>

After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the SVG file provided in the src attribute.

It solves several issues with SVG injection:

  1. SVGs can be hidden until injection has finished. This is important if a style is already applied during load time, which would otherwise cause a brief "unstyled content flash".

  2. The <img> elements inject themselves automatically. If you add SVGs dynamically, you don't have to worry about calling the injection function again.

  3. A random string is added to each ID in the SVG to avoid having the same ID multiple times in the document if an SVG is injected more than once.

SVGInject is plain Javascript and works with all browsers that support SVG.

Disclaimer: I am the co-author of SVGInject

SpringMVC RequestMapping for GET parameters

This will get ALL parameters from the request. For Debugging purposes only:

@RequestMapping (value = "/promote", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView renderPromotePage (HttpServletRequest request) {
    Map<String, String[]> parameters = request.getParameterMap();

    for(String key : parameters.keySet()) {
        System.out.println(key);
        String[] vals = parameters.get(key);
        for(String val : vals)
            System.out.println(" -> " + val);
    }

    ModelAndView mv = new ModelAndView();
    mv.setViewName("test");
    return mv;
}

How to use curl in a shell script?

Firstly, your example is looking quite correct and works well on my machine. You may go another way.

curl $CURLARGS $RVMHTTP > ./install.sh

All output now storing in ./install.sh file, which you can edit and execute.

Remove substring from the string

If you are using Rails there's also remove.

E.g. "Testmessage".remove("message") yields "Test".

Warning: this method removes all occurrences

Laravel 5.4 create model, controller and migration in single artisan command

How I was doing it until now:

php artisan make:model Customer
php artisan make:controller CustomersController --resource

Apparently, there’s a quicker way:

php artisan make:controller CustomersController --model=Customer

RegEx to exclude a specific string constant

This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:

$var !~ /^foo$/
    or die "too much foo";

If not, you have to do something evil:

$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
    or die "too much foo";

That one basically says "if it starts with non-f, the rest can be anything; if it starts with f, non-o, the rest can be anything; otherwise, if it starts fo, the next character had better not be another o".

what is the difference between OLE DB and ODBC data sources?

According to ADO: ActiveX Data Objects, a book by Jason T. Roff, published by O'Reilly Media in 2001 (excellent diagram here), he says precisely what MOZILLA said.

(directly from page 7 of that book)

  • ODBC provides access only to relational databases
  • OLE DB provides the following features
    • Access to data regardless of its format or location
    • Full access to ODBC data sources and ODBC drivers

So it would seem that OLE DB interacts with SQL-based datasources THRU the ODBC driver layer.

alt text

I'm not 100% sure this image is correct. The two connections I'm not certain about are ADO.NET thru ADO C-api, and OLE DB thru ODBC to SQL-based data source (because in this diagram the author doesn't put OLE DB's access thru ODBC, which I believe is a mistake).

Auto expand a textarea using jQuery

I just built this function to expand textareas on pageload. Just change each to keyup and it will occur when the textarea is typed in.

// On page-load, auto-expand textareas to be tall enough to contain initial content
$('textarea').each(function(){
    var pad = parseInt($(this).css('padding-top'));
    if ($.browser.mozilla) 
        $(this).height(1);
    var contentHeight = this.scrollHeight;
    if (!$.browser.mozilla) 
        contentHeight -= pad * 2;
    if (contentHeight > $(this).height()) 
        $(this).height(contentHeight);
});

Tested in Chrome, IE9 and Firefox. Unfortunately Firefox has this bug which returns the incorrect value for scrollHeight, so the above code contains a (hacky) workaround for it.

Could not load file or assembly 'System.Data.SQLite'

As someone who's had to deal with quite a few bug reports on Roadkill Wiki with exactly the same issue, this is what you need to do:

  • Are you using x64 or x86? Sqlite comes with DLLs for separate architectures - copy the right one to your bin folder, there are two DLLS for the official provider: System.Data.SQLite.dll System.Data.SQLite.Linq.dll
  • If you can't be bothered hunting around for these assemblies, enable 32 bit mode for your App Pool (a solution for dev machines only usually)
  • If you're hosting on a server, you'll need the Microsoft C++ Runtime redistributable - it's not installed on Server 2008 R2 by default. x64 version, x86 version

It's a real pain in the ass how many hoops you have to jump through when re-distributing the SQLite .NET binaries, my solution for Roadkill in the end was to copy the correct binaries to the ~/bin folder based on the architecture your using. Unfortunately that doesn't solve the C++ runtime issue.

How do I get the latest version of my code?

Case 1: Don’t care about local changes

  • Solution 1: Get the latest code and reset the code

    git fetch origin
    git reset --hard origin/[tag/branch/commit-id usually: master]
    
  • Solution 2: Delete the folder and clone again :D

    rm -rf [project_folder]
    git clone [remote_repo]
    

Case 2: Care about local changes

  • Solution 1: no conflicts with new-online version

    git fetch origin
    git status
    

    will report something like:

    Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
    

    Then get the latest version

    git pull
    
  • Solution 2: conflicts with new-online version

    git fetch origin
    git status
    

    will report something like:

    error: Your local changes to the following files would be overwritten by merge:
        file_name
    Please, commit your changes or stash them before you can merge.
    Aborting
    

    Commit your local changes

    git add .
    git commit -m ‘Commit msg’
    

    Try to get the changes (will fail)

    git pull
    

    will report something like:

    Pull is not possible because you have unmerged files.
    Please, fix them up in the work tree, and then use 'git add/rm <file>'
    as appropriate to mark resolution, or use 'git commit -a'.
    

    Open the conflict file and fix the conflict. Then:

    git add .
    git commit -m ‘Fix conflicts’
    git pull
    

    will report something like:

    Already up-to-date.
    

More info: How do I use 'git reset --hard HEAD' to revert to a previous commit?

Input length must be multiple of 16 when decrypting with padded cipher

This is a very old question, but my answer may help someone.

  • In the encrypt method, don't forget to encode your string to Base64
  • In the decrypt method, don't forget to decode your string to Base64

Below is the working code

    import java.util.Arrays;
    import java.util.Base64;

    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    public class EncryptionDecryptionUtil {

    public static String encrypt(final String secret, final String data) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while encrypting data", e);
        }

    }

    public static String decrypt(final String secret,
            final String encryptedString) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.DECRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
            return new String(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while decrypting data", e);
        }
    }


    public static void main(String[] args) {

        String data = "This is not easy as you think";
        String key = "---------------------------------";
        String encrypted = encrypt(key, data);
        System.out.println(encrypted);
        System.out.println(decrypt(key, encrypted));
      }
  }

For Generating Key you can use below class

    import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SecretKeyGenerator {

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

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

        SecureRandom secureRandom = new SecureRandom();
        int keyBitSize = 256;
        keyGenerator.init(keyBitSize, secureRandom);

        SecretKey secretKey = keyGenerator.generateKey();

 System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
    }

}

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

execute below

Python manage.py makemigrations

It will show missing package.

Install missing package and again run below command to make sure if nothing is missed.

Python manage.py makemigrations

It will resolve your issue.

Convert varchar to uniqueidentifier in SQL Server

your varchar col C:

SELECT CONVERT(uniqueidentifier,LEFT(C, 8)
                                + '-' +RIGHT(LEFT(C, 12), 4)
                                + '-' +RIGHT(LEFT(C, 16), 4)
                                + '-' +RIGHT(LEFT(C, 20), 4)
                                + '-' +RIGHT(C, 12))

compare two files in UNIX

I got the solution by using comm

comm -23 file1 file2 

will give you the desired output.

The files need to be sorted first anyway.

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

More Pythonic Way to Run a Process X Times

There is not a really pythonic way of repeating something. However, it is a better way:

map(lambda index:do_something(), xrange(10))

If you need to pass the index then:

map(lambda index:do_something(index), xrange(10))

Consider that it returns the results as a collection. So, if you need to collect the results it can help.

How to detect online/offline event cross-browser?

In HTML5 you can use the navigator.onLine property. Look here:

http://www.w3.org/TR/offline-webapps/#related

Probably your current behavior is random as the javascript only ready the "browser" variable and then knows if you're offline and online, but it doesn't actually check the Network Connection.

Let us know if this is what you're looking for.

Kind Regards,

Where is the user's Subversion config file stored on the major operating systems?

~/.subversion/config or /etc/subversion/config

for Mac/Linux

and

%appdata%\subversion\config

for Windows

"The system cannot find the file specified"

Server Error in '/' Application.

The system cannot find the file specified

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified

Source Error:

     {
                   SqlCommand cmd = new SqlCommand("select * from tblemployee",con);
                   con.Open();
                   GridView1.DataSource = cmd.ExecuteReader();
                   GridView1.DataBind();

Source File: d:\C# programs\kudvenkat\adobasics1\adobasics1\employeedata.aspx.cs Line: 23

if your error is same like mine..just do this

right click on your table in sqlserver object explorer,choose properties in lower left corner in general option there is a connection block with server and connection specification.in your web config for datasource=. or local choose name specified in server in properties..

How do I convert a Swift Array to a String?

Swift 3

["I Love","Swift"].joined(separator:" ") // previously joinWithSeparator(" ")

jquery draggable: how to limit the draggable area?

Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV

buildDraggable = function() {
    $( "#handle" ).draggable({
    containment: '#thumbnail',
    drag: function(event) {
        var top = $(this).position().top;
        var left = $(this).position().left;

        ICZoom.panImage(top, left);
    },
});

Reading Excel file using node.js

There are a few different libraries doing parsing of Excel files (.xlsx). I will list two projects I find interesting and worth looking into.

Node-xlsx

Excel parser and builder. It's kind of a wrapper for a popular project JS-XLSX, which is a pure javascript implementation from the Office Open XML spec.

node-xlsx project page

Example for parsing file

var xlsx = require('node-xlsx');

var obj = xlsx.parse(__dirname + '/myFile.xlsx'); // parses a file

var obj = xlsx.parse(fs.readFileSync(__dirname + '/myFile.xlsx')); // parses a buffer

ExcelJS

Read, manipulate and write spreadsheet data and styles to XLSX and JSON. It's an active project. At the time of writing the latest commit was 9 hours ago. I haven't tested this myself, but the api looks extensive with a lot of possibilites.

exceljs project page

Code example:

// read from a file
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
    .then(function() {
        // use workbook
    });

// pipe from stream
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());

how to get program files x86 env variable?

On a 64-bit Windows system, the reading of the various environment variables and some Windows Registry keys is redirected to different sources, depending whether the process doing the reading is 32-bit or 64-bit.

The table below lists these data sources:

X = HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion
Y = HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion
Z = HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
     
READING ENVIRONMENT VARIABLES:    Source for 64-bit process               Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
                %ProgramFiles% :  X\ProgramW6432Dir                       X\ProgramFilesDir (x86)
           %ProgramFiles(x86)% :  X\ProgramFilesDir (x86)                 X\ProgramFilesDir (x86)
                %ProgramW6432% :  X\ProgramW6432Dir                       X\ProgramW6432Dir
     
          %CommonProgramFiles% :  X\CommonW6432Dir                        X\CommonFilesDir (x86)
     %CommonProgramFiles(x86)% :  X\CommonFilesDir (x86)                  X\CommonFilesDir (x86)
          %CommonProgramW6432% :  X\CommonW6432Dir                        X\CommonW6432Dir
     
                 %ProgramData% :  Z\ProgramData                           Z\ProgramData


      READING REGISTRY VALUES:    Source for 64-bit process               Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
             X\ProgramFilesDir :  X\ProgramFilesDir                       Y\ProgramFilesDir
       X\ProgramFilesDir (x86) :  X\ProgramFilesDir (x86)                 Y\ProgramFilesDir (x86)
            X\ProgramFilesPath :  X\ProgramFilesPath = %ProgramFiles%     Y\ProgramFilesPath = %ProgramFiles(x86)%
             X\ProgramW6432Dir :  X\ProgramW6432Dir                       Y\ProgramW6432Dir
     
              X\CommonFilesDir :  X\CommonFilesDir                        Y\CommonFilesDir
        X\CommonFilesDir (x86) :  X\CommonFilesDir (x86)                  Y\CommonFilesDir (x86)
              X\CommonW6432Dir :  X\CommonW6432Dir                        Y\CommonW6432Dir
     

So for example, for a 32-bit process, the source of the data for the %ProgramFiles% and %ProgramFiles(x86)% environment variables is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86).

However, for a 64-bit process, the source of the data for the %ProgramFiles% environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir ...and the source of the data for the %ProgramFiles(x86)% environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)

Most default Windows installation put a string like C:\Program Files (x86) into the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86) but this (and others) can be changed.

Whatever is entered into these Windows Registry values will be read by Windows Explorer into respective Environment Variables upon login and then copied to any child process that it subsequently spawns.

The registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesPath is especially noteworthy because most Windows installations put the string %ProgramFiles% into it, to be read by 64-bit processes. This string refers to the environment variable %ProgramFiles% which in turn, takes its data from the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir ...unless some program changes the value of this environment variable apriori.

I have written a small utility, which displays these environment variables for 64-bit and 32-bit processes. You can download it here.
The source code for VisualStudio 2017 is included and the compiled 64-bit and 32-bit binary executables are in the directories ..\x64\Release and ..\x86\Release, respectively.

How to grep recursively, but only in files with certain extensions?

Just use the --include parameter, like this:

grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]

that should do what you want.

To take the explanation from HoldOffHunger's answer below:

  • grep: command

  • -r: recursively

  • -i: ignore-case

  • -n: each output line is preceded by its relative line number in the file

  • --include \*.cpp: all *.cpp: C++ files (escape with \ just in case you have a directory with asterisks in the filenames)

  • ./: Start at current directory.

Use -notlike to filter out multiple strings in PowerShell

I think Peter has the right idea. I would use a regular expression for this along with the -notmatch operator.

Get-EventLog Security | ?{$_.Username -notmatch '^user1$|^.*user$'}

Split (explode) pandas dataframe string entry to separate rows

Just used jiln's excellent answer from above, but needed to expand to split multiple columns. Thought I would share.

def splitDataFrameList(df,target_column,separator):
''' df = dataframe to split,
target_column = the column containing the values to split
separator = the symbol used to perform the split

returns: a dataframe with each entry for the target column separated, with each element moved into a new row. 
The values in the other columns are duplicated across the newly divided rows.
'''
def splitListToRows(row, row_accumulator, target_columns, separator):
    split_rows = []
    for target_column in target_columns:
        split_rows.append(row[target_column].split(separator))
    # Seperate for multiple columns
    for i in range(len(split_rows[0])):
        new_row = row.to_dict()
        for j in range(len(split_rows)):
            new_row[target_columns[j]] = split_rows[j][i]
        row_accumulator.append(new_row)
new_rows = []
df.apply(splitListToRows,axis=1,args = (new_rows,target_column,separator))
new_df = pd.DataFrame(new_rows)
return new_df

Can a PDF file's print dialog be opened with Javascript?

I usually do something similar to the approach given by How to Use JavaScript to Print a PDF (eHow.com), using an iframe.

  1. a function to house the print trigger...

    function printTrigger(elementId) {
        var getMyFrame = document.getElementById(elementId);
        getMyFrame.focus();
        getMyFrame.contentWindow.print();
    }
    
  2. an button to give the user access...

    (an onClick on an a or button or input or whatever you wish)

    <input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
    
  3. an iframe pointing to your PDF...

    <iframe id="iFramePdf" src="myPdfUrl.pdf" style="display:none;"></iframe>
    

Bonus Idea #1 - Create the iframe and add it to your page within the printTrigger(); so that the PDF isn't loaded until the user clicks your "Print" button, then the javascript can attack! the iframe and trigger the print dialog.


Bonus Idea #2 - Extra credit if you disable your "Print" button and give the user a little loading spinner or something after they click it, so that they know something's in process instead of clicking it repeatedly!

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

Setting PasswordAuthentication to yes, is not the best way to go , is not as secure as using private and public keys for authentication !

First make sure that that you have the fallowing permissions set, on the server side.

First check your home dir (SERVER SIDE)

[vini@random ~]$ ls -ld ~

drwx------. 3 vini vini 127 Nov 23 15:29 /home/vini

if it is not like this, run

chmod 0700 /home/your_home

Now check .ssh folder

[vini@random ~]$ ls -ld  /home/vini/.ssh/

drwx------. 2 vini vini 29 Nov 23 15:28 /home/vini/.ssh/

if it is not looking like this, run

chmod 0700 /home/your_home/.ssh

now make sure that authorized_keys looks like this

[vini@venon ~]$ ls -ld  /home/vini/.ssh/authorized_keys 

-rw-------. 1 vini vini 393 Nov 23 15:28 /home/vini/.ssh/authorized_keys

or just run

chmod 0600 /home/your_home/.ssh/authorized_keys

After that go to /etc/ssh/sshd_config

For best security set

PermitRootLogin no

PubkeyAuthentication yes

keep as yes for testing purposes

PasswordAuthentication yes

Make sure that

ChallengeResponseAuthentication no

Comment those lines for GSSAPI

# #GSSAPIAuthentication yes
# #GSSAPICleanupCredentials no

Make sure that is set to UsePAM yes

UsePAM yes

now restart sshd service

systemctl restart sshd 

on the client side

cd /home/your_home/.ssh

generate new keys; setting a password is optional but is a good idea

ssh-keygen -t rsa -b 2048  

copy pub key to your server

ssh-copy-id -i id_rsa.pub user_name@server_ip 

start ssh agent 

eval $(ssh-agent)

ssh-add /home/user/.ssh/your_private_key

now your are good to go !

ssh user_name@server_ip

if everything works just fine

make a backup of your private key and then deny PasswordAuthentication

PasswordAuthentication no 

Restart you server

now anyone trying to ssh into your server, without your keys should get

vini@random: Permission denied (publickey).

keep script kids away from your business, and good luck

java how to use classes in other package?

Given your example, you need to add the following import in your main.main class:

import second.second;

Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:

package main;  //lowercase package names
public class Main //titlecase class names
{
    //Main class content
}

How to quit a java app from within the program

System.exit(0);

The "0" lets whomever called your program know that everything went OK. If, however, you are quitting due to an error, you should System.exit(1);, or with another non-zero number corresponding to the specific error.

Also, as others have mentioned, clean up first! That involves closing files and other open resources.

Show animated GIF

public class aiubMain {
public static void main(String args[]) throws MalformedURLException{
    //home frame = new home();
    java.net.URL imgUrl2 = home.class.getResource("Campus.gif");

Icon icon = new ImageIcon(imgUrl2);
JLabel label = new JLabel(icon);

JFrame f = new JFrame("Animation");
f.getContentPane().add(label);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

CodeIgniter - File upload required validation

CodeIgniter file upload optionally ...works perfectly..... :)

---------- controller ---------

function file()
{
 $this->load->view('includes/template', $data);
}

function valid_file()
{
 $this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');

 if ($this->form_validation->run()==FALSE) 
 {
    $this->file();
 }
 else
 {
  $config['upload_path']   = './documents/';
  $config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
  $config['max_size']      = '1000';
  $config['max_width']     = '1024';
  $config['max_height']    = '768';

  $this->load->library('upload', $config);

  if ( !$this->upload->do_upload('userfile',FALSE))
  {
    $this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());

    if($_FILES['userfile']['error'] != 4)
    {
        return false;
    }

  }
  else
  {
    return true;
  }
}

i just use this lines which makes it optionally,

if($_FILES['userfile']['error'] != 4)
{
 return false;
}

$_FILES['userfile']['error'] != 4 is for file required to upload.

you can make it unnecessary by using $_FILES['userfile']['error'] != 4, then it will pass this error for file required and works great with other types of errors if any by using return false , hope it works for u ....

How do I perform the SQL Join equivalent in MongoDB?

There is a specification that a lot of drivers support that's called DBRef.

DBRef is a more formal specification for creating references between documents. DBRefs (generally) include a collection name as well as an object id. Most developers only use DBRefs if the collection can change from one document to the next. If your referenced collection will always be the same, the manual references outlined above are more efficient.

Taken from MongoDB Documentation: Data Models > Data Model Reference > Database References

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

A checkbox has a linked cell, which contains the True/False representing the state of the checkbox. It is much easier to reference this cell's value than the value of the embedded object which is the checkbox.

Manually: Right click on the checkbox, choose Format, click in the Linked Cell box, and select the cell to contain the checkbox value.

In code:

Set cbTime = ActiveSheet.CheckBoxes.Add(100, 100, 50, 15)
With cbTime
    .Value = xlOff ' = unchecked  xlOn = checked
    .LinkedCell = "$A$1"
End With

How to use placeholder as default value in select2 framework

You have to add an empty option (i.e. <option></option>) as a first element to see a placeholder.

From Select2 official documentation :

"Note that because browsers assume the first option element is selected in non-multi-value select boxes an empty first option element must be provided (<option></option>) for the placeholder to work."

Hope this helps.

Example:

<select id="countries">
    <option></option>
    <option value="1">Germany</option>
    <option value="2">France</option>
    <option value="3">Spain</option>
</select>

and the Javascript would be:

$('#countries').select2({
    placeholder: "Please select a country"
});

how to measure running time of algorithms in python

I am not 100% sure what is meant by "running times of my algorithms written in python", so I thought I might try to offer a broader look at some of the potential answers.

  • Algorithms don't have running times; implementations can be timed, but an algorithm is an abstract approach to doing something. The most common and often the most valuable part of optimizing a program is analyzing the algorithm, usually using asymptotic analysis and computing the big O complexity in time, space, disk use and so forth.

    A computer cannot really do this step for you. This requires doing the math to figure out how something works. Optimizing this side of things is the main component to having scalable performance.

  • You can time your specific implementation. The nicest way to do this in Python is to use timeit. The way it seems most to want to be used is to make a module with a function encapsulating what you want to call and call it from the command line with python -m timeit ....

    Using timeit to compare multiple snippets when doing microoptimization, but often isn't the correct tool you want for comparing two different algorithms. It is common that what you want is asymptotic analysis, but it's possible you want more complicated types of analysis.

  • You have to know what to time. Most snippets aren't worth improving. You need to make changes where they actually count, especially when you're doing micro-optimisation and not improving the asymptotic complexity of your algorithm.

    If you quadruple the speed of a function in which your code spends 1% of the time, that's not a real speedup. If you make a 20% speed increase on a function in which your program spends 50% of the time, you have a real gain.

    To determine the time spent by a real Python program, use the stdlib profiling utilities. This will tell you where in an example program your code is spending its time.

maximum value of int

Why not write a piece of code like:

int  max_neg = ~(1 << 31);
int  all_ones = -1;
int max_pos = all_ones & max_neg;

How to manually trigger click event in ReactJS?

Here is the Hooks solution

    import React, {useRef} from 'react';

    const MyComponent = () =>{

    const myRefname= useRef(null);

    const handleClick = () => {
        myRefname.current.focus();
     }

    return (
      <div onClick={handleClick}>
        <input ref={myRefname}/>
      </div>
     );
    }

Differences between "java -cp" and "java -jar"?

When using java -cp you are required to provide fully qualified main class name, e.g.

java -cp com.mycompany.MyMain

When using java -jar myjar.jar your jar file must provide the information about main class via manifest.mf contained into the jar file in folder META-INF:

Main-Class: com.mycompany.MyMain

How do I make a "div" button submit the form its sitting in?

To keep the scripting in one place rather than using onClick in the HTML tag, add the following code to your script block:

$('#id-of-the-button').click(function() {document.forms[0].submit()});

Which assumes you just have the one form on the page.

How to symbolicate crash log Xcode?

Follow these steps in Xcode 10 to symbolicate a crash log from an app build on the same machine:

  1. Inside Organizer, locate the archive where the app is based on.
  2. Click on the Download Debug Symbols button. Nothing will appear in your Downloads folder, but that's OK.
  3. Connect the build machine to an iOS device.
  4. Select the device in Devices and Simulators.
  5. Click on the View Devices Logs button.
  6. Drag-and-drop the crash file to the left panel. The file must end with a .crash extension, otherwise the drag fails.
  7. Switch to the All Logs tab.
  8. Select the added crash file.
  9. The file should automatically symbolicate, otherwise use the right-click context menu item Re-Symbolicate Log.

How to run shell script on host from docker container?

That REALLY depends on what you need that bash script to do!

For example, if the bash script just echoes some output, you could just do

docker run --rm -v $(pwd)/mybashscript.sh:/mybashscript.sh ubuntu bash /mybashscript.sh

Another possibility is that you want the bash script to install some software- say the script to install docker-compose. you could do something like

docker run --rm -v /usr/bin:/usr/bin --privileged -v $(pwd)/mybashscript.sh:/mybashscript.sh ubuntu bash /mybashscript.sh

But at this point you're really getting into having to know intimately what the script is doing to allow the specific permissions it needs on your host from inside the container.

Webdriver findElements By xpath

The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.

or

To explicitly do this in XPath, you'd be looking at:

(//div[@id='container'])[1]

for the first one, for the second etc:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:

//div[@id='container']/parent::*

That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:

(//div[@id='container'])[1]/parent::*

Hope that helps!

Count the number of occurrences of a string in a VARCHAR field?

In SQL SERVER, this is the answer

Declare @t table(TITLE VARCHAR(100), DESCRIPTION VARCHAR(100))

INSERT INTO @t SELECT 'test1', 'value blah blah value' 
INSERT INTO @t SELECT 'test2','value test' 
INSERT INTO @t SELECT 'test3','test test test' 
INSERT INTO @t SELECT 'test4','valuevaluevaluevaluevalue' 


SELECT TITLE,DESCRIPTION,Count = (LEN(DESCRIPTION) - LEN(REPLACE(DESCRIPTION, 'value', '')))/LEN('value') 

FROM @t

Result

TITLE   DESCRIPTION               Count
test1   value blah blah value        2
test2   value test                   1
test3   test test test               0
test4   valuevaluevaluevaluevalue    5

I don't have MySQL install, but goggled to find the Equivalent of LEN is LENGTH while REPLACE is same.

So the equivalent query in MySql should be

SELECT TITLE,DESCRIPTION, (LENGTH(DESCRIPTION) - LENGTH(REPLACE(DESCRIPTION, 'value', '')))/LENGTH('value') AS Count
FROM <yourTable>

Please let me know if it worked for you in MySql also.

List of tables, db schema, dump etc using the Python sqlite3 API

If someone wants to do the same thing with Pandas

import pandas as pd
import sqlite3
conn = sqlite3.connect("db.sqlite3")
table = pd.read_sql_query("SELECT name FROM sqlite_master WHERE type='table'", conn)
print(table)

Using Java 8 to convert a list of objects into a string obtained from the toString() method

StringListName = ObjectListName.stream().map( m -> m.toString() ).collect( Collectors.toList() );

How can I catch an error caused by mail()?

According to http://php.net/manual/en/function.error-get-last.php, use:

print_r(error_get_last());

Which will return an array of the last error generated. You can access the [message] element to display the error.

Eclipse 3.5 Unable to install plugins

i fought with eclipse 3.5.0 (galileo) for days, i had to use this version because I am doing blackberry development and eclipse comes bundle with blackberry specifics so i need to use the package they bundled, which was not 3.5.0 (not the 3.5.1) , BUT SirFabel saved the day, thanks to all who contributed to this post

I used 3.5.0 and did "Set the following system property in you eclipse.ini file: -Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient For more details on this: wiki.eclipse.org/… - Configure only the HTTP and HTTPS proxies. Not SOCKS!! "

and I am able to get through my companies proxy!!!!

TLS 1.2 in .NET Framework 4.0

I meet the same issue on a Windows installed .NET Framework 4.0.
And I Solved this issue by installing .NET Framework 4.6.2.
Or you may download the newest package to have a try.

How do I copy directories recursively with gulp?

If you want to copy the entire contents of a folder recursively into another folder, you can execute the following windows command from gulp:

xcopy /path/to/srcfolder /path/to/destfolder /s /e /y

The /y option at the end is to suppress the overwrite confirmation message.

In Linux, you can execute the following command from gulp:

cp -R /path/to/srcfolder /path/to/destfolder

you can use gulp-exec or gulp-run plugin to execute system commands from gulp.

Related Links:

  1. xcopy usage

  2. gulp-exec and gulp-run

jQuery: Setting select list 'selected' based on text, failing strangely

When an <option> isn't given a value="", the text becomes its value, so you can just use .val() on the <select> to set by value, like this:

var text1 = 'Monkey';
$("#mySelect1").val(text1);

var text2 = 'Mushroom pie';
$("#mySelect2").val(text2);

You can test it out here, if the example is not what you're after and they actually have a value, use the <option> element's .text property to .filter(), like this:

var text1 = 'Monkey';
$("#mySelect1 option").filter(function() {
    return this.text == text1; 
}).attr('selected', true);

var text2 = 'Mushroom pie';
$("#mySelect2 option").filter(function() {
    return this.text == text2; 
}).attr('selected', true);?

You can test that version here.

DECODE( ) function in SQL Server

Create a function in SQL Server as below and replace the DECODE with dbo.DECODE

CREATE FUNCTION DECODE(@CondField as nvarchar(100),@Criteria as nvarchar(100), 
                       @True Value as nvarchar(100), @FalseValue as nvarchar(100))
returns nvarchar(100)
begin
       return case when @CondField = @Criteria then @TrueValue 
                   else @FalseValue end
end

How to use TLS 1.2 in Java 6

I think that the solution of @Azimuts (https://stackoverflow.com/a/33375677/6503697) is for HTTP only connection. For FTPS connection you can use Bouncy Castle with org.apache.commons.net.ftp.FTPSClient without the need for rewrite FTPS protocol.

I have a program running on JRE 1.6.0_04 and I can not update the JRE.

The program has to connect to an FTPS server that work only with TLS 1.2 (IIS server).

I struggled for days and finally I have understood that there are few versions of bouncy castle library right in my use case: bctls-jdk15on-1.60.jar and bcprov-jdk15on-1.60.jar are ok, but 1.64 versions are not.

The version of apache commons-net is 3.1 .

Following is a small snippet of code that should work:

import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.security.Security;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider;
import org.junit.Test;


public class FtpsTest {

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
    }

    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
    }
} };

@Test public void test() throws Exception {


    Security.insertProviderAt(new BouncyCastleProvider(), 1);
    Security.addProvider(new BouncyCastleJsseProvider());


    SSLContext sslContext = SSLContext.getInstance("TLS", new BouncyCastleJsseProvider());
    sslContext.init(null, trustAllCerts, new SecureRandom());
    org.apache.commons.net.ftp.FTPSClient ftpClient = new FTPSClient(sslContext);
    ByteArrayOutputStream out = null;
    try {

        ftpClient.connect("hostaname", 21);
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            String msg = "Il server ftp ha rifiutato la connessione.";
            throw new Exception(msg);
        }
        if (!ftpClient.login("username", "pwd")) {
            String msg = "Il server ftp ha rifiutato il login con username:  username  e pwd:  password  .";
            ftpClient.disconnect();
            throw new Exception(msg);
        }


        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.setDataTimeout(60000);
        ftpClient.execPBSZ(0); // Set protection buffer size
        ftpClient.execPROT("P"); // Set data channel protection to private
        int bufSize = 1024 * 1024; // 1MB
        ftpClient.setBufferSize(bufSize);
        out = new ByteArrayOutputStream(bufSize);
        ftpClient.retrieveFile("remoteFileName", out);
        out.toByteArray();
    }
    finally {
        if (out != null) {
            out.close();
        }
        ftpClient.disconnect();

    }

}

}

Can I set the height of a div based on a percentage-based width?

This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.

Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:

_x000D_
_x000D_
$(function() {_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
});
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):

_x000D_
_x000D_
$(window).ready(updateHeight);_x000D_
$(window).resize(updateHeight);_x000D_
_x000D_
function updateHeight()_x000D_
{_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
}
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

keycode and charcode

It is a conditional statement.

If browser supprts e.keyCode then take e.keyCode else e.charCode.

It is similar to

var code = event.keyCode || event.charCode

event.keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event.

event.charCode: Returns the Unicode value of a character key pressed during a keypress event.

The Android emulator is not starting, showing "invalid command-line parameter"

emulator-arm.exe error, couldn't run. Problem was that my laptop has 2 graphic cards and was selected only one (the performance one) from Nvidia 555M. By selecting the other graphic card from Nvidia mediu,(selected base Intel card) the emulator started!

What is the return value of os.system() in Python?

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

00000000    00000000
exit code   signal num

Example 1 - command exit with code 1

os.system('command') #it returns 256
256 in 16 bits -  00000001 00000000
Exit code is 00000001 which means 1

Example 2 - command exit with code 3

os.system('command') # it returns 768
768 in 16 bits  - 00000011 00000000
Exit code is 00000011 which means 3

Now try with signal - Example 3 - Write a program which sleep for long time use it as command in os.system() and then kill it by kill -15 or kill -9

os.system('command') #it returns signal num by which it is killed
15 in bits - 00000000 00001111
Signal num is 00001111 which means 15

You can have a python program as command = 'python command.py'

import sys
sys.exit(n)  # here n would be exit code

In case of c or c++ program you can use return from main() or exit(n) from any function #

Note - This is applicable on unix

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

os.wait()

Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

Availability: Unix

.

git: fatal unable to auto-detect email address

I'm running Ubuntu through Windows Subsystem for Linux and had properly set my credentials through Git Bash, including in VS Code's terminal (where I was getting the error every time I tried to commit.)

Apparently even tho VS is using Bash in the terminal, the UI git controls still run through Windows, where I had not set my credentials.

Setting the credentials in Windows Powershell fixed the issue

How to get a subset of a javascript object's properties

TypeScript solution:

function pick<T extends object, U extends keyof T>(
  obj: T,
  paths: Array<U>
): Pick<T, U> {
  const ret = Object.create(null);
  for (const k of paths) {
    ret[k] = obj[k];
  }
  return ret;
}

The typing information even allows for auto-completion:

Credit to DefinitelyTyped for U extends keyof T trick!

TypeScript Playground

Keyboard shortcuts with jQuery

I recently wrote a standalone library for this. It does not require jQuery, but you can use it with jQuery no problem. It's called Mousetrap.

You can check it out at http://craig.is/killing/mice

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

The error message proved to be true as Apache Ant isn't in the path of Mac OS X Mavericks anymore.

Bulletproof solution:

  1. Download and install Homebrew by executing following command in terminal:

    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

  2. Install Apache Ant via Homebrew by executing

    brew install ant

Run the PhoneGap build again and it should successfully compile and install your Android app.

getMinutes() 0-9 - How to display two digit numbers?

.length is undefined because getMinutes is returning a number, not a string. numbers don't have a length property. You could do

var m = "" + date.getMinutes();

to make it a string, then check the length (you would want to check for length === 1, not 0).

Meaning of @classmethod and @staticmethod for beginner?

One would use @classmethod when he/she would want to change the behaviour of the method based on which subclass is calling the method. remember we have a reference to the calling class in a class method.

While using static you would want the behaviour to remain unchanged across subclasses

Example:

class Hero:

  @staticmethod
  def say_hello():
     print("Helllo...")

  @classmethod
  def say_class_hello(cls):
     if(cls.__name__=="HeroSon"):
        print("Hi Kido")
     elif(cls.__name__=="HeroDaughter"):
        print("Hi Princess")

class HeroSon(Hero):
  def say_son_hello(self):
     print("test  hello")



class HeroDaughter(Hero):
  def say_daughter_hello(self):
     print("test  hello daughter")


testson = HeroSon()

testson.say_class_hello() #Output: "Hi Kido"

testson.say_hello() #Outputs: "Helllo..."

testdaughter = HeroDaughter()

testdaughter.say_class_hello() #Outputs: "Hi Princess"

testdaughter.say_hello() #Outputs: "Helllo..."

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Sadly none of the solutions worked for me! I solved my problem by uninstalling existing APK from my phone and it all started working perfectly!

This started happening after I've updated android studio to latest version.

How to calculate percentage when old value is ZERO

How to deal with Zeros when calculating percentage changes is the researcher's call and requires some domain expertise. If the researcher believes that it would not be distorting the data, s/he may simply add a very small constant to all values to get rid of all zeros. In financial series, when dealing with trading volume, for example, we may not want to do this because trading volume = 0 just means that: the asset did not trade at all. The meaning of volume = 0 may be very different from volume = 0.00000000001. This is my preferred strategy in cases whereby I can not logically add a small constant to all values. Consider the percentage change formula ((New-Old)/Old) *100. If New = 0, then percentage change would be -100%. This number indeed makes financial sense as long as it is the minimum percentage change in the series (This is indeed guaranteed to be the minimum percentage change in the series). Why? Because it shows that trading volume experiences maximum possible decrease, which is going from any number to 0, -100%. So, I'll be fine with this value being in my percentage change series. If I normalize that series, then even better since this (possibly) relatively big number in absolute value will be analyzed on the same scale as other variables are. Now, what if the Old value = 0. That's a trickier case. Percentage change due to going from 0 to 1 will be equal to that due to going from 0 to a million: infinity. The fact that we call both "infinity" percentage change is problematic. In this case, I would set the infinities equal to np.nan and interpolate them.

The following graph shows what I discussed above. Starting from series 1, we get series 4, which is ready to be analyzed, with no Inf or NaNs.

enter image description here

One more thing: a lot of the time, the reason for calculating percentage change is to stationarize the data. So, if your original series contains zero and you wish to convert it to percentage change to achieve stationarity, first make sure it is not already stationary. Because if it is, you don't have to calculate percentage change. The point is that series that take the value of 0 a lot (the problem OP has) are very likely to be already stationary, for example the volume series I considered above. Imagine a series oscillating above and below zero, thus hitting 0 at times. Such a series is very likely already stationary.

RVM is not a function, selecting rubies with 'rvm use ...' will not work

For me in Ubuntu(18.08), I have added below line in .bashrc and it works.

 source /home/username/.rvm/scripts/rvm

Please add this line.

Setting Margin Properties in code

One would guess that (and my WPF is a little rusty right now) that Margin takes an object and cannot be directly changed.

e.g

MyControl.Margin = new Margin(10,0,0,0);

How can I set focus on an element in an HTML form using JavaScript?

If your <input> or <textarea> has attribute id=mytext then use

mytext.focus();

_x000D_
_x000D_
function setFocusToTextBox() {_x000D_
    mytext.focus();_x000D_
}
_x000D_
<body onload='setFocusToTextBox()'>_x000D_
  <form>_x000D_
    <input type="text" id="mytext"/>_x000D_
  </form>_x000D_
</body>
_x000D_
_x000D_
_x000D_

What is the iPad user agent?

It's worth noting that when running in web-app mode (using the apple-mobile-web-app-capable meta tag) the user agent changes from:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B405 Safari/531.21.10

to:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405

Converting string to Date and DateTime

You need to be careful with m/d/Y and m-d-Y formats. PHP considers / to mean m/d/Y and - to mean d-m-Y. I would explicitly describe the input format in this case:

$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');

That way you are not at the whims of a certain interpretation.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

This appears to be a problem with the way mac is handling reading the /etc/hosts file. See for example http://youtrack.jetbrains.com/issue/IDEA-96865

Adding the hostname to the hosts file as bond described should not be required, but it does solve the problem.

Jump to function definition in vim

Use ctags. Generate a tags file, and tell vim where it is using the :tags command. Then you can just jump to the function definition using Ctrl-]

There are more tags tricks and tips in this question.

How to split a line into words separated by one or more spaces in bash?

s='foo bar baz'
a=( $s )
echo ${a[0]}
echo ${a[1]}
...

How to call a web service from jQuery

You can make an AJAX request like any other requests:

$.ajax( {
type:'Get',
url:'http://mysite.com/mywebservice',
success:function(data) {
 alert(data);
}

})

Docker container not starting (docker start)

You are trying to run bash, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d, but you can do this by adding -it to the command line, which ensures that the container has a valid tty associated with it and that stdin remains connected:

docker run -it -d -p 52022:22 basickarl/docker-git-test

You would more commonly run some sort of long-lived non-interactive process (like sshd, or a web server, or a database server, or a process manager like systemd or supervisor) when starting detached containers.

If you are trying to run a service like sshd, you cannot simply run service ssh start. This will -- depending on the distribution you're running inside your container -- do one of two things:

  • It will try to contact a process manager like systemd or upstart to start the service. Because there is no service manager running, this will fail.

  • It will actually start sshd, but it will be started in the background. This means that (a) the service sshd start command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.

If you want to run just ssh in a container, consider an example like this.

If you want to run sshd and other processes inside the container, you will need to investigate some sort of process supervisor.

How do I base64 encode (decode) in C?

I needed C++ implementation working on std::string. None of answers satisfied my needs, I needed simple two-function solution for encoding and decoding, but I was too lazy to write my own code, so I found this:

http://www.adp-gmbh.ch/cpp/common/base64.html

Credits for code go to René Nyffenegger.

Putting the code below in case the site goes down:

base64.cpp

/* 
   base64.cpp and base64.h

   Copyright (C) 2004-2008 René Nyffenegger

   This source code is provided 'as-is', without any express or implied
   warranty. In no event will the author be held liable for any damages
   arising from the use of this software.

   Permission is granted to anyone to use this software for any purpose,
   including commercial applications, and to alter it and redistribute it
   freely, subject to the following restrictions:

   1. The origin of this source code must not be misrepresented; you must not
      claim that you wrote the original source code. If you use this source code
      in a product, an acknowledgment in the product documentation would be
      appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and must not be
      misrepresented as being the original source code.

   3. This notice may not be removed or altered from any source distribution.

   René Nyffenegger [email protected]

*/

#include "base64.h"
#include <iostream>

static const std::string base64_chars = 
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";


static inline bool is_base64(unsigned char c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];

  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';

  }

  return ret;

}

std::string base64_decode(std::string const& encoded_string) {
  int in_len = encoded_string.size();
  int i = 0;
  int j = 0;
  int in_ = 0;
  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = base64_chars.find(char_array_4[i]);

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = base64_chars.find(char_array_4[j]);

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  }

  return ret;
}

base64.h

#include <string>

std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);

Usage

const std::string s = "test";
std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length());
  std::string decoded = base64_decode(encoded);

How do I remove repeated elements from ArrayList?

Probably a bit overkill, but I enjoy this kind of isolated problem. :)

This code uses a temporary Set (for the uniqueness check) but removes elements directly inside the original list. Since element removal inside an ArrayList can induce a huge amount of array copying, the remove(int)-method is avoided.

public static <T> void removeDuplicates(ArrayList<T> list) {
    int size = list.size();
    int out = 0;
    {
        final Set<T> encountered = new HashSet<T>();
        for (int in = 0; in < size; in++) {
            final T t = list.get(in);
            final boolean first = encountered.add(t);
            if (first) {
                list.set(out++, t);
            }
        }
    }
    while (out < size) {
        list.remove(--size);
    }
}

While we're at it, here's a version for LinkedList (a lot nicer!):

public static <T> void removeDuplicates(LinkedList<T> list) {
    final Set<T> encountered = new HashSet<T>();
    for (Iterator<T> iter = list.iterator(); iter.hasNext(); ) {
        final T t = iter.next();
        final boolean first = encountered.add(t);
        if (!first) {
            iter.remove();
        }
    }
}

Use the marker interface to present a unified solution for List:

public static <T> void removeDuplicates(List<T> list) {
    if (list instanceof RandomAccess) {
        // use first version here
    } else {
        // use other version here
    }
}

EDIT: I guess the generics-stuff doesn't really add any value here.. Oh well. :)

How to query GROUP BY Month in a Year

For MS SQL you can do this.

    select  CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+ 
CAST(DATEPART(YEAR, DateTyme) as VARCHAR) as 'Date' from #temp
    group by Name, CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+
 CAST(DATEPART(YEAR, DateTyme) as VARCHAR) 

Disable LESS-CSS Overwriting calc()

Here's a cross-browser less mixin for using CSS's calc with any property:

.calc(@prop; @val) {
  @{prop}: calc(~'@{val}');
  @{prop}: -moz-calc(~'@{val}');
  @{prop}: -webkit-calc(~'@{val}');
  @{prop}: -o-calc(~'@{val}');
}

Example usage:

.calc(width; "100% - 200px");

And the CSS that's output:

width: calc(100% - 200px);
width: -moz-calc(100% - 200px);
width: -webkit-calc(100% - 200px);
width: -o-calc(100% - 200px);

A codepen of this example: http://codepen.io/patrickberkeley/pen/zobdp

Javascript validation: Block special characters

It would help you... assume you have a form with "formname" form and a text box with "txt" name. then you can use following code to allow only aphanumeric values

var checkString = document.formname.txt.value;
if (checkString != "") {
    if ( /[^A-Za-z\d]/.test(checkString)) {
        alert("Please enter only letter and numeric characters");
        document.formname.txt.focus();
        return (false);
    }
}

How to create a directory and give permission in single command

Just to expand on and improve some of the above answers:

First, I'll check the mkdir man page for GNU Coreutils 8.26 -- it gives us this information about the option '-m' and '-p' (can also be given as --mode=MODE and --parents, respectively):

...set[s] file mode (as in chmod), not a=rwx - umask

...no error if existing, make parent directories as needed

The statements are vague and unclear in my opinion. But basically, it says that you can make the directory with permissions specified by "chmod numeric notation" (octals) or you can go "the other way" and use a/your umask.

Side note: I say "the other way" since the umask value is actually exactly what it sounds like -- a mask, hiding/removing permissions rather than "granting" them as with chmod's numeric octal notation.

You can execute the shell-builtin command umask to see what your 3-digit umask is; for me, it's 022. This means that when I execute mkdir yodirectory in a given folder (say, mahome) and stat it, I'll get some output resembling this:

               755                   richard:richard         /mahome/yodirectory
 #          permissions                 user:group      what I just made (yodirectory),
 # (owner,group,others--in that order)                 where I made it (i.e. in mahome)
 # 

Now, to add just a tiny bit more about those octal permissions. When you make a directory, "your system" take your default directory perms' [which applies for new directories (its value should 777)] and slaps on yo(u)mask, effectively hiding some of those perms'. My umask is 022--now if we "subtract" 022 from 777 (technically subtracting is an oversimplification and not always correct - we are actually turning off perms or masking them)...we get 755 as stated (or "statted") earlier.

We can omit the '0' in front of the 3-digit octal (so they don't have to be 4 digits) since in our case we didn't want (or rather didn't mention) any sticky bits, setuids or setgids (you might want to look into those, btw, they might be useful since you are going 777). So in other words, 0777 implies (or is equivalent to) 777 (but 777 isn't necessarily equivalent to 0777--since 777 only specifies the permissions, not the setuids, setgids, etc.)

Now, to apply this to your question in a broader sense--you have (already) got a few options. All the answers above work (at least according to my coreutils). But you may (or are pretty likely to) run into problems with the above solutions when you want to create subdirectories (nested directories) with 777 permissions all at once. Specifically, if I do the following in mahome with a umask of 022:

mkdir -m 777 -p yodirectory/yostuff/mastuffinyostuff
# OR (you can swap 777 for 0777 if you so desire, outcome will be the same)
install -d -m 777 -p yodirectory/yostuff/mastuffinyostuff

I will get perms 755 for both yodirectory and yostuff, with only 777 perms for mastuffinyostuff. So it appears that the umask is all that's slapped on yodirectory and yostuff...to get around this we can use a subshell:

( umask 000 && mkdir -p yodirectory/yostuff/mastuffinyostuff )

and that's it. 777 perms for yostuff, mastuffinyostuff, and yodirectory.

How to reload the datatable(jquery) data?

To reload the table data from Ajax data source, use the following function:

dataTable.ajax.reload()

Where dataTable is the variable used to create the table.

var dataTable = $('#your_table_id').DataTable({
     ajax: "URL"
});

See ajax.reload() for more information.

WebDriver - wait for element using Java

Above wait statement is a nice example of Explicit wait.

As Explicit waits are intelligent waits that are confined to a particular web element(as mentioned in above x-path).

By Using explicit waits you are basically telling WebDriver at the max it is to wait for X units(whatever you have given as timeoutInSeconds) of time before it gives up.

How to split a python string on new line characters

? Splitting line in Python:

Have you tried using str.splitlines() method?:

From the docs:

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']

Which delimiters are considered?

This method uses the universal newlines approach to splitting lines.

The main difference between Python 2.X and Python 3.X is that the former uses the universal newlines approach to splitting lines, so "\r", "\n", and "\r\n" are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:

  • \v or \x0b: Line Tabulation (added in Python 3.2).
  • \f or \x0c: Form Feed (added in Python 3.2).
  • \x1c: File Separator.
  • \x1d: Group Separator.
  • \x1e: Record Separator.
  • \x85: Next Line (C1 Control Code).
  • \u2028: Line Separator.
  • \u2029: Paragraph Separator.

splitlines VS split:

Unlike str.split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> ''.splitlines()
[]

>>> 'Line 1\n'.splitlines()
['Line 1']

While str.split('\n') returns:

>>> ''.split('\n')
['']

>>> 'Line 1\n'.split('\n')
['Line 1', '']

?? Removing additional whitespace:

If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines(), you could use str.splitlines() together with str.strip():

>>> [str.strip() for str in 'Line 1  \n  \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']

? Removing empty strings (''):

Lastly, if you want to filter out the empty strings from the resulting list, you could use filter():

>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']

>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']

Additional comment regarding the original question:

As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

Is there a MySQL option/feature to track history of changes to records?

You could create triggers to solve this. Here is a tutorial to do so (archived link).

Setting constraints and rules in the database is better than writing special code to handle the same task since it will prevent another developer from writing a different query that bypasses all of the special code and could leave your database with poor data integrity.

For a long time I was copying info to another table using a script since MySQL didn’t support triggers at the time. I have now found this trigger to be more effective at keeping track of everything.

This trigger will copy an old value to a history table if it is changed when someone edits a row. Editor ID and last mod are stored in the original table every time someone edits that row; the time corresponds to when it was changed to its current form.

DROP TRIGGER IF EXISTS history_trigger $$

CREATE TRIGGER history_trigger
BEFORE UPDATE ON clients
    FOR EACH ROW
    BEGIN
        IF OLD.first_name != NEW.first_name
        THEN
                INSERT INTO history_clients
                    (
                        client_id    ,
                        col          ,
                        value        ,
                        user_id      ,
                        edit_time
                    )
                    VALUES
                    (
                        NEW.client_id,
                        'first_name',
                        NEW.first_name,
                        NEW.editor_id,
                        NEW.last_mod
                    );
        END IF;

        IF OLD.last_name != NEW.last_name
        THEN
                INSERT INTO history_clients
                    (
                        client_id    ,
                        col          ,
                        value        ,
                        user_id      ,
                        edit_time
                    )
                    VALUES
                    (
                        NEW.client_id,
                        'last_name',
                        NEW.last_name,
                        NEW.editor_id,
                        NEW.last_mod
                    );
        END IF;

    END;
$$

Another solution would be to keep an Revision field and update this field on save. You could decide that the max is the newest revision, or that 0 is the most recent row. That's up to you.

How do I get the XML SOAP request of an WCF Web service request?

I just wanted to add this to the answer from Kimberly. Maybe it can save some time and avoid compilation errors for not implementing all methods that the IEndpointBehaviour interface requires.

Best regards

Nicki

    /*
        // This is just to illustrate how it can be implemented on an imperative declarared binding, channel and client.

        string url = "SOME WCF URL";
        BasicHttpBinding wsBinding = new BasicHttpBinding();                
        EndpointAddress endpointAddress = new EndpointAddress(url);

        ChannelFactory<ISomeService> channelFactory = new ChannelFactory<ISomeService>(wsBinding, endpointAddress);
        channelFactory.Endpoint.Behaviors.Add(new InspectorBehavior());
        ISomeService client = channelFactory.CreateChannel();
    */    
        public class InspectorBehavior : IEndpointBehavior
        {
            public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
            {
                // No implementation necessary  
            }

            public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
                clientRuntime.MessageInspectors.Add(new MyMessageInspector());
            }

            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {
                // No implementation necessary  
            }

            public void Validate(ServiceEndpoint endpoint)
            {
                // No implementation necessary  
            }  

        }

        public class MyMessageInspector : IClientMessageInspector
        {
            public object BeforeSendRequest(ref Message request, IClientChannel channel)
            {
                // Do something with the SOAP request
                string request = request.ToString();
                return null;
            }

            public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                // Do something with the SOAP reply
                string replySoap = reply.ToString();
            }
        }

What does upstream mean in nginx?

If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.

Convert array of integers to comma-separated string

int[] arr = new int[5] {1,2,3,4,5};

You can use Linq for it

String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);

Handling Dialogs in WPF with MVVM

I had the same situation and wrapped up the MessageBox into a designer invisible control. The details are in my blog

http://geekswithblogs.net/mukapu/archive/2010/03/12/user-prompts-messagebox-with-mvvm.aspx

The same can be extended to any modal dialogs, file browse control etc.

ARM compilation error, VFP registers used by executable, not object file

Also the error can be solved by adding several flags, like -marm -mthumb-interwork. It was helpful for me to avoid this same error.

How to see my Eclipse version?

Go to Help -> About Eclipse Sdk

enter image description here

enter image description here

Unique on a dataframe with only selected columns

Using unique():

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))    
dat[row.names(unique(dat[,c("id", "id2")])),]

How to enable C# 6.0 feature in Visual Studio 2013?

It is possible to use full C# 6.0 features in Visual Studio 2013 if you have Resharper.
You have to enable Resharper Build and voilá! In Resharper Options -> Build - enable Resharper Build and in "Use MSBuild.exe version" choose "Latest Installed"

This way Resharper is going to build your C# 6.0 Projects and will also not underline C# 6.0 code as invalid.

I am also using this although I have Visual Studio 2015 because:

  1. Unit Tests in Resharper don't work for me with Visual Studio 2015 for some reason
  2. VS 2015 uses a lot more memory than VS 2013.

I am putting this here, as I was looking for a solution for this problem for some time now and maybe it will help someone else.

How to print a two dimensional array?

Something like this that i answer in another question

public class Snippet {
    public static void main(String[] args) {
        int [][]lst = new int[10][10];

        for (int[] arr : lst) {
            System.out.println(Arrays.toString(arr));
        }
    }

}

Display only 10 characters of a long string?

Try this :)

var mystring = "How do I get a long text string";
mystring = mystring.substring(0,10);
alert(mystring);

How to update a claim in ASP.NET Identity?

when I use MVC5, and add the claim here.

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(PATAUserManager manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        userIdentity.AddClaim(new Claim(ClaimTypes.Role, this.Role));

        return userIdentity;
    }

when I'm check the claim result in the SignInAsync function,i can't get the role value use anyway. But...

after this request finished, I can access Role in other action(anther request).

 var userWithClaims = (ClaimsPrincipal)User;
        Claim CRole = userWithClaims.Claims.First(c => c.Type == ClaimTypes.Role);

so, i think maybe asynchronous cause the IEnumerable updated behind the process.

How to create python bytes object from long hex string?

You can do this with the hex codec. ie:

>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'

In Python script, how do I set PYTHONPATH?

If you put sys.path.append('dir/to/path') without check it is already added, you could generate a long list in sys.path. For that, I recommend this:

import sys
import os # if you want this directory

try:
    sys.path.index('/dir/path') # Or os.getcwd() for this directory
except ValueError:
    sys.path.append('/dir/path') # Or os.getcwd() for this directory

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

Removing trailing newline character from fgets() input

size_t ln = strlen(name) - 1;
if (*name && name[ln] == '\n') 
    name[ln] = '\0';

Differences between fork and exec

The prime example to understand the fork() and exec() concept is the shell,the command interpreter program that users typically executes after logging into the system.The shell interprets the first word of command line as a command name

For many commands,the shell forks and the child process execs the command associated with the name treating the remaining words on the command line as parameters to the command.

The shell allows three types of commands. First, a command can be an executable file that contains object code produced by compilation of source code (a C program for example). Second, a command can be an executable file that contains a sequence of shell command lines. Finally, a command can be an internal shell command.(instead of an executable file ex->cd,ls etc.)

How to grant remote access to MySQL for a whole subnet?

mysql> GRANT ALL ON *.* to root@'192.168.1.%' IDENTIFIED BY 'your-root-password';  

The wildcard character is a "%" instead of an "*"

Insertion Sort vs. Selection Sort

selection -selecting a particular item(the lowest) and swap it with the i(no of iteration)th element. (i.e,first,second,third.......) hence,making the sorted list on one side.

insertion- comparing first with second compare third with second & first compare fourth with third,second & first......

a link where all sortings are compared

Want custom title / image / description in facebook share link from a flash app

You can't, it just doesn't support it.

I have to ask, why those calculations need to happen Only inside the flash app?

You have to be navigating to an URL that clearly relates to the metadata you get from the flash app. Otherwise how would the flash app know to get the values depending on the URL you hit.

Options are:

  • calculate on the page: When serving the page you need to do those same calculations on the server and send the title, etc on the page metadata.
  • send metadata in the query string to your site: If you really must keep the calculation off the server, an alternative trick would be to explicitly set the metadata in the URL the users click to get to your site from Facebook. When processing the page, you just copy it back in the metadata sections (don't forget to encode appropriately). That is clearly limited because of the url size restrictions.
  • send the calculation results in the query string to your site: if those calculations just give you a couple numbers that are used in the metadata, you could include just that in the query string of the URL the users click back to your site. That's more likely to not give you problems with URL sizes.

re

Why is this upvoted? It's wrong. You CAN - it IS supported to add custom title, description and images to your share. I do it all the time. – Dustin Fineout 3 hours ago

The OP very clearly stated that he already knew you could serve that from a page, but wanted to pass the values directly to facebook (not through the target page).

Besides, note that I gave 3 different options to work around the issue, one of which is what you posted as an answer later. Your option isn't how the OP was trying to do it, its just a workaround because of facebook restrictions.

Finally, just as I did, you should mention that particular solution is flawed because you can easily hit the URL size restriction.

The backend version is not supported to design database diagrams or tables

This is commonly reported as an error due to using the wrong version of SSMS(Sql Server Management Studio). Use the version designed for your database version. You can use the command select @@version to check which version of sql server you are actually using. This version is reported in a way that is easier to interpret than that shown in the Help About in SSMS.


Using a newer version of SSMS than your database is generally error-free, i.e. backward compatible.

All com.android.support libraries must use the exact same version specification

After searching and combining answers, 2018 version of this question and it worked for me:

1) On navigation tab change it to project view

2) Navigate to [YourProjectName]/.idea/libraries/

3) Delete all files starting with Gradle__com_android_support_[libraryName]

E.g: Gradle__com_android_support_animated_vector_drawable_26_0_0.xml

4) In your gradle file define a variable and use it to replace version number like ${variableName}

Def variable:

ext {
    support_library_version = '28.0.0' //use the version of choice
}

Use variable:

implementation "com.android.support:cardview-v7:${support_library_version}"

example gradle:

dependencies {
    ext {
        support_library_version = '28.0.0' //use the version of choice
    }

    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation "com.android.support:animated-vector-drawable:${support_library_version}"
    implementation "com.android.support:appcompat-v7:${support_library_version}"
    implementation "com.android.support:customtabs:${support_library_version}"
    implementation "com.android.support:cardview-v7:${support_library_version}"
    implementation "com.android.support:support-compat:${support_library_version}"
    implementation "com.android.support:support-v4:${support_library_version}"
    implementation "com.android.support:support-core-utils:${support_library_version}"
    implementation "com.android.support:support-core-ui:${support_library_version}"
    implementation "com.android.support:support-fragment:${support_library_version}"
    implementation "com.android.support:support-media-compat:${support_library_version}"
    implementation "com.android.support:appcompat-v7:${support_library_version}"
    implementation "com.android.support:recyclerview-v7:${support_library_version}"
    implementation "com.android.support:design:${support_library_version}"

}

How to retrieve field names from temporary table (SQL Server 2008)

To use information_schema and not collide with other sessions:

select * 
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name =
    object_name(
        object_id('tempdb..#test'),
        (select database_id from sys.databases where name = 'tempdb'))

Readably print out a python dict() sorted by key

I wrote the following function to print dicts, lists, and tuples in a more readable format:

def printplus(obj):
    """
    Pretty-prints the object passed in.

    """
    # Dict
    if isinstance(obj, dict):
        for k, v in sorted(obj.items()):
            print u'{0}: {1}'.format(k, v)

    # List or tuple            
    elif isinstance(obj, list) or isinstance(obj, tuple):
        for x in obj:
            print x

    # Other
    else:
        print obj

Example usage in iPython:

>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> printplus(dict_example)
a: 3
b: 2
c: 1

>>> tuple_example = ((1, 2), (3, 4), (5, 6), (7, 8))
>>> printplus(tuple_example)
(1, 2)
(3, 4)
(5, 6)
(7, 8)

how to File.listFiles in alphabetical order?

The listFiles method, with or without a filter does not guarantee any order.

It does, however, return an array, which you can sort with Arrays.sort().

File[] files = XMLDirectory.listFiles(filter_xml_files);
Arrays.sort(files);
for(File _xml_file : files) {
    ...
}

This works because File is a comparable class, which by default sorts pathnames lexicographically. If you want to sort them differently, you can define your own comparator.

If you prefer using Streams:

A more modern approach is the following. To print the names of all files in a given directory, in alphabetical order, do:

Files.list(Paths.get(dirName)).sorted().forEach(System.out::println)

Replace the System.out::println with whatever you want to do with the file names. If you want only filenames that end with "xml" just do:

Files.list(Paths.get(dirName))
    .filter(s -> s.toString().endsWith(".xml"))
    .sorted()
    .forEach(System.out::println)

Again, replace the printing with whichever processing operation you would like.

jquery-ui-dialog - How to hook into dialog close event

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

"close" property of dialog gives the close event for the same.

PHP Notice: Undefined offset: 1 with array when reading data

Change

$data[$parts[0]] = $parts[1];

to

if ( ! isset($parts[1])) {
   $parts[1] = null;
}

$data[$parts[0]] = $parts[1];

or simply:

$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;

Not every line of your file has a colon in it and therefore explode on it returns an array of size 1.

According to php.net possible return values from explode:

Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

Importing CSV File to Google Maps

We have now (jan2017) a csv layer import inside Google Maps itself.enter image description here

Google Maps > "Your Places" > "Open in My Maps"

Eclipse will not open due to environment variables

Ok...Ok... Don't worry i am also ruined by this error and fatal and when i got it i was so serious even i was not giving an attention to other work, but i got it, Simply first of all copy this code and paste in your system variable Under path ...

C:\Program Files;C:\Winnt;C:\Winnt\System32;C:\Program Files\Java\jre6\bin\javaw.exe

Now copy the "jre" folder from your path like i have have "jre" under this path

            C:\Program Files\Java

and paste it in your eclipse folder means where your eclipse.exe file is placed. like i have my eclipse set up in this location

    F:\Softwares\LANGUAGES SOFTEARE\Android Setup\eclipse

So inside the eclipse Folder paste the "jre" FOLDER . If you have "jre6" then rename it as "jre"....and run your eclipse you will got the solution...

   //<<<<<<<<<<<<<<----------------------------->>>>>>>>>>>>>>>>>>>                 

OTHER SOLUTION: 2

If the problem could't solve with the above steps, then follow these steps

  1. Copy the folder "jre" from your Java path like C:\Program Files\Java\jre6* etc, and paste it in your eclipse directory(Where is your eclipse available)
  2. Go to eclipse.ini file , open it up.
  3. Change the directory of your javaw.exe file like

-vmF:\Softwares\LANGUAGES SOFTEARE\Android Setup\eclipse Indigo version 32 Bit\jre\bin/javaw.exe

Now this time when you will start eclipse it will search for javaw.exe, so it will search the path in the eclipse.ini, as it is now in the same folder so, it will start the javaw.exe and it will start working.

If You still have any query you can ask it again, just go on my profile and find out my email id. because i love stack overflow forum, and it made me a programmer.*

How can I apply styles to multiple classes at once?

just seperate the class name with a comma.

.a,.b{
your styles
}

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

In our case, the problem was with federated signon between a .Net site and ADFS. When redirecting to the ADFS endpoint the wctx parameter needed all three parameters for the WSFederationAuthenticationModule.CreateSignInRequest method: rm, id, and ru

Thanks to Guillaume Raymond for the tip to check the URL parameters!

Increment variable value by 1 ( shell programming)

you can use bc as it can also do floats

var=$(echo "1+2"|bc)

What is Java Servlet?

I think servlet is basically a java class which acts as a middle way between HTTP request and HTTP response.Servlet is also used to make your web page dynamic. Suppose for example if you want to redirect to another web page on server then you have to use servlets. Another important thing is that servlet can run on localhost as well as a web browser.

Python convert tuple to string

Easiest way would be to use join like this:

>>> myTuple = ['h','e','l','l','o']
>>> ''.join(myTuple)
'hello'

This works because your delimiter is essentially nothing, not even a blank space: ''.

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

How to make graphics with transparent background in R using ggplot2?

Updated with the theme() function, ggsave() and the code for the legend background:

df <- data.frame(y = d, x = 1, group = rep(c("gr1", "gr2"), 50))
p <- ggplot(df) +
  stat_boxplot(aes(x = x, y = y, color = group), 
               fill = "transparent" # for the inside of the boxplot
  ) 

Fastest way is using using rect, as all the rectangle elements inherit from rect:

p <- p +
  theme(
        rect = element_rect(fill = "transparent") # all rectangles
      )
    p

More controlled way is to use options of theme:

p <- p +
  theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
  )
p

To save (this last step is important):

ggsave(p, filename = "tr_tst2.png",  bg = "transparent")

Using Docker-Compose, how to execute multiple commands

Another idea:

If, as in this case, you build the container just place a startup script in it and run this with command. Or mount the startup script as volume.

jQuery selector regular expressions

James Padolsey created a wonderful filter that allows regex to be used for selection.

Say you have the following div:

<div class="asdf">

Padolsey's :regex filter can select it like so:

$("div:regex(class, .*sd.*)")

Also, check the official documentation on selectors.

UPDATE: : syntax Deprecation JQuery 3.0

Since jQuery.expr[':'] used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:

jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
    return function (elem) {
        var matchParams = expression.split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                    matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels, '')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    }
});

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

How to Calculate Execution Time of a Code Snippet in C++

just a simple class that benchmark the codeblock :

using namespace std::chrono;

class benchmark {
  public:
  time_point<high_resolution_clock>  t0, t1;
  unsigned int *d;
  benchmark(unsigned int *res) : d(res) { 
                 t0 = high_resolution_clock::now();
  }
  ~benchmark() { t1 = high_resolution_clock::now();
                  milliseconds dur = duration_cast<milliseconds>(t1 - t0);
                  *d = dur.count();
  }
};
// simple usage 
// unsigned int t;
// { // put the code in a block
//  benchmark bench(&t);
//  // ...
//  // code to benchmark
// }
// HERE the t contains time in milliseconds

// one way to use it can be :
#define BENCH(TITLE,CODEBLOCK) \
  unsigned int __time__##__LINE__ = 0;  \
  { benchmark bench(&__time__##__LINE__); \
      CODEBLOCK \
  } \
  printf("%s took %d ms\n",(TITLE),__time__##__LINE__);


int main(void) {
  BENCH("TITLE",{
    for(int n = 0; n < testcount; n++ )
      int a = n % 3;
  });
  return 0;
}

Android Studio installation on Windows 7 fails, no JDK found

With the last update of Androd Studio I have two versions of the IDE's launcher

One is called studio.exe and the other studio64.exe they are both on:

C:\Users\myUserName\AppData\Local\Android\android-studio\bin

You have to launch the one that matches your Java version 64 or 32 bit

Why is Node.js single threaded?

The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.

Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).

The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.

In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.

If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

jQuery remove selected option from this

This should do the trick:

$('#some_select_box').click(function() {
  $('option:selected', this ).remove();
});

Pad with leading zeros

An integer value is a mathematical representation of a number and is ignorant of leading zeroes.

You can get a string with leading zeroes like this:

someNumber.ToString("00000000")

How to remove not null constraint in sql server using query

Remove column constraint: not null to null

ALTER TABLE test ALTER COLUMN column_01 DROP NOT NULL;

Using a BOOL property

Apple recommends for stylistic purposes.If you write this code:

@property (nonatomic,assign) BOOL working;

Then you can not use [object isWorking].
It will show an error. But if you use below code means

@property (assign,getter=isWorking) BOOL working;

So you can use [object isWorking] .

What is the difference between Class.getResource() and ClassLoader.getResource()?

I tried reading from input1.txt which was inside one of my packages together with the class which was trying to read it.

The following works:

String fileName = FileTransferClient.class.getResource("input1.txt").getPath();

System.out.println(fileName);

BufferedReader bufferedTextIn = new BufferedReader(new FileReader(fileName));

The most important part was to call getPath() if you want the correct path name in String format. DO NOT USE toString() because it will add some extra formatting text which will TOTALLY MESS UP the fileName (you can try it and see the print out).

Spent 2 hours debugging this... :(